babylon.max.js 3.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Color3 = (function () {
  67. /**
  68. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  69. */
  70. function Color3(r, g, b) {
  71. if (r === void 0) { r = 0; }
  72. if (g === void 0) { g = 0; }
  73. if (b === void 0) { b = 0; }
  74. this.r = r;
  75. this.g = g;
  76. this.b = b;
  77. }
  78. /**
  79. * Returns a string with the Color3 current values.
  80. */
  81. Color3.prototype.toString = function () {
  82. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  83. };
  84. /**
  85. * Returns the string "Color3".
  86. */
  87. Color3.prototype.getClassName = function () {
  88. return "Color3";
  89. };
  90. /**
  91. * Returns the Color3 hash code.
  92. */
  93. Color3.prototype.getHashCode = function () {
  94. var hash = this.r || 0;
  95. hash = (hash * 397) ^ (this.g || 0);
  96. hash = (hash * 397) ^ (this.b || 0);
  97. return hash;
  98. };
  99. // Operators
  100. /**
  101. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  102. * Returns the Color3.
  103. */
  104. Color3.prototype.toArray = function (array, index) {
  105. if (index === undefined) {
  106. index = 0;
  107. }
  108. array[index] = this.r;
  109. array[index + 1] = this.g;
  110. array[index + 2] = this.b;
  111. return this;
  112. };
  113. /**
  114. * Returns a new Color4 object from the current Color3 and the passed alpha.
  115. */
  116. Color3.prototype.toColor4 = function (alpha) {
  117. if (alpha === void 0) { alpha = 1; }
  118. return new Color4(this.r, this.g, this.b, alpha);
  119. };
  120. /**
  121. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  122. */
  123. Color3.prototype.asArray = function () {
  124. var result = [];
  125. this.toArray(result, 0);
  126. return result;
  127. };
  128. /**
  129. * Returns the luminance value (float).
  130. */
  131. Color3.prototype.toLuminance = function () {
  132. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  133. };
  134. /**
  135. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  136. * Returns this new object.
  137. */
  138. Color3.prototype.multiply = function (otherColor) {
  139. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  140. };
  141. /**
  142. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  143. * Returns the current Color3.
  144. */
  145. Color3.prototype.multiplyToRef = function (otherColor, result) {
  146. result.r = this.r * otherColor.r;
  147. result.g = this.g * otherColor.g;
  148. result.b = this.b * otherColor.b;
  149. return this;
  150. };
  151. /**
  152. * Boolean : True if the rgb values are equal to the passed ones.
  153. */
  154. Color3.prototype.equals = function (otherColor) {
  155. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  156. };
  157. /**
  158. * Boolean : True if the rgb values are equal to the passed ones.
  159. */
  160. Color3.prototype.equalsFloats = function (r, g, b) {
  161. return this.r === r && this.g === g && this.b === b;
  162. };
  163. /**
  164. * Multiplies in place each rgb value by scale.
  165. * Returns the updated Color3.
  166. */
  167. Color3.prototype.scale = function (scale) {
  168. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  169. };
  170. /**
  171. * Multiplies the rgb values by scale and stores the result into "result".
  172. * Returns the unmodified current Color3.
  173. */
  174. Color3.prototype.scaleToRef = function (scale, result) {
  175. result.r = this.r * scale;
  176. result.g = this.g * scale;
  177. result.b = this.b * scale;
  178. return this;
  179. };
  180. /**
  181. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  182. */
  183. Color3.prototype.add = function (otherColor) {
  184. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  185. };
  186. /**
  187. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  188. * Returns the unmodified current Color3.
  189. */
  190. Color3.prototype.addToRef = function (otherColor, result) {
  191. result.r = this.r + otherColor.r;
  192. result.g = this.g + otherColor.g;
  193. result.b = this.b + otherColor.b;
  194. return this;
  195. };
  196. /**
  197. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  198. */
  199. Color3.prototype.subtract = function (otherColor) {
  200. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  201. };
  202. /**
  203. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  204. * Returns the unmodified current Color3.
  205. */
  206. Color3.prototype.subtractToRef = function (otherColor, result) {
  207. result.r = this.r - otherColor.r;
  208. result.g = this.g - otherColor.g;
  209. result.b = this.b - otherColor.b;
  210. return this;
  211. };
  212. /**
  213. * Returns a new Color3 copied the current one.
  214. */
  215. Color3.prototype.clone = function () {
  216. return new Color3(this.r, this.g, this.b);
  217. };
  218. /**
  219. * Copies the rgb values from the source in the current Color3.
  220. * Returns the updated Color3.
  221. */
  222. Color3.prototype.copyFrom = function (source) {
  223. this.r = source.r;
  224. this.g = source.g;
  225. this.b = source.b;
  226. return this;
  227. };
  228. /**
  229. * Updates the Color3 rgb values from the passed floats.
  230. * Returns the Color3.
  231. */
  232. Color3.prototype.copyFromFloats = function (r, g, b) {
  233. this.r = r;
  234. this.g = g;
  235. this.b = b;
  236. return this;
  237. };
  238. /**
  239. * Updates the Color3 rgb values from the passed floats.
  240. * Returns the Color3.
  241. */
  242. Color3.prototype.set = function (r, g, b) {
  243. return this.copyFromFloats(r, g, b);
  244. };
  245. /**
  246. * Returns the Color3 hexadecimal code as a string.
  247. */
  248. Color3.prototype.toHexString = function () {
  249. var intR = (this.r * 255) | 0;
  250. var intG = (this.g * 255) | 0;
  251. var intB = (this.b * 255) | 0;
  252. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  253. };
  254. /**
  255. * Returns a new Color3 converted to linear space.
  256. */
  257. Color3.prototype.toLinearSpace = function () {
  258. var convertedColor = new Color3();
  259. this.toLinearSpaceToRef(convertedColor);
  260. return convertedColor;
  261. };
  262. /**
  263. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  264. * Returns the unmodified Color3.
  265. */
  266. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  267. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  268. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  269. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  270. return this;
  271. };
  272. /**
  273. * Returns a new Color3 converted to gamma space.
  274. */
  275. Color3.prototype.toGammaSpace = function () {
  276. var convertedColor = new Color3();
  277. this.toGammaSpaceToRef(convertedColor);
  278. return convertedColor;
  279. };
  280. /**
  281. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  282. * Returns the unmodified Color3.
  283. */
  284. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  285. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  286. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  287. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  288. return this;
  289. };
  290. // Statics
  291. /**
  292. * Creates a new Color3 from the string containing valid hexadecimal values.
  293. */
  294. Color3.FromHexString = function (hex) {
  295. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  296. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  297. return new Color3(0, 0, 0);
  298. }
  299. var r = parseInt(hex.substring(1, 3), 16);
  300. var g = parseInt(hex.substring(3, 5), 16);
  301. var b = parseInt(hex.substring(5, 7), 16);
  302. return Color3.FromInts(r, g, b);
  303. };
  304. /**
  305. * Creates a new Vector3 from the startind index of the passed array.
  306. */
  307. Color3.FromArray = function (array, offset) {
  308. if (offset === void 0) { offset = 0; }
  309. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  310. };
  311. /**
  312. * Creates a new Color3 from integer values ( < 256).
  313. */
  314. Color3.FromInts = function (r, g, b) {
  315. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  316. };
  317. /**
  318. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  319. */
  320. Color3.Lerp = function (start, end, amount) {
  321. var r = start.r + ((end.r - start.r) * amount);
  322. var g = start.g + ((end.g - start.g) * amount);
  323. var b = start.b + ((end.b - start.b) * amount);
  324. return new Color3(r, g, b);
  325. };
  326. Color3.Red = function () { return new Color3(1, 0, 0); };
  327. Color3.Green = function () { return new Color3(0, 1, 0); };
  328. Color3.Blue = function () { return new Color3(0, 0, 1); };
  329. Color3.Black = function () { return new Color3(0, 0, 0); };
  330. Color3.White = function () { return new Color3(1, 1, 1); };
  331. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  332. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  333. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  334. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  335. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  336. return Color3;
  337. }());
  338. BABYLON.Color3 = Color3;
  339. var Color4 = (function () {
  340. /**
  341. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  342. */
  343. function Color4(r, g, b, a) {
  344. this.r = r;
  345. this.g = g;
  346. this.b = b;
  347. this.a = a;
  348. }
  349. // Operators
  350. /**
  351. * Adds in place the passed Color4 values to the current Color4.
  352. * Returns the updated Color4.
  353. */
  354. Color4.prototype.addInPlace = function (right) {
  355. this.r += right.r;
  356. this.g += right.g;
  357. this.b += right.b;
  358. this.a += right.a;
  359. return this;
  360. };
  361. /**
  362. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  363. */
  364. Color4.prototype.asArray = function () {
  365. var result = [];
  366. this.toArray(result, 0);
  367. return result;
  368. };
  369. /**
  370. * Stores from the starting index in the passed array the Color4 successive values.
  371. * Returns the Color4.
  372. */
  373. Color4.prototype.toArray = function (array, index) {
  374. if (index === undefined) {
  375. index = 0;
  376. }
  377. array[index] = this.r;
  378. array[index + 1] = this.g;
  379. array[index + 2] = this.b;
  380. array[index + 3] = this.a;
  381. return this;
  382. };
  383. /**
  384. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  385. */
  386. Color4.prototype.add = function (right) {
  387. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  388. };
  389. /**
  390. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  391. */
  392. Color4.prototype.subtract = function (right) {
  393. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  394. };
  395. /**
  396. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  397. * Returns the Color4.
  398. */
  399. Color4.prototype.subtractToRef = function (right, result) {
  400. result.r = this.r - right.r;
  401. result.g = this.g - right.g;
  402. result.b = this.b - right.b;
  403. result.a = this.a - right.a;
  404. return this;
  405. };
  406. /**
  407. * Creates a new Color4 with the current Color4 values multiplied by scale.
  408. */
  409. Color4.prototype.scale = function (scale) {
  410. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  411. };
  412. /**
  413. * Multiplies the current Color4 values by scale and stores the result in "result".
  414. * Returns the Color4.
  415. */
  416. Color4.prototype.scaleToRef = function (scale, result) {
  417. result.r = this.r * scale;
  418. result.g = this.g * scale;
  419. result.b = this.b * scale;
  420. result.a = this.a * scale;
  421. return this;
  422. };
  423. /**
  424. * Multipy an RGBA Color4 value by another and return a new Color4 object
  425. * @param color The Color4 (RGBA) value to multiply by
  426. * @returns A new Color4.
  427. */
  428. Color4.prototype.multiply = function (color) {
  429. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  430. };
  431. /**
  432. * Multipy an RGBA Color4 value by another and push the result in a reference value
  433. * @param color The Color4 (RGBA) value to multiply by
  434. * @param result The Color4 (RGBA) to fill the result in
  435. * @returns the result Color4.
  436. */
  437. Color4.prototype.multiplyToRef = function (color, result) {
  438. result.r = this.r * color.r;
  439. result.g = this.g * color.g;
  440. result.b = this.b * color.b;
  441. result.a = this.a * color.a;
  442. return result;
  443. };
  444. /**
  445. * Returns a string with the Color4 values.
  446. */
  447. Color4.prototype.toString = function () {
  448. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  449. };
  450. /**
  451. * Returns the string "Color4"
  452. */
  453. Color4.prototype.getClassName = function () {
  454. return "Color4";
  455. };
  456. /**
  457. * Return the Color4 hash code as a number.
  458. */
  459. Color4.prototype.getHashCode = function () {
  460. var hash = this.r || 0;
  461. hash = (hash * 397) ^ (this.g || 0);
  462. hash = (hash * 397) ^ (this.b || 0);
  463. hash = (hash * 397) ^ (this.a || 0);
  464. return hash;
  465. };
  466. /**
  467. * Creates a new Color4 copied from the current one.
  468. */
  469. Color4.prototype.clone = function () {
  470. return new Color4(this.r, this.g, this.b, this.a);
  471. };
  472. /**
  473. * Copies the passed Color4 values into the current one.
  474. * Returns the updated Color4.
  475. */
  476. Color4.prototype.copyFrom = function (source) {
  477. this.r = source.r;
  478. this.g = source.g;
  479. this.b = source.b;
  480. this.a = source.a;
  481. return this;
  482. };
  483. /**
  484. * Copies the passed float values into the current one.
  485. * Returns the updated Color4.
  486. */
  487. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  488. this.r = r;
  489. this.g = g;
  490. this.b = b;
  491. this.a = a;
  492. return this;
  493. };
  494. /**
  495. * Copies the passed float values into the current one.
  496. * Returns the updated Color4.
  497. */
  498. Color4.prototype.set = function (r, g, b, a) {
  499. return this.copyFromFloats(r, g, b, a);
  500. };
  501. /**
  502. * Returns a string containing the hexadecimal Color4 code.
  503. */
  504. Color4.prototype.toHexString = function () {
  505. var intR = (this.r * 255) | 0;
  506. var intG = (this.g * 255) | 0;
  507. var intB = (this.b * 255) | 0;
  508. var intA = (this.a * 255) | 0;
  509. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  510. };
  511. // Statics
  512. /**
  513. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  514. */
  515. Color4.FromHexString = function (hex) {
  516. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  517. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  518. return new Color4(0.0, 0.0, 0.0, 0.0);
  519. }
  520. var r = parseInt(hex.substring(1, 3), 16);
  521. var g = parseInt(hex.substring(3, 5), 16);
  522. var b = parseInt(hex.substring(5, 7), 16);
  523. var a = parseInt(hex.substring(7, 9), 16);
  524. return Color4.FromInts(r, g, b, a);
  525. };
  526. /**
  527. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  528. */
  529. Color4.Lerp = function (left, right, amount) {
  530. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  531. Color4.LerpToRef(left, right, amount, result);
  532. return result;
  533. };
  534. /**
  535. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  536. */
  537. Color4.LerpToRef = function (left, right, amount, result) {
  538. result.r = left.r + (right.r - left.r) * amount;
  539. result.g = left.g + (right.g - left.g) * amount;
  540. result.b = left.b + (right.b - left.b) * amount;
  541. result.a = left.a + (right.a - left.a) * amount;
  542. };
  543. /**
  544. * Creates a new Color4 from the starting index element of the passed array.
  545. */
  546. Color4.FromArray = function (array, offset) {
  547. if (offset === void 0) { offset = 0; }
  548. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  549. };
  550. /**
  551. * Creates a new Color4 from the passed integers ( < 256 ).
  552. */
  553. Color4.FromInts = function (r, g, b, a) {
  554. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  555. };
  556. Color4.CheckColors4 = function (colors, count) {
  557. // Check if color3 was used
  558. if (colors.length === count * 3) {
  559. var colors4 = [];
  560. for (var index = 0; index < colors.length; index += 3) {
  561. var newIndex = (index / 3) * 4;
  562. colors4[newIndex] = colors[index];
  563. colors4[newIndex + 1] = colors[index + 1];
  564. colors4[newIndex + 2] = colors[index + 2];
  565. colors4[newIndex + 3] = 1.0;
  566. }
  567. return colors4;
  568. }
  569. return colors;
  570. };
  571. return Color4;
  572. }());
  573. BABYLON.Color4 = Color4;
  574. var Vector2 = (function () {
  575. /**
  576. * Creates a new Vector2 from the passed x and y coordinates.
  577. */
  578. function Vector2(x, y) {
  579. this.x = x;
  580. this.y = y;
  581. }
  582. /**
  583. * Returns a string with the Vector2 coordinates.
  584. */
  585. Vector2.prototype.toString = function () {
  586. return "{X: " + this.x + " Y:" + this.y + "}";
  587. };
  588. /**
  589. * Returns the string "Vector2"
  590. */
  591. Vector2.prototype.getClassName = function () {
  592. return "Vector2";
  593. };
  594. /**
  595. * Returns the Vector2 hash code as a number.
  596. */
  597. Vector2.prototype.getHashCode = function () {
  598. var hash = this.x || 0;
  599. hash = (hash * 397) ^ (this.y || 0);
  600. return hash;
  601. };
  602. // Operators
  603. /**
  604. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  605. * Returns the Vector2.
  606. */
  607. Vector2.prototype.toArray = function (array, index) {
  608. if (index === void 0) { index = 0; }
  609. array[index] = this.x;
  610. array[index + 1] = this.y;
  611. return this;
  612. };
  613. /**
  614. * Returns a new array with 2 elements : the Vector2 coordinates.
  615. */
  616. Vector2.prototype.asArray = function () {
  617. var result = [];
  618. this.toArray(result, 0);
  619. return result;
  620. };
  621. /**
  622. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  623. * Returns the updated Vector2.
  624. */
  625. Vector2.prototype.copyFrom = function (source) {
  626. this.x = source.x;
  627. this.y = source.y;
  628. return this;
  629. };
  630. /**
  631. * Sets the Vector2 coordinates with the passed floats.
  632. * Returns the updated Vector2.
  633. */
  634. Vector2.prototype.copyFromFloats = function (x, y) {
  635. this.x = x;
  636. this.y = y;
  637. return this;
  638. };
  639. /**
  640. * Sets the Vector2 coordinates with the passed floats.
  641. * Returns the updated Vector2.
  642. */
  643. Vector2.prototype.set = function (x, y) {
  644. return this.copyFromFloats(x, y);
  645. };
  646. /**
  647. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  648. */
  649. Vector2.prototype.add = function (otherVector) {
  650. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  651. };
  652. /**
  653. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  654. * Returns the Vector2.
  655. */
  656. Vector2.prototype.addToRef = function (otherVector, result) {
  657. result.x = this.x + otherVector.x;
  658. result.y = this.y + otherVector.y;
  659. return this;
  660. };
  661. /**
  662. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  663. * Returns the updated Vector2.
  664. */
  665. Vector2.prototype.addInPlace = function (otherVector) {
  666. this.x += otherVector.x;
  667. this.y += otherVector.y;
  668. return this;
  669. };
  670. /**
  671. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  672. */
  673. Vector2.prototype.addVector3 = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  678. */
  679. Vector2.prototype.subtract = function (otherVector) {
  680. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  681. };
  682. /**
  683. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  684. * Returns the Vector2.
  685. */
  686. Vector2.prototype.subtractToRef = function (otherVector, result) {
  687. result.x = this.x - otherVector.x;
  688. result.y = this.y - otherVector.y;
  689. return this;
  690. };
  691. /**
  692. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  693. * Returns the updated Vector2.
  694. */
  695. Vector2.prototype.subtractInPlace = function (otherVector) {
  696. this.x -= otherVector.x;
  697. this.y -= otherVector.y;
  698. return this;
  699. };
  700. /**
  701. * Multiplies in place the current Vector2 coordinates by the passed ones.
  702. * Returns the updated Vector2.
  703. */
  704. Vector2.prototype.multiplyInPlace = function (otherVector) {
  705. this.x *= otherVector.x;
  706. this.y *= otherVector.y;
  707. return this;
  708. };
  709. /**
  710. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  711. */
  712. Vector2.prototype.multiply = function (otherVector) {
  713. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  714. };
  715. /**
  716. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  717. * Returns the Vector2.
  718. */
  719. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  720. result.x = this.x * otherVector.x;
  721. result.y = this.y * otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  726. */
  727. Vector2.prototype.multiplyByFloats = function (x, y) {
  728. return new Vector2(this.x * x, this.y * y);
  729. };
  730. /**
  731. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  732. */
  733. Vector2.prototype.divide = function (otherVector) {
  734. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  735. };
  736. /**
  737. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  738. * Returns the Vector2.
  739. */
  740. Vector2.prototype.divideToRef = function (otherVector, result) {
  741. result.x = this.x / otherVector.x;
  742. result.y = this.y / otherVector.y;
  743. return this;
  744. };
  745. /**
  746. * Returns a new Vector2 with current Vector2 negated coordinates.
  747. */
  748. Vector2.prototype.negate = function () {
  749. return new Vector2(-this.x, -this.y);
  750. };
  751. /**
  752. * Multiply the Vector2 coordinates by scale.
  753. * Returns the updated Vector2.
  754. */
  755. Vector2.prototype.scaleInPlace = function (scale) {
  756. this.x *= scale;
  757. this.y *= scale;
  758. return this;
  759. };
  760. /**
  761. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  762. */
  763. Vector2.prototype.scale = function (scale) {
  764. return new Vector2(this.x * scale, this.y * scale);
  765. };
  766. /**
  767. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  768. */
  769. Vector2.prototype.equals = function (otherVector) {
  770. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  771. };
  772. /**
  773. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  774. */
  775. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  776. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  777. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  778. };
  779. // Properties
  780. /**
  781. * Returns the vector length (float).
  782. */
  783. Vector2.prototype.length = function () {
  784. return Math.sqrt(this.x * this.x + this.y * this.y);
  785. };
  786. /**
  787. * Returns the vector squared length (float);
  788. */
  789. Vector2.prototype.lengthSquared = function () {
  790. return (this.x * this.x + this.y * this.y);
  791. };
  792. // Methods
  793. /**
  794. * Normalize the vector.
  795. * Returns the updated Vector2.
  796. */
  797. Vector2.prototype.normalize = function () {
  798. var len = this.length();
  799. if (len === 0)
  800. return this;
  801. var num = 1.0 / len;
  802. this.x *= num;
  803. this.y *= num;
  804. return this;
  805. };
  806. /**
  807. * Returns a new Vector2 copied from the Vector2.
  808. */
  809. Vector2.prototype.clone = function () {
  810. return new Vector2(this.x, this.y);
  811. };
  812. // Statics
  813. /**
  814. * Returns a new Vector2(0, 0)
  815. */
  816. Vector2.Zero = function () {
  817. return new Vector2(0, 0);
  818. };
  819. /**
  820. * Returns a new Vector2 set from the passed index element of the passed array or Float32Array.
  821. */
  822. Vector2.FromArray = function (array, offset) {
  823. if (offset === void 0) { offset = 0; }
  824. return new Vector2(array[offset], array[offset + 1]);
  825. };
  826. /**
  827. * Sets "result" from the passed index element of the passed array or Float32Array.
  828. * Returns the Vector2.
  829. */
  830. Vector2.FromArrayToRef = function (array, offset, result) {
  831. result.x = array[offset];
  832. result.y = array[offset + 1];
  833. };
  834. /**
  835. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  836. */
  837. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  838. var squared = amount * amount;
  839. var cubed = amount * squared;
  840. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  841. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  842. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  843. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  844. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  845. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  846. return new Vector2(x, y);
  847. };
  848. /**
  849. * 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".
  850. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  851. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  852. */
  853. Vector2.Clamp = function (value, min, max) {
  854. var x = value.x;
  855. x = (x > max.x) ? max.x : x;
  856. x = (x < min.x) ? min.x : x;
  857. var y = value.y;
  858. y = (y > max.y) ? max.y : y;
  859. y = (y < min.y) ? min.y : y;
  860. return new Vector2(x, y);
  861. };
  862. /**
  863. * Returns a new Vecto2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  864. */
  865. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  866. var squared = amount * amount;
  867. var cubed = amount * squared;
  868. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  869. var part2 = (-2.0 * cubed) + (3.0 * squared);
  870. var part3 = (cubed - (2.0 * squared)) + amount;
  871. var part4 = cubed - squared;
  872. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  873. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  874. return new Vector2(x, y);
  875. };
  876. /**
  877. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  878. */
  879. Vector2.Lerp = function (start, end, amount) {
  880. var x = start.x + ((end.x - start.x) * amount);
  881. var y = start.y + ((end.y - start.y) * amount);
  882. return new Vector2(x, y);
  883. };
  884. /**
  885. * Returns the dot product (float) of the vector "left" and the vector "right".
  886. */
  887. Vector2.Dot = function (left, right) {
  888. return left.x * right.x + left.y * right.y;
  889. };
  890. /**
  891. * Returns a new Vector2 equal to the normalized passed vector.
  892. */
  893. Vector2.Normalize = function (vector) {
  894. var newVector = vector.clone();
  895. newVector.normalize();
  896. return newVector;
  897. };
  898. /**
  899. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  900. */
  901. Vector2.Minimize = function (left, right) {
  902. var x = (left.x < right.x) ? left.x : right.x;
  903. var y = (left.y < right.y) ? left.y : right.y;
  904. return new Vector2(x, y);
  905. };
  906. /**
  907. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  908. */
  909. Vector2.Maximize = function (left, right) {
  910. var x = (left.x > right.x) ? left.x : right.x;
  911. var y = (left.y > right.y) ? left.y : right.y;
  912. return new Vector2(x, y);
  913. };
  914. /**
  915. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  916. */
  917. Vector2.Transform = function (vector, transformation) {
  918. var r = Vector2.Zero();
  919. Vector2.TransformToRef(vector, transformation, r);
  920. return r;
  921. };
  922. /**
  923. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  924. */
  925. Vector2.TransformToRef = function (vector, transformation, result) {
  926. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  927. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  928. result.x = x;
  929. result.y = y;
  930. };
  931. /**
  932. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  933. */
  934. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  935. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  936. var sign = a < 0 ? -1 : 1;
  937. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  938. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  939. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  940. };
  941. /**
  942. * Returns the distance (float) between the vectors "value1" and "value2".
  943. */
  944. Vector2.Distance = function (value1, value2) {
  945. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  946. };
  947. /**
  948. * Returns the squared distance (float) between the vectors "value1" and "value2".
  949. */
  950. Vector2.DistanceSquared = function (value1, value2) {
  951. var x = value1.x - value2.x;
  952. var y = value1.y - value2.y;
  953. return (x * x) + (y * y);
  954. };
  955. /**
  956. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  957. */
  958. Vector2.Center = function (value1, value2) {
  959. var center = value1.add(value2);
  960. center.scaleInPlace(0.5);
  961. return center;
  962. };
  963. /**
  964. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  965. */
  966. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  967. var l2 = Vector2.DistanceSquared(segA, segB);
  968. if (l2 === 0.0) {
  969. return Vector2.Distance(p, segA);
  970. }
  971. var v = segB.subtract(segA);
  972. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  973. var proj = segA.add(v.multiplyByFloats(t, t));
  974. return Vector2.Distance(p, proj);
  975. };
  976. return Vector2;
  977. }());
  978. BABYLON.Vector2 = Vector2;
  979. var Vector3 = (function () {
  980. /**
  981. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  982. * A Vector3 is the main object used in 3D geometry.
  983. * It can represent etiher the coordinates of a point the space, either a direction.
  984. */
  985. function Vector3(x, y, z) {
  986. this.x = x;
  987. this.y = y;
  988. this.z = z;
  989. }
  990. /**
  991. * Returns a string with the Vector3 coordinates.
  992. */
  993. Vector3.prototype.toString = function () {
  994. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  995. };
  996. /**
  997. * Returns the string "Vector3"
  998. */
  999. Vector3.prototype.getClassName = function () {
  1000. return "Vector3";
  1001. };
  1002. /**
  1003. * Returns the Vector hash code.
  1004. */
  1005. Vector3.prototype.getHashCode = function () {
  1006. var hash = this.x || 0;
  1007. hash = (hash * 397) ^ (this.y || 0);
  1008. hash = (hash * 397) ^ (this.z || 0);
  1009. return hash;
  1010. };
  1011. // Operators
  1012. /**
  1013. * Returns a new array with three elements : the coordinates the Vector3.
  1014. */
  1015. Vector3.prototype.asArray = function () {
  1016. var result = [];
  1017. this.toArray(result, 0);
  1018. return result;
  1019. };
  1020. /**
  1021. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1022. * Returns the Vector3.
  1023. */
  1024. Vector3.prototype.toArray = function (array, index) {
  1025. if (index === void 0) { index = 0; }
  1026. array[index] = this.x;
  1027. array[index + 1] = this.y;
  1028. array[index + 2] = this.z;
  1029. return this;
  1030. };
  1031. /**
  1032. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1033. */
  1034. Vector3.prototype.toQuaternion = function () {
  1035. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1036. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1037. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1038. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1039. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1040. var cosy = Math.cos(this.y * 0.5);
  1041. var siny = Math.sin(this.y * 0.5);
  1042. result.x = coszMinusx * siny;
  1043. result.y = -sinzMinusx * siny;
  1044. result.z = sinxPlusz * cosy;
  1045. result.w = cosxPlusz * cosy;
  1046. return result;
  1047. };
  1048. /**
  1049. * Adds the passed vector to the current Vector3.
  1050. * Returns the updated Vector3.
  1051. */
  1052. Vector3.prototype.addInPlace = function (otherVector) {
  1053. this.x += otherVector.x;
  1054. this.y += otherVector.y;
  1055. this.z += otherVector.z;
  1056. return this;
  1057. };
  1058. /**
  1059. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1060. */
  1061. Vector3.prototype.add = function (otherVector) {
  1062. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1063. };
  1064. /**
  1065. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1066. * Returns the current Vector3.
  1067. */
  1068. Vector3.prototype.addToRef = function (otherVector, result) {
  1069. result.x = this.x + otherVector.x;
  1070. result.y = this.y + otherVector.y;
  1071. result.z = this.z + otherVector.z;
  1072. return this;
  1073. };
  1074. /**
  1075. * Subtract the passed vector from the current Vector3.
  1076. * Returns the updated Vector3.
  1077. */
  1078. Vector3.prototype.subtractInPlace = function (otherVector) {
  1079. this.x -= otherVector.x;
  1080. this.y -= otherVector.y;
  1081. this.z -= otherVector.z;
  1082. return this;
  1083. };
  1084. /**
  1085. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1086. */
  1087. Vector3.prototype.subtract = function (otherVector) {
  1088. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1089. };
  1090. /**
  1091. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1092. * Returns the current Vector3.
  1093. */
  1094. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1095. result.x = this.x - otherVector.x;
  1096. result.y = this.y - otherVector.y;
  1097. result.z = this.z - otherVector.z;
  1098. return this;
  1099. };
  1100. /**
  1101. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1102. */
  1103. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1104. return new Vector3(this.x - x, this.y - y, this.z - z);
  1105. };
  1106. /**
  1107. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1108. * Returns the current Vector3.
  1109. */
  1110. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1111. result.x = this.x - x;
  1112. result.y = this.y - y;
  1113. result.z = this.z - z;
  1114. return this;
  1115. };
  1116. /**
  1117. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1118. */
  1119. Vector3.prototype.negate = function () {
  1120. return new Vector3(-this.x, -this.y, -this.z);
  1121. };
  1122. /**
  1123. * Multiplies the Vector3 coordinates by the float "scale".
  1124. * Returns the updated Vector3.
  1125. */
  1126. Vector3.prototype.scaleInPlace = function (scale) {
  1127. this.x *= scale;
  1128. this.y *= scale;
  1129. this.z *= scale;
  1130. return this;
  1131. };
  1132. /**
  1133. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1134. */
  1135. Vector3.prototype.scale = function (scale) {
  1136. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1137. };
  1138. /**
  1139. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1140. * Returns the current Vector3.
  1141. */
  1142. Vector3.prototype.scaleToRef = function (scale, result) {
  1143. result.x = this.x * scale;
  1144. result.y = this.y * scale;
  1145. result.z = this.z * scale;
  1146. return this;
  1147. };
  1148. /**
  1149. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1150. */
  1151. Vector3.prototype.equals = function (otherVector) {
  1152. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1153. };
  1154. /**
  1155. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1156. */
  1157. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1158. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1159. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1160. };
  1161. /**
  1162. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1163. */
  1164. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1165. return this.x === x && this.y === y && this.z === z;
  1166. };
  1167. /**
  1168. * Muliplies the current Vector3 coordinates by the passed ones.
  1169. * Returns the updated Vector3.
  1170. */
  1171. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1172. this.x *= otherVector.x;
  1173. this.y *= otherVector.y;
  1174. this.z *= otherVector.z;
  1175. return this;
  1176. };
  1177. /**
  1178. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1179. */
  1180. Vector3.prototype.multiply = function (otherVector) {
  1181. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1182. };
  1183. /**
  1184. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1185. * Returns the current Vector3.
  1186. */
  1187. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1188. result.x = this.x * otherVector.x;
  1189. result.y = this.y * otherVector.y;
  1190. result.z = this.z * otherVector.z;
  1191. return this;
  1192. };
  1193. /**
  1194. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1195. */
  1196. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1197. return new Vector3(this.x * x, this.y * y, this.z * z);
  1198. };
  1199. /**
  1200. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1201. */
  1202. Vector3.prototype.divide = function (otherVector) {
  1203. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1204. };
  1205. /**
  1206. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1207. * Returns the current Vector3.
  1208. */
  1209. Vector3.prototype.divideToRef = function (otherVector, result) {
  1210. result.x = this.x / otherVector.x;
  1211. result.y = this.y / otherVector.y;
  1212. result.z = this.z / otherVector.z;
  1213. return this;
  1214. };
  1215. /**
  1216. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1217. * Returns the updated Vector3.
  1218. */
  1219. Vector3.prototype.MinimizeInPlace = function (other) {
  1220. if (other.x < this.x)
  1221. this.x = other.x;
  1222. if (other.y < this.y)
  1223. this.y = other.y;
  1224. if (other.z < this.z)
  1225. this.z = other.z;
  1226. return this;
  1227. };
  1228. /**
  1229. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1230. * Returns the updated Vector3.
  1231. */
  1232. Vector3.prototype.MaximizeInPlace = function (other) {
  1233. if (other.x > this.x)
  1234. this.x = other.x;
  1235. if (other.y > this.y)
  1236. this.y = other.y;
  1237. if (other.z > this.z)
  1238. this.z = other.z;
  1239. return this;
  1240. };
  1241. // Properties
  1242. /**
  1243. * Returns the length of the Vector3 (float).
  1244. */
  1245. Vector3.prototype.length = function () {
  1246. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1247. };
  1248. /**
  1249. * Returns the squared length of the Vector3 (float).
  1250. */
  1251. Vector3.prototype.lengthSquared = function () {
  1252. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1253. };
  1254. // Methods
  1255. /**
  1256. * Normalize the current Vector3.
  1257. * Returns the updated Vector3.
  1258. */
  1259. Vector3.prototype.normalize = function () {
  1260. var len = this.length();
  1261. if (len === 0 || len === 1.0)
  1262. return this;
  1263. var num = 1.0 / len;
  1264. this.x *= num;
  1265. this.y *= num;
  1266. this.z *= num;
  1267. return this;
  1268. };
  1269. /**
  1270. * Returns a new Vector3 copied from the current Vector3.
  1271. */
  1272. Vector3.prototype.clone = function () {
  1273. return new Vector3(this.x, this.y, this.z);
  1274. };
  1275. /**
  1276. * Copies the passed vector coordinates to the current Vector3 ones.
  1277. * Returns the updated Vector3.
  1278. */
  1279. Vector3.prototype.copyFrom = function (source) {
  1280. this.x = source.x;
  1281. this.y = source.y;
  1282. this.z = source.z;
  1283. return this;
  1284. };
  1285. /**
  1286. * Copies the passed floats to the current Vector3 coordinates.
  1287. * Returns the updated Vector3.
  1288. */
  1289. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1290. this.x = x;
  1291. this.y = y;
  1292. this.z = z;
  1293. return this;
  1294. };
  1295. /**
  1296. * Copies the passed floats to the current Vector3 coordinates.
  1297. * Returns the updated Vector3.
  1298. */
  1299. Vector3.prototype.set = function (x, y, z) {
  1300. return this.copyFromFloats(x, y, z);
  1301. };
  1302. // Statics
  1303. /**
  1304. *
  1305. */
  1306. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1307. var d0 = Vector3.Dot(vector0, axis) - size;
  1308. var d1 = Vector3.Dot(vector1, axis) - size;
  1309. var s = d0 / (d0 - d1);
  1310. return s;
  1311. };
  1312. /**
  1313. * Returns a new Vector3 set from the index "offset" of the passed array or Float32Array.
  1314. */
  1315. Vector3.FromArray = function (array, offset) {
  1316. if (!offset) {
  1317. offset = 0;
  1318. }
  1319. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1320. };
  1321. /**
  1322. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1323. */
  1324. Vector3.FromFloatArray = function (array, offset) {
  1325. if (!offset) {
  1326. offset = 0;
  1327. }
  1328. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1329. };
  1330. /**
  1331. * Sets the passed vector "result" with the element values from the index "offset" of the passed array or Float32Array.
  1332. */
  1333. Vector3.FromArrayToRef = function (array, offset, result) {
  1334. result.x = array[offset];
  1335. result.y = array[offset + 1];
  1336. result.z = array[offset + 2];
  1337. };
  1338. /**
  1339. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1340. */
  1341. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1342. result.x = array[offset];
  1343. result.y = array[offset + 1];
  1344. result.z = array[offset + 2];
  1345. };
  1346. /**
  1347. * Sets the passed vector "result" with the passed floats.
  1348. */
  1349. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1350. result.x = x;
  1351. result.y = y;
  1352. result.z = z;
  1353. };
  1354. /**
  1355. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1356. */
  1357. Vector3.Zero = function () {
  1358. return new Vector3(0.0, 0.0, 0.0);
  1359. };
  1360. /**
  1361. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1362. */
  1363. Vector3.Up = function () {
  1364. return new Vector3(0.0, 1.0, 0.0);
  1365. };
  1366. /**
  1367. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1368. */
  1369. Vector3.Forward = function () {
  1370. return new Vector3(0.0, 0.0, 1.0);
  1371. };
  1372. /**
  1373. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1374. */
  1375. Vector3.Right = function () {
  1376. return new Vector3(1.0, 0.0, 0.0);
  1377. };
  1378. /**
  1379. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1380. */
  1381. Vector3.Left = function () {
  1382. return new Vector3(-1.0, 0.0, 0.0);
  1383. };
  1384. /**
  1385. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1386. * This method computes tranformed coordinates only, not transformed direction vectors.
  1387. */
  1388. Vector3.TransformCoordinates = function (vector, transformation) {
  1389. var result = Vector3.Zero();
  1390. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1391. return result;
  1392. };
  1393. /**
  1394. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1395. * This method computes tranformed coordinates only, not transformed direction vectors.
  1396. */
  1397. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1398. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1399. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1400. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1401. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1402. result.x = x / w;
  1403. result.y = y / w;
  1404. result.z = z / w;
  1405. };
  1406. /**
  1407. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1408. * This method computes tranformed coordinates only, not transformed direction vectors.
  1409. */
  1410. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1411. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1412. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1413. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1414. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1415. result.x = rx / rw;
  1416. result.y = ry / rw;
  1417. result.z = rz / rw;
  1418. };
  1419. /**
  1420. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1421. * This methods computes transformed normalized direction vectors only.
  1422. */
  1423. Vector3.TransformNormal = function (vector, transformation) {
  1424. var result = Vector3.Zero();
  1425. Vector3.TransformNormalToRef(vector, transformation, result);
  1426. return result;
  1427. };
  1428. /**
  1429. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1430. * This methods computes transformed normalized direction vectors only.
  1431. */
  1432. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1433. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1434. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1435. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1436. result.x = x;
  1437. result.y = y;
  1438. result.z = z;
  1439. };
  1440. /**
  1441. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1442. * This methods computes transformed normalized direction vectors only.
  1443. */
  1444. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1445. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1446. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1447. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1448. };
  1449. /**
  1450. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1451. */
  1452. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1453. var squared = amount * amount;
  1454. var cubed = amount * squared;
  1455. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1456. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1457. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1458. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1459. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1460. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1461. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1462. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1463. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1464. return new Vector3(x, y, z);
  1465. };
  1466. /**
  1467. * 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".
  1468. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1469. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1470. */
  1471. Vector3.Clamp = function (value, min, max) {
  1472. var x = value.x;
  1473. x = (x > max.x) ? max.x : x;
  1474. x = (x < min.x) ? min.x : x;
  1475. var y = value.y;
  1476. y = (y > max.y) ? max.y : y;
  1477. y = (y < min.y) ? min.y : y;
  1478. var z = value.z;
  1479. z = (z > max.z) ? max.z : z;
  1480. z = (z < min.z) ? min.z : z;
  1481. return new Vector3(x, y, z);
  1482. };
  1483. /**
  1484. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1485. */
  1486. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1487. var squared = amount * amount;
  1488. var cubed = amount * squared;
  1489. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1490. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1491. var part3 = (cubed - (2.0 * squared)) + amount;
  1492. var part4 = cubed - squared;
  1493. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1494. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1495. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1496. return new Vector3(x, y, z);
  1497. };
  1498. /**
  1499. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1500. */
  1501. Vector3.Lerp = function (start, end, amount) {
  1502. var result = new Vector3(0, 0, 0);
  1503. Vector3.LerpToRef(start, end, amount, result);
  1504. return result;
  1505. };
  1506. /**
  1507. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1508. */
  1509. Vector3.LerpToRef = function (start, end, amount, result) {
  1510. result.x = start.x + ((end.x - start.x) * amount);
  1511. result.y = start.y + ((end.y - start.y) * amount);
  1512. result.z = start.z + ((end.z - start.z) * amount);
  1513. };
  1514. /**
  1515. * Returns the dot product (float) between the vectors "left" and "right".
  1516. */
  1517. Vector3.Dot = function (left, right) {
  1518. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1519. };
  1520. /**
  1521. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1522. * The cross product is then orthogonal to both "left" and "right".
  1523. */
  1524. Vector3.Cross = function (left, right) {
  1525. var result = Vector3.Zero();
  1526. Vector3.CrossToRef(left, right, result);
  1527. return result;
  1528. };
  1529. /**
  1530. * Sets the passed vector "result" with the cross product of "left" and "right".
  1531. * The cross product is then orthogonal to both "left" and "right".
  1532. */
  1533. Vector3.CrossToRef = function (left, right, result) {
  1534. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1535. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1536. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1537. result.copyFrom(MathTmp.Vector3[0]);
  1538. };
  1539. /**
  1540. * Returns a new Vector3 as the normalization of the passed vector.
  1541. */
  1542. Vector3.Normalize = function (vector) {
  1543. var result = Vector3.Zero();
  1544. Vector3.NormalizeToRef(vector, result);
  1545. return result;
  1546. };
  1547. /**
  1548. * Sets the passed vector "result" with the normalization of the passed first vector.
  1549. */
  1550. Vector3.NormalizeToRef = function (vector, result) {
  1551. result.copyFrom(vector);
  1552. result.normalize();
  1553. };
  1554. Vector3.Project = function (vector, world, transform, viewport) {
  1555. var cw = viewport.width;
  1556. var ch = viewport.height;
  1557. var cx = viewport.x;
  1558. var cy = viewport.y;
  1559. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1560. 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);
  1561. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1562. world.multiplyToRef(transform, matrix);
  1563. matrix.multiplyToRef(viewportMatrix, matrix);
  1564. return Vector3.TransformCoordinates(vector, matrix);
  1565. };
  1566. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1567. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1568. world.multiplyToRef(transform, matrix);
  1569. matrix.invert();
  1570. source.x = source.x / viewportWidth * 2 - 1;
  1571. source.y = -(source.y / viewportHeight * 2 - 1);
  1572. var vector = Vector3.TransformCoordinates(source, matrix);
  1573. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1574. if (MathTools.WithinEpsilon(num, 1.0)) {
  1575. vector = vector.scale(1.0 / num);
  1576. }
  1577. return vector;
  1578. };
  1579. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1580. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1581. world.multiplyToRef(view, matrix);
  1582. matrix.multiplyToRef(projection, matrix);
  1583. matrix.invert();
  1584. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1585. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1586. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1587. if (MathTools.WithinEpsilon(num, 1.0)) {
  1588. vector = vector.scale(1.0 / num);
  1589. }
  1590. return vector;
  1591. };
  1592. Vector3.Minimize = function (left, right) {
  1593. var min = left.clone();
  1594. min.MinimizeInPlace(right);
  1595. return min;
  1596. };
  1597. Vector3.Maximize = function (left, right) {
  1598. var max = left.clone();
  1599. max.MaximizeInPlace(right);
  1600. return max;
  1601. };
  1602. /**
  1603. * Returns the distance (float) between the vectors "value1" and "value2".
  1604. */
  1605. Vector3.Distance = function (value1, value2) {
  1606. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1607. };
  1608. /**
  1609. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1610. */
  1611. Vector3.DistanceSquared = function (value1, value2) {
  1612. var x = value1.x - value2.x;
  1613. var y = value1.y - value2.y;
  1614. var z = value1.z - value2.z;
  1615. return (x * x) + (y * y) + (z * z);
  1616. };
  1617. /**
  1618. * Returns a new Vector3 located at the center between "value1" and "value2".
  1619. */
  1620. Vector3.Center = function (value1, value2) {
  1621. var center = value1.add(value2);
  1622. center.scaleInPlace(0.5);
  1623. return center;
  1624. };
  1625. /**
  1626. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1627. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1628. * to something in order to rotate it from its local system to the given target system.
  1629. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1630. * Returns a new Vector3.
  1631. */
  1632. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1633. var rotation = Vector3.Zero();
  1634. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1635. return rotation;
  1636. };
  1637. /**
  1638. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1639. */
  1640. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1641. var quat = MathTmp.Quaternion[0];
  1642. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1643. quat.toEulerAnglesToRef(ref);
  1644. };
  1645. return Vector3;
  1646. }());
  1647. BABYLON.Vector3 = Vector3;
  1648. //Vector4 class created for EulerAngle class conversion to Quaternion
  1649. var Vector4 = (function () {
  1650. /**
  1651. * Creates a Vector4 object from the passed floats.
  1652. */
  1653. function Vector4(x, y, z, w) {
  1654. this.x = x;
  1655. this.y = y;
  1656. this.z = z;
  1657. this.w = w;
  1658. }
  1659. /**
  1660. * Returns the string with the Vector4 coordinates.
  1661. */
  1662. Vector4.prototype.toString = function () {
  1663. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1664. };
  1665. /**
  1666. * Returns the string "Vector4".
  1667. */
  1668. Vector4.prototype.getClassName = function () {
  1669. return "Vector4";
  1670. };
  1671. /**
  1672. * Returns the Vector4 hash code.
  1673. */
  1674. Vector4.prototype.getHashCode = function () {
  1675. var hash = this.x || 0;
  1676. hash = (hash * 397) ^ (this.y || 0);
  1677. hash = (hash * 397) ^ (this.z || 0);
  1678. hash = (hash * 397) ^ (this.w || 0);
  1679. return hash;
  1680. };
  1681. // Operators
  1682. /**
  1683. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1684. */
  1685. Vector4.prototype.asArray = function () {
  1686. var result = [];
  1687. this.toArray(result, 0);
  1688. return result;
  1689. };
  1690. /**
  1691. * Populates the passed array from the passed index with the Vector4 coordinates.
  1692. * Returns the Vector4.
  1693. */
  1694. Vector4.prototype.toArray = function (array, index) {
  1695. if (index === undefined) {
  1696. index = 0;
  1697. }
  1698. array[index] = this.x;
  1699. array[index + 1] = this.y;
  1700. array[index + 2] = this.z;
  1701. array[index + 3] = this.w;
  1702. return this;
  1703. };
  1704. /**
  1705. * Adds the passed vector to the current Vector4.
  1706. * Returns the updated Vector4.
  1707. */
  1708. Vector4.prototype.addInPlace = function (otherVector) {
  1709. this.x += otherVector.x;
  1710. this.y += otherVector.y;
  1711. this.z += otherVector.z;
  1712. this.w += otherVector.w;
  1713. return this;
  1714. };
  1715. /**
  1716. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1717. */
  1718. Vector4.prototype.add = function (otherVector) {
  1719. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1720. };
  1721. /**
  1722. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1723. * Returns the current Vector4.
  1724. */
  1725. Vector4.prototype.addToRef = function (otherVector, result) {
  1726. result.x = this.x + otherVector.x;
  1727. result.y = this.y + otherVector.y;
  1728. result.z = this.z + otherVector.z;
  1729. result.w = this.w + otherVector.w;
  1730. return this;
  1731. };
  1732. /**
  1733. * Subtract in place the passed vector from the current Vector4.
  1734. * Returns the updated Vector4.
  1735. */
  1736. Vector4.prototype.subtractInPlace = function (otherVector) {
  1737. this.x -= otherVector.x;
  1738. this.y -= otherVector.y;
  1739. this.z -= otherVector.z;
  1740. this.w -= otherVector.w;
  1741. return this;
  1742. };
  1743. /**
  1744. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1745. */
  1746. Vector4.prototype.subtract = function (otherVector) {
  1747. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1748. };
  1749. /**
  1750. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1751. * Returns the current Vector4.
  1752. */
  1753. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1754. result.x = this.x - otherVector.x;
  1755. result.y = this.y - otherVector.y;
  1756. result.z = this.z - otherVector.z;
  1757. result.w = this.w - otherVector.w;
  1758. return this;
  1759. };
  1760. /**
  1761. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1762. */
  1763. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1764. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1765. };
  1766. /**
  1767. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1768. * Returns the current Vector4.
  1769. */
  1770. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1771. result.x = this.x - x;
  1772. result.y = this.y - y;
  1773. result.z = this.z - z;
  1774. result.w = this.w - w;
  1775. return this;
  1776. };
  1777. /**
  1778. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1779. */
  1780. Vector4.prototype.negate = function () {
  1781. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1782. };
  1783. /**
  1784. * Multiplies the current Vector4 coordinates by scale (float).
  1785. * Returns the updated Vector4.
  1786. */
  1787. Vector4.prototype.scaleInPlace = function (scale) {
  1788. this.x *= scale;
  1789. this.y *= scale;
  1790. this.z *= scale;
  1791. this.w *= scale;
  1792. return this;
  1793. };
  1794. /**
  1795. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1796. */
  1797. Vector4.prototype.scale = function (scale) {
  1798. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1799. };
  1800. /**
  1801. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1802. * Returns the current Vector4.
  1803. */
  1804. Vector4.prototype.scaleToRef = function (scale, result) {
  1805. result.x = this.x * scale;
  1806. result.y = this.y * scale;
  1807. result.z = this.z * scale;
  1808. result.w = this.w * scale;
  1809. return this;
  1810. };
  1811. /**
  1812. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1813. */
  1814. Vector4.prototype.equals = function (otherVector) {
  1815. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1816. };
  1817. /**
  1818. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1819. */
  1820. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1821. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1822. return otherVector
  1823. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1824. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1825. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1826. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1827. };
  1828. /**
  1829. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1830. */
  1831. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1832. return this.x === x && this.y === y && this.z === z && this.w === w;
  1833. };
  1834. /**
  1835. * Multiplies in place the current Vector4 by the passed one.
  1836. * Returns the updated Vector4.
  1837. */
  1838. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1839. this.x *= otherVector.x;
  1840. this.y *= otherVector.y;
  1841. this.z *= otherVector.z;
  1842. this.w *= otherVector.w;
  1843. return this;
  1844. };
  1845. /**
  1846. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1847. */
  1848. Vector4.prototype.multiply = function (otherVector) {
  1849. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1850. };
  1851. /**
  1852. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1853. * Returns the current Vector4.
  1854. */
  1855. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1856. result.x = this.x * otherVector.x;
  1857. result.y = this.y * otherVector.y;
  1858. result.z = this.z * otherVector.z;
  1859. result.w = this.w * otherVector.w;
  1860. return this;
  1861. };
  1862. /**
  1863. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1864. */
  1865. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1866. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1867. };
  1868. /**
  1869. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1870. */
  1871. Vector4.prototype.divide = function (otherVector) {
  1872. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1873. };
  1874. /**
  1875. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1876. * Returns the current Vector4.
  1877. */
  1878. Vector4.prototype.divideToRef = function (otherVector, result) {
  1879. result.x = this.x / otherVector.x;
  1880. result.y = this.y / otherVector.y;
  1881. result.z = this.z / otherVector.z;
  1882. result.w = this.w / otherVector.w;
  1883. return this;
  1884. };
  1885. /**
  1886. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1887. */
  1888. Vector4.prototype.MinimizeInPlace = function (other) {
  1889. if (other.x < this.x)
  1890. this.x = other.x;
  1891. if (other.y < this.y)
  1892. this.y = other.y;
  1893. if (other.z < this.z)
  1894. this.z = other.z;
  1895. if (other.w < this.w)
  1896. this.w = other.w;
  1897. return this;
  1898. };
  1899. /**
  1900. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1901. */
  1902. Vector4.prototype.MaximizeInPlace = function (other) {
  1903. if (other.x > this.x)
  1904. this.x = other.x;
  1905. if (other.y > this.y)
  1906. this.y = other.y;
  1907. if (other.z > this.z)
  1908. this.z = other.z;
  1909. if (other.w > this.w)
  1910. this.w = other.w;
  1911. return this;
  1912. };
  1913. // Properties
  1914. /**
  1915. * Returns the Vector4 length (float).
  1916. */
  1917. Vector4.prototype.length = function () {
  1918. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1919. };
  1920. /**
  1921. * Returns the Vector4 squared length (float).
  1922. */
  1923. Vector4.prototype.lengthSquared = function () {
  1924. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1925. };
  1926. // Methods
  1927. /**
  1928. * Normalizes in place the Vector4.
  1929. * Returns the updated Vector4.
  1930. */
  1931. Vector4.prototype.normalize = function () {
  1932. var len = this.length();
  1933. if (len === 0)
  1934. return this;
  1935. var num = 1.0 / len;
  1936. this.x *= num;
  1937. this.y *= num;
  1938. this.z *= num;
  1939. this.w *= num;
  1940. return this;
  1941. };
  1942. /**
  1943. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1944. */
  1945. Vector4.prototype.toVector3 = function () {
  1946. return new Vector3(this.x, this.y, this.z);
  1947. };
  1948. /**
  1949. * Returns a new Vector4 copied from the current one.
  1950. */
  1951. Vector4.prototype.clone = function () {
  1952. return new Vector4(this.x, this.y, this.z, this.w);
  1953. };
  1954. /**
  1955. * Updates the current Vector4 with the passed one coordinates.
  1956. * Returns the updated Vector4.
  1957. */
  1958. Vector4.prototype.copyFrom = function (source) {
  1959. this.x = source.x;
  1960. this.y = source.y;
  1961. this.z = source.z;
  1962. this.w = source.w;
  1963. return this;
  1964. };
  1965. /**
  1966. * Updates the current Vector4 coordinates with the passed floats.
  1967. * Returns the updated Vector4.
  1968. */
  1969. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1970. this.x = x;
  1971. this.y = y;
  1972. this.z = z;
  1973. this.w = w;
  1974. return this;
  1975. };
  1976. /**
  1977. * Updates the current Vector4 coordinates with the passed floats.
  1978. * Returns the updated Vector4.
  1979. */
  1980. Vector4.prototype.set = function (x, y, z, w) {
  1981. return this.copyFromFloats(x, y, z, w);
  1982. };
  1983. // Statics
  1984. /**
  1985. * Returns a new Vector4 set from the starting index of the passed array.
  1986. */
  1987. Vector4.FromArray = function (array, offset) {
  1988. if (!offset) {
  1989. offset = 0;
  1990. }
  1991. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1992. };
  1993. /**
  1994. * Updates the passed vector "result" from the starting index of the passed array.
  1995. */
  1996. Vector4.FromArrayToRef = function (array, offset, result) {
  1997. result.x = array[offset];
  1998. result.y = array[offset + 1];
  1999. result.z = array[offset + 2];
  2000. result.w = array[offset + 3];
  2001. };
  2002. /**
  2003. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2004. */
  2005. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2006. result.x = array[offset];
  2007. result.y = array[offset + 1];
  2008. result.z = array[offset + 2];
  2009. result.w = array[offset + 3];
  2010. };
  2011. /**
  2012. * Updates the passed vector "result" coordinates from the passed floats.
  2013. */
  2014. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2015. result.x = x;
  2016. result.y = y;
  2017. result.z = z;
  2018. result.w = w;
  2019. };
  2020. /**
  2021. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2022. */
  2023. Vector4.Zero = function () {
  2024. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2025. };
  2026. /**
  2027. * Returns a new normalized Vector4 from the passed one.
  2028. */
  2029. Vector4.Normalize = function (vector) {
  2030. var result = Vector4.Zero();
  2031. Vector4.NormalizeToRef(vector, result);
  2032. return result;
  2033. };
  2034. /**
  2035. * Updates the passed vector "result" from the normalization of the passed one.
  2036. */
  2037. Vector4.NormalizeToRef = function (vector, result) {
  2038. result.copyFrom(vector);
  2039. result.normalize();
  2040. };
  2041. Vector4.Minimize = function (left, right) {
  2042. var min = left.clone();
  2043. min.MinimizeInPlace(right);
  2044. return min;
  2045. };
  2046. Vector4.Maximize = function (left, right) {
  2047. var max = left.clone();
  2048. max.MaximizeInPlace(right);
  2049. return max;
  2050. };
  2051. /**
  2052. * Returns the distance (float) between the vectors "value1" and "value2".
  2053. */
  2054. Vector4.Distance = function (value1, value2) {
  2055. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2056. };
  2057. /**
  2058. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2059. */
  2060. Vector4.DistanceSquared = function (value1, value2) {
  2061. var x = value1.x - value2.x;
  2062. var y = value1.y - value2.y;
  2063. var z = value1.z - value2.z;
  2064. var w = value1.w - value2.w;
  2065. return (x * x) + (y * y) + (z * z) + (w * w);
  2066. };
  2067. /**
  2068. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2069. */
  2070. Vector4.Center = function (value1, value2) {
  2071. var center = value1.add(value2);
  2072. center.scaleInPlace(0.5);
  2073. return center;
  2074. };
  2075. /**
  2076. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2077. * This methods computes transformed normalized direction vectors only.
  2078. */
  2079. Vector4.TransformNormal = function (vector, transformation) {
  2080. var result = Vector4.Zero();
  2081. Vector4.TransformNormalToRef(vector, transformation, result);
  2082. return result;
  2083. };
  2084. /**
  2085. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2086. * This methods computes transformed normalized direction vectors only.
  2087. */
  2088. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2089. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2090. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2091. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2092. result.x = x;
  2093. result.y = y;
  2094. result.z = z;
  2095. result.w = vector.w;
  2096. };
  2097. /**
  2098. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2099. * This methods computes transformed normalized direction vectors only.
  2100. */
  2101. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2102. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2103. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2104. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2105. result.w = w;
  2106. };
  2107. return Vector4;
  2108. }());
  2109. BABYLON.Vector4 = Vector4;
  2110. var Size = (function () {
  2111. /**
  2112. * Creates a Size object from the passed width and height (floats).
  2113. */
  2114. function Size(width, height) {
  2115. this.width = width;
  2116. this.height = height;
  2117. }
  2118. // Returns a string with the Size width and height.
  2119. Size.prototype.toString = function () {
  2120. return "{W: " + this.width + ", H: " + this.height + "}";
  2121. };
  2122. /**
  2123. * Returns the string "Size"
  2124. */
  2125. Size.prototype.getClassName = function () {
  2126. return "Size";
  2127. };
  2128. /**
  2129. * Returns the Size hash code.
  2130. */
  2131. Size.prototype.getHashCode = function () {
  2132. var hash = this.width || 0;
  2133. hash = (hash * 397) ^ (this.height || 0);
  2134. return hash;
  2135. };
  2136. /**
  2137. * Updates the current size from the passed one.
  2138. * Returns the updated Size.
  2139. */
  2140. Size.prototype.copyFrom = function (src) {
  2141. this.width = src.width;
  2142. this.height = src.height;
  2143. };
  2144. /**
  2145. * Updates in place the current Size from the passed floats.
  2146. * Returns the updated Size.
  2147. */
  2148. Size.prototype.copyFromFloats = function (width, height) {
  2149. this.width = width;
  2150. this.height = height;
  2151. return this;
  2152. };
  2153. /**
  2154. * Updates in place the current Size from the passed floats.
  2155. * Returns the updated Size.
  2156. */
  2157. Size.prototype.set = function (width, height) {
  2158. return this.copyFromFloats(width, height);
  2159. };
  2160. /**
  2161. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2162. */
  2163. Size.prototype.multiplyByFloats = function (w, h) {
  2164. return new Size(this.width * w, this.height * h);
  2165. };
  2166. /**
  2167. * Returns a new Size copied from the passed one.
  2168. */
  2169. Size.prototype.clone = function () {
  2170. return new Size(this.width, this.height);
  2171. };
  2172. /**
  2173. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2174. */
  2175. Size.prototype.equals = function (other) {
  2176. if (!other) {
  2177. return false;
  2178. }
  2179. return (this.width === other.width) && (this.height === other.height);
  2180. };
  2181. Object.defineProperty(Size.prototype, "surface", {
  2182. /**
  2183. * Returns the surface of the Size : width * height (float).
  2184. */
  2185. get: function () {
  2186. return this.width * this.height;
  2187. },
  2188. enumerable: true,
  2189. configurable: true
  2190. });
  2191. /**
  2192. * Returns a new Size set to (0.0, 0.0)
  2193. */
  2194. Size.Zero = function () {
  2195. return new Size(0.0, 0.0);
  2196. };
  2197. /**
  2198. * Returns a new Size set as the addition result of the current Size and the passed one.
  2199. */
  2200. Size.prototype.add = function (otherSize) {
  2201. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2202. return r;
  2203. };
  2204. /**
  2205. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2206. */
  2207. Size.prototype.subtract = function (otherSize) {
  2208. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2209. return r;
  2210. };
  2211. /**
  2212. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2213. */
  2214. Size.Lerp = function (start, end, amount) {
  2215. var w = start.width + ((end.width - start.width) * amount);
  2216. var h = start.height + ((end.height - start.height) * amount);
  2217. return new Size(w, h);
  2218. };
  2219. return Size;
  2220. }());
  2221. BABYLON.Size = Size;
  2222. var Quaternion = (function () {
  2223. /**
  2224. * Creates a new Quaternion from the passed floats.
  2225. */
  2226. function Quaternion(x, y, z, w) {
  2227. if (x === void 0) { x = 0.0; }
  2228. if (y === void 0) { y = 0.0; }
  2229. if (z === void 0) { z = 0.0; }
  2230. if (w === void 0) { w = 1.0; }
  2231. this.x = x;
  2232. this.y = y;
  2233. this.z = z;
  2234. this.w = w;
  2235. }
  2236. /**
  2237. * Returns a string with the Quaternion coordinates.
  2238. */
  2239. Quaternion.prototype.toString = function () {
  2240. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2241. };
  2242. /**
  2243. * Returns the string "Quaternion".
  2244. */
  2245. Quaternion.prototype.getClassName = function () {
  2246. return "Quaternion";
  2247. };
  2248. /**
  2249. * Returns the Quaternion hash code.
  2250. */
  2251. Quaternion.prototype.getHashCode = function () {
  2252. var hash = this.x || 0;
  2253. hash = (hash * 397) ^ (this.y || 0);
  2254. hash = (hash * 397) ^ (this.z || 0);
  2255. hash = (hash * 397) ^ (this.w || 0);
  2256. return hash;
  2257. };
  2258. /**
  2259. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2260. */
  2261. Quaternion.prototype.asArray = function () {
  2262. return [this.x, this.y, this.z, this.w];
  2263. };
  2264. /**
  2265. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2266. */
  2267. Quaternion.prototype.equals = function (otherQuaternion) {
  2268. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2269. };
  2270. /**
  2271. * Returns a new Quaternion copied from the current one.
  2272. */
  2273. Quaternion.prototype.clone = function () {
  2274. return new Quaternion(this.x, this.y, this.z, this.w);
  2275. };
  2276. /**
  2277. * Updates the current Quaternion from the passed one coordinates.
  2278. * Returns the updated Quaterion.
  2279. */
  2280. Quaternion.prototype.copyFrom = function (other) {
  2281. this.x = other.x;
  2282. this.y = other.y;
  2283. this.z = other.z;
  2284. this.w = other.w;
  2285. return this;
  2286. };
  2287. /**
  2288. * Updates the current Quaternion from the passed float coordinates.
  2289. * Returns the updated Quaterion.
  2290. */
  2291. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2292. this.x = x;
  2293. this.y = y;
  2294. this.z = z;
  2295. this.w = w;
  2296. return this;
  2297. };
  2298. /**
  2299. * Updates the current Quaternion from the passed float coordinates.
  2300. * Returns the updated Quaterion.
  2301. */
  2302. Quaternion.prototype.set = function (x, y, z, w) {
  2303. return this.copyFromFloats(x, y, z, w);
  2304. };
  2305. /**
  2306. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2307. */
  2308. Quaternion.prototype.add = function (other) {
  2309. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2310. };
  2311. /**
  2312. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2313. */
  2314. Quaternion.prototype.subtract = function (other) {
  2315. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2316. };
  2317. /**
  2318. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2319. */
  2320. Quaternion.prototype.scale = function (value) {
  2321. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2322. };
  2323. /**
  2324. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2325. */
  2326. Quaternion.prototype.multiply = function (q1) {
  2327. var result = new Quaternion(0, 0, 0, 1.0);
  2328. this.multiplyToRef(q1, result);
  2329. return result;
  2330. };
  2331. /**
  2332. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2333. * Returns the current Quaternion.
  2334. */
  2335. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2336. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2337. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2338. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2339. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2340. result.copyFromFloats(x, y, z, w);
  2341. return this;
  2342. };
  2343. /**
  2344. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2345. * Returns the updated Quaternion.
  2346. */
  2347. Quaternion.prototype.multiplyInPlace = function (q1) {
  2348. this.multiplyToRef(q1, this);
  2349. return this;
  2350. };
  2351. /**
  2352. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2353. * Returns the current Quaternion.
  2354. */
  2355. Quaternion.prototype.conjugateToRef = function (ref) {
  2356. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2357. return this;
  2358. };
  2359. /**
  2360. * Conjugates in place the current Quaternion.
  2361. * Returns the updated Quaternion.
  2362. */
  2363. Quaternion.prototype.conjugateInPlace = function () {
  2364. this.x *= -1;
  2365. this.y *= -1;
  2366. this.z *= -1;
  2367. return this;
  2368. };
  2369. /**
  2370. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2371. */
  2372. Quaternion.prototype.conjugate = function () {
  2373. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2374. return result;
  2375. };
  2376. /**
  2377. * Returns the Quaternion length (float).
  2378. */
  2379. Quaternion.prototype.length = function () {
  2380. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2381. };
  2382. /**
  2383. * Normalize in place the current Quaternion.
  2384. * Returns the updated Quaternion.
  2385. */
  2386. Quaternion.prototype.normalize = function () {
  2387. var length = 1.0 / this.length();
  2388. this.x *= length;
  2389. this.y *= length;
  2390. this.z *= length;
  2391. this.w *= length;
  2392. return this;
  2393. };
  2394. /**
  2395. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2396. */
  2397. Quaternion.prototype.toEulerAngles = function (order) {
  2398. if (order === void 0) { order = "YZX"; }
  2399. var result = Vector3.Zero();
  2400. this.toEulerAnglesToRef(result, order);
  2401. return result;
  2402. };
  2403. /**
  2404. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2405. * Returns the current Quaternion.
  2406. */
  2407. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2408. if (order === void 0) { order = "YZX"; }
  2409. var qz = this.z;
  2410. var qx = this.x;
  2411. var qy = this.y;
  2412. var qw = this.w;
  2413. var sqw = qw * qw;
  2414. var sqz = qz * qz;
  2415. var sqx = qx * qx;
  2416. var sqy = qy * qy;
  2417. var zAxisY = qy * qz - qx * qw;
  2418. var limit = .4999999;
  2419. if (zAxisY < -limit) {
  2420. result.y = 2 * Math.atan2(qy, qw);
  2421. result.x = Math.PI / 2;
  2422. result.z = 0;
  2423. }
  2424. else if (zAxisY > limit) {
  2425. result.y = 2 * Math.atan2(qy, qw);
  2426. result.x = -Math.PI / 2;
  2427. result.z = 0;
  2428. }
  2429. else {
  2430. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2431. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2432. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2433. }
  2434. return this;
  2435. };
  2436. /**
  2437. * Updates the passed rotation matrix with the current Quaternion values.
  2438. * Returns the current Quaternion.
  2439. */
  2440. Quaternion.prototype.toRotationMatrix = function (result) {
  2441. var xx = this.x * this.x;
  2442. var yy = this.y * this.y;
  2443. var zz = this.z * this.z;
  2444. var xy = this.x * this.y;
  2445. var zw = this.z * this.w;
  2446. var zx = this.z * this.x;
  2447. var yw = this.y * this.w;
  2448. var yz = this.y * this.z;
  2449. var xw = this.x * this.w;
  2450. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2451. result.m[1] = 2.0 * (xy + zw);
  2452. result.m[2] = 2.0 * (zx - yw);
  2453. result.m[3] = 0;
  2454. result.m[4] = 2.0 * (xy - zw);
  2455. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2456. result.m[6] = 2.0 * (yz + xw);
  2457. result.m[7] = 0;
  2458. result.m[8] = 2.0 * (zx + yw);
  2459. result.m[9] = 2.0 * (yz - xw);
  2460. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2461. result.m[11] = 0;
  2462. result.m[12] = 0;
  2463. result.m[13] = 0;
  2464. result.m[14] = 0;
  2465. result.m[15] = 1.0;
  2466. result._markAsUpdated();
  2467. return this;
  2468. };
  2469. /**
  2470. * Updates the current Quaternion from the passed rotation matrix values.
  2471. * Returns the updated Quaternion.
  2472. */
  2473. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2474. Quaternion.FromRotationMatrixToRef(matrix, this);
  2475. return this;
  2476. };
  2477. // Statics
  2478. /**
  2479. * Returns a new Quaternion set from the passed rotation matrix values.
  2480. */
  2481. Quaternion.FromRotationMatrix = function (matrix) {
  2482. var result = new Quaternion();
  2483. Quaternion.FromRotationMatrixToRef(matrix, result);
  2484. return result;
  2485. };
  2486. /**
  2487. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2488. */
  2489. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2490. var data = matrix.m;
  2491. var m11 = data[0], m12 = data[4], m13 = data[8];
  2492. var m21 = data[1], m22 = data[5], m23 = data[9];
  2493. var m31 = data[2], m32 = data[6], m33 = data[10];
  2494. var trace = m11 + m22 + m33;
  2495. var s;
  2496. if (trace > 0) {
  2497. s = 0.5 / Math.sqrt(trace + 1.0);
  2498. result.w = 0.25 / s;
  2499. result.x = (m32 - m23) * s;
  2500. result.y = (m13 - m31) * s;
  2501. result.z = (m21 - m12) * s;
  2502. }
  2503. else if (m11 > m22 && m11 > m33) {
  2504. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2505. result.w = (m32 - m23) / s;
  2506. result.x = 0.25 * s;
  2507. result.y = (m12 + m21) / s;
  2508. result.z = (m13 + m31) / s;
  2509. }
  2510. else if (m22 > m33) {
  2511. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2512. result.w = (m13 - m31) / s;
  2513. result.x = (m12 + m21) / s;
  2514. result.y = 0.25 * s;
  2515. result.z = (m23 + m32) / s;
  2516. }
  2517. else {
  2518. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2519. result.w = (m21 - m12) / s;
  2520. result.x = (m13 + m31) / s;
  2521. result.y = (m23 + m32) / s;
  2522. result.z = 0.25 * s;
  2523. }
  2524. };
  2525. /**
  2526. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2527. */
  2528. Quaternion.Zero = function () {
  2529. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2530. };
  2531. /**
  2532. * Returns a new Quaternion as the inverted current Quaternion.
  2533. */
  2534. Quaternion.Inverse = function (q) {
  2535. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2536. };
  2537. /**
  2538. * Returns the identity Quaternion.
  2539. */
  2540. Quaternion.Identity = function () {
  2541. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2542. };
  2543. Quaternion.IsIdentity = function (quaternion) {
  2544. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2545. };
  2546. /**
  2547. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2548. */
  2549. Quaternion.RotationAxis = function (axis, angle) {
  2550. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2551. };
  2552. /**
  2553. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2554. */
  2555. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2556. var sin = Math.sin(angle / 2);
  2557. axis.normalize();
  2558. result.w = Math.cos(angle / 2);
  2559. result.x = axis.x * sin;
  2560. result.y = axis.y * sin;
  2561. result.z = axis.z * sin;
  2562. return result;
  2563. };
  2564. /**
  2565. * Retuns a new Quaternion set from the starting index of the passed array.
  2566. */
  2567. Quaternion.FromArray = function (array, offset) {
  2568. if (!offset) {
  2569. offset = 0;
  2570. }
  2571. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2572. };
  2573. /**
  2574. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2575. */
  2576. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2577. var q = new Quaternion();
  2578. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2579. return q;
  2580. };
  2581. /**
  2582. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2583. */
  2584. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2585. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2586. var halfRoll = roll * 0.5;
  2587. var halfPitch = pitch * 0.5;
  2588. var halfYaw = yaw * 0.5;
  2589. var sinRoll = Math.sin(halfRoll);
  2590. var cosRoll = Math.cos(halfRoll);
  2591. var sinPitch = Math.sin(halfPitch);
  2592. var cosPitch = Math.cos(halfPitch);
  2593. var sinYaw = Math.sin(halfYaw);
  2594. var cosYaw = Math.cos(halfYaw);
  2595. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2596. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2597. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2598. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2599. };
  2600. /**
  2601. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2602. */
  2603. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2604. var result = new Quaternion();
  2605. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2606. return result;
  2607. };
  2608. /**
  2609. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2610. */
  2611. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2612. // Produces a quaternion from Euler angles in the z-x-z orientation
  2613. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2614. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2615. var halfBeta = beta * 0.5;
  2616. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2617. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2618. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2619. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2620. };
  2621. /**
  2622. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2623. * cf to Vector3.RotationFromAxis() documentation.
  2624. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2625. */
  2626. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2627. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2628. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2629. return quat;
  2630. };
  2631. /**
  2632. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2633. * cf to Vector3.RotationFromAxis() documentation.
  2634. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2635. */
  2636. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2637. var rotMat = MathTmp.Matrix[0];
  2638. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2639. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2640. };
  2641. Quaternion.Slerp = function (left, right, amount) {
  2642. var result = Quaternion.Identity();
  2643. Quaternion.SlerpToRef(left, right, amount, result);
  2644. return result;
  2645. };
  2646. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2647. var num2;
  2648. var num3;
  2649. var num = amount;
  2650. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2651. var flag = false;
  2652. if (num4 < 0) {
  2653. flag = true;
  2654. num4 = -num4;
  2655. }
  2656. if (num4 > 0.999999) {
  2657. num3 = 1 - num;
  2658. num2 = flag ? -num : num;
  2659. }
  2660. else {
  2661. var num5 = Math.acos(num4);
  2662. var num6 = (1.0 / Math.sin(num5));
  2663. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2664. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2665. }
  2666. result.x = (num3 * left.x) + (num2 * right.x);
  2667. result.y = (num3 * left.y) + (num2 * right.y);
  2668. result.z = (num3 * left.z) + (num2 * right.z);
  2669. result.w = (num3 * left.w) + (num2 * right.w);
  2670. };
  2671. return Quaternion;
  2672. }());
  2673. BABYLON.Quaternion = Quaternion;
  2674. var Matrix = (function () {
  2675. function Matrix() {
  2676. this.m = new Float32Array(16);
  2677. this._markAsUpdated();
  2678. }
  2679. Matrix.prototype._markAsUpdated = function () {
  2680. this.updateFlag = Matrix._updateFlagSeed++;
  2681. };
  2682. // Properties
  2683. /**
  2684. * Boolean : True is the matrix is the identity matrix
  2685. */
  2686. Matrix.prototype.isIdentity = function () {
  2687. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2688. return false;
  2689. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2690. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2691. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2692. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2693. return false;
  2694. return true;
  2695. };
  2696. /**
  2697. * Returns the matrix determinant (float).
  2698. */
  2699. Matrix.prototype.determinant = function () {
  2700. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2701. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2702. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2703. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2704. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2705. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2706. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2707. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2708. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2709. };
  2710. // Methods
  2711. /**
  2712. * Returns the matrix underlying array.
  2713. */
  2714. Matrix.prototype.toArray = function () {
  2715. return this.m;
  2716. };
  2717. /**
  2718. * Returns the matrix underlying array.
  2719. */
  2720. Matrix.prototype.asArray = function () {
  2721. return this.toArray();
  2722. };
  2723. /**
  2724. * Inverts in place the Matrix.
  2725. * Returns the Matrix inverted.
  2726. */
  2727. Matrix.prototype.invert = function () {
  2728. this.invertToRef(this);
  2729. return this;
  2730. };
  2731. /**
  2732. * Sets all the matrix elements to zero.
  2733. * Returns the Matrix.
  2734. */
  2735. Matrix.prototype.reset = function () {
  2736. for (var index = 0; index < 16; index++) {
  2737. this.m[index] = 0.0;
  2738. }
  2739. this._markAsUpdated();
  2740. return this;
  2741. };
  2742. /**
  2743. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2744. */
  2745. Matrix.prototype.add = function (other) {
  2746. var result = new Matrix();
  2747. this.addToRef(other, result);
  2748. return result;
  2749. };
  2750. /**
  2751. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2752. * Returns the Matrix.
  2753. */
  2754. Matrix.prototype.addToRef = function (other, result) {
  2755. for (var index = 0; index < 16; index++) {
  2756. result.m[index] = this.m[index] + other.m[index];
  2757. }
  2758. result._markAsUpdated();
  2759. return this;
  2760. };
  2761. /**
  2762. * Adds in place the passed matrix to the current Matrix.
  2763. * Returns the updated Matrix.
  2764. */
  2765. Matrix.prototype.addToSelf = function (other) {
  2766. for (var index = 0; index < 16; index++) {
  2767. this.m[index] += other.m[index];
  2768. }
  2769. this._markAsUpdated();
  2770. return this;
  2771. };
  2772. /**
  2773. * Sets the passed matrix with the current inverted Matrix.
  2774. * Returns the unmodified current Matrix.
  2775. */
  2776. Matrix.prototype.invertToRef = function (other) {
  2777. var l1 = this.m[0];
  2778. var l2 = this.m[1];
  2779. var l3 = this.m[2];
  2780. var l4 = this.m[3];
  2781. var l5 = this.m[4];
  2782. var l6 = this.m[5];
  2783. var l7 = this.m[6];
  2784. var l8 = this.m[7];
  2785. var l9 = this.m[8];
  2786. var l10 = this.m[9];
  2787. var l11 = this.m[10];
  2788. var l12 = this.m[11];
  2789. var l13 = this.m[12];
  2790. var l14 = this.m[13];
  2791. var l15 = this.m[14];
  2792. var l16 = this.m[15];
  2793. var l17 = (l11 * l16) - (l12 * l15);
  2794. var l18 = (l10 * l16) - (l12 * l14);
  2795. var l19 = (l10 * l15) - (l11 * l14);
  2796. var l20 = (l9 * l16) - (l12 * l13);
  2797. var l21 = (l9 * l15) - (l11 * l13);
  2798. var l22 = (l9 * l14) - (l10 * l13);
  2799. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2800. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2801. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2802. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2803. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2804. var l28 = (l7 * l16) - (l8 * l15);
  2805. var l29 = (l6 * l16) - (l8 * l14);
  2806. var l30 = (l6 * l15) - (l7 * l14);
  2807. var l31 = (l5 * l16) - (l8 * l13);
  2808. var l32 = (l5 * l15) - (l7 * l13);
  2809. var l33 = (l5 * l14) - (l6 * l13);
  2810. var l34 = (l7 * l12) - (l8 * l11);
  2811. var l35 = (l6 * l12) - (l8 * l10);
  2812. var l36 = (l6 * l11) - (l7 * l10);
  2813. var l37 = (l5 * l12) - (l8 * l9);
  2814. var l38 = (l5 * l11) - (l7 * l9);
  2815. var l39 = (l5 * l10) - (l6 * l9);
  2816. other.m[0] = l23 * l27;
  2817. other.m[4] = l24 * l27;
  2818. other.m[8] = l25 * l27;
  2819. other.m[12] = l26 * l27;
  2820. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2821. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2822. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2823. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2824. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2825. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2826. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2827. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2828. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2829. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2830. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2831. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2832. other._markAsUpdated();
  2833. return this;
  2834. };
  2835. /**
  2836. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2837. * Returns the updated Matrix.
  2838. */
  2839. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2840. this.m[12] = x;
  2841. this.m[13] = y;
  2842. this.m[14] = z;
  2843. this._markAsUpdated();
  2844. return this;
  2845. };
  2846. /**
  2847. * Inserts the translation vector in the current Matrix.
  2848. * Returns the updated Matrix.
  2849. */
  2850. Matrix.prototype.setTranslation = function (vector3) {
  2851. this.m[12] = vector3.x;
  2852. this.m[13] = vector3.y;
  2853. this.m[14] = vector3.z;
  2854. this._markAsUpdated();
  2855. return this;
  2856. };
  2857. /**
  2858. * Returns a new Vector3 as the extracted translation from the Matrix.
  2859. */
  2860. Matrix.prototype.getTranslation = function () {
  2861. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2862. };
  2863. /**
  2864. * Fill a Vector3 with the extracted translation from the Matrix.
  2865. */
  2866. Matrix.prototype.getTranslationToRef = function (result) {
  2867. result.x = this.m[12];
  2868. result.y = this.m[13];
  2869. result.z = this.m[14];
  2870. return this;
  2871. };
  2872. /**
  2873. * Remove rotation and scaling part from the Matrix.
  2874. * Returns the updated Matrix.
  2875. */
  2876. Matrix.prototype.removeRotationAndScaling = function () {
  2877. this.setRowFromFloats(0, 1, 0, 0, 0);
  2878. this.setRowFromFloats(1, 0, 1, 0, 0);
  2879. this.setRowFromFloats(2, 0, 0, 1, 0);
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2884. */
  2885. Matrix.prototype.multiply = function (other) {
  2886. var result = new Matrix();
  2887. this.multiplyToRef(other, result);
  2888. return result;
  2889. };
  2890. /**
  2891. * Updates the current Matrix from the passed one values.
  2892. * Returns the updated Matrix.
  2893. */
  2894. Matrix.prototype.copyFrom = function (other) {
  2895. for (var index = 0; index < 16; index++) {
  2896. this.m[index] = other.m[index];
  2897. }
  2898. this._markAsUpdated();
  2899. return this;
  2900. };
  2901. /**
  2902. * Populates the passed array from the starting index with the Matrix values.
  2903. * Returns the Matrix.
  2904. */
  2905. Matrix.prototype.copyToArray = function (array, offset) {
  2906. if (offset === void 0) { offset = 0; }
  2907. for (var index = 0; index < 16; index++) {
  2908. array[offset + index] = this.m[index];
  2909. }
  2910. return this;
  2911. };
  2912. /**
  2913. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2914. */
  2915. Matrix.prototype.multiplyToRef = function (other, result) {
  2916. this.multiplyToArray(other, result.m, 0);
  2917. result._markAsUpdated();
  2918. return this;
  2919. };
  2920. /**
  2921. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2922. */
  2923. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2924. var tm0 = this.m[0];
  2925. var tm1 = this.m[1];
  2926. var tm2 = this.m[2];
  2927. var tm3 = this.m[3];
  2928. var tm4 = this.m[4];
  2929. var tm5 = this.m[5];
  2930. var tm6 = this.m[6];
  2931. var tm7 = this.m[7];
  2932. var tm8 = this.m[8];
  2933. var tm9 = this.m[9];
  2934. var tm10 = this.m[10];
  2935. var tm11 = this.m[11];
  2936. var tm12 = this.m[12];
  2937. var tm13 = this.m[13];
  2938. var tm14 = this.m[14];
  2939. var tm15 = this.m[15];
  2940. var om0 = other.m[0];
  2941. var om1 = other.m[1];
  2942. var om2 = other.m[2];
  2943. var om3 = other.m[3];
  2944. var om4 = other.m[4];
  2945. var om5 = other.m[5];
  2946. var om6 = other.m[6];
  2947. var om7 = other.m[7];
  2948. var om8 = other.m[8];
  2949. var om9 = other.m[9];
  2950. var om10 = other.m[10];
  2951. var om11 = other.m[11];
  2952. var om12 = other.m[12];
  2953. var om13 = other.m[13];
  2954. var om14 = other.m[14];
  2955. var om15 = other.m[15];
  2956. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2957. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2958. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2959. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2960. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2961. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2962. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2963. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2964. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2965. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2966. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2967. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2968. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2969. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2970. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2971. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2972. return this;
  2973. };
  2974. /**
  2975. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2976. */
  2977. Matrix.prototype.equals = function (value) {
  2978. return value &&
  2979. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2980. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2981. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2982. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2983. };
  2984. /**
  2985. * Returns a new Matrix from the current Matrix.
  2986. */
  2987. Matrix.prototype.clone = function () {
  2988. 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]);
  2989. };
  2990. /**
  2991. * Returns the string "Matrix"
  2992. */
  2993. Matrix.prototype.getClassName = function () {
  2994. return "Matrix";
  2995. };
  2996. /**
  2997. * Returns the Matrix hash code.
  2998. */
  2999. Matrix.prototype.getHashCode = function () {
  3000. var hash = this.m[0] || 0;
  3001. for (var i = 1; i < 16; i++) {
  3002. hash = (hash * 397) ^ (this.m[i] || 0);
  3003. }
  3004. return hash;
  3005. };
  3006. /**
  3007. * Decomposes the current Matrix into :
  3008. * - a scale vector3 passed as a reference to update,
  3009. * - a rotation quaternion passed as a reference to update,
  3010. * - a translation vector3 passed as a reference to update.
  3011. * Returns the boolean `true`.
  3012. */
  3013. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3014. translation.x = this.m[12];
  3015. translation.y = this.m[13];
  3016. translation.z = this.m[14];
  3017. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3018. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3019. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3020. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3021. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3022. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3023. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3024. rotation.x = 0;
  3025. rotation.y = 0;
  3026. rotation.z = 0;
  3027. rotation.w = 1;
  3028. return false;
  3029. }
  3030. 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]);
  3031. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3032. return true;
  3033. };
  3034. /**
  3035. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3036. */
  3037. Matrix.prototype.getRotationMatrix = function () {
  3038. var result = Matrix.Identity();
  3039. this.getRotationMatrixToRef(result);
  3040. return result;
  3041. };
  3042. /**
  3043. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3044. * Returns the current Matrix.
  3045. */
  3046. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3047. var m = this.m;
  3048. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3049. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3050. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3051. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3052. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3053. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3054. 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);
  3055. return this;
  3056. };
  3057. // Statics
  3058. /**
  3059. * Returns a new Matrix set from the starting index of the passed array.
  3060. */
  3061. Matrix.FromArray = function (array, offset) {
  3062. var result = new Matrix();
  3063. if (!offset) {
  3064. offset = 0;
  3065. }
  3066. Matrix.FromArrayToRef(array, offset, result);
  3067. return result;
  3068. };
  3069. /**
  3070. * Sets the passed "result" matrix from the starting index of the passed array.
  3071. */
  3072. Matrix.FromArrayToRef = function (array, offset, result) {
  3073. for (var index = 0; index < 16; index++) {
  3074. result.m[index] = array[index + offset];
  3075. }
  3076. result._markAsUpdated();
  3077. };
  3078. /**
  3079. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3080. */
  3081. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3082. for (var index = 0; index < 16; index++) {
  3083. result.m[index] = array[index + offset] * scale;
  3084. }
  3085. result._markAsUpdated();
  3086. };
  3087. /**
  3088. * Sets the passed matrix "result" with the 16 passed floats.
  3089. */
  3090. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3091. result.m[0] = initialM11;
  3092. result.m[1] = initialM12;
  3093. result.m[2] = initialM13;
  3094. result.m[3] = initialM14;
  3095. result.m[4] = initialM21;
  3096. result.m[5] = initialM22;
  3097. result.m[6] = initialM23;
  3098. result.m[7] = initialM24;
  3099. result.m[8] = initialM31;
  3100. result.m[9] = initialM32;
  3101. result.m[10] = initialM33;
  3102. result.m[11] = initialM34;
  3103. result.m[12] = initialM41;
  3104. result.m[13] = initialM42;
  3105. result.m[14] = initialM43;
  3106. result.m[15] = initialM44;
  3107. result._markAsUpdated();
  3108. };
  3109. /**
  3110. * Returns the index-th row of the current matrix as a new Vector4.
  3111. */
  3112. Matrix.prototype.getRow = function (index) {
  3113. if (index < 0 || index > 3) {
  3114. return null;
  3115. }
  3116. var i = index * 4;
  3117. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3118. };
  3119. /**
  3120. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3121. * Returns the updated Matrix.
  3122. */
  3123. Matrix.prototype.setRow = function (index, row) {
  3124. if (index < 0 || index > 3) {
  3125. return this;
  3126. }
  3127. var i = index * 4;
  3128. this.m[i + 0] = row.x;
  3129. this.m[i + 1] = row.y;
  3130. this.m[i + 2] = row.z;
  3131. this.m[i + 3] = row.w;
  3132. this._markAsUpdated();
  3133. return this;
  3134. };
  3135. /**
  3136. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3137. * Returns the updated Matrix.
  3138. */
  3139. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3140. if (index < 0 || index > 3) {
  3141. return this;
  3142. }
  3143. var i = index * 4;
  3144. this.m[i + 0] = x;
  3145. this.m[i + 1] = y;
  3146. this.m[i + 2] = z;
  3147. this.m[i + 3] = w;
  3148. this._markAsUpdated();
  3149. return this;
  3150. };
  3151. /**
  3152. * Returns a new Matrix set from the 16 passed floats.
  3153. */
  3154. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3155. var result = new Matrix();
  3156. result.m[0] = initialM11;
  3157. result.m[1] = initialM12;
  3158. result.m[2] = initialM13;
  3159. result.m[3] = initialM14;
  3160. result.m[4] = initialM21;
  3161. result.m[5] = initialM22;
  3162. result.m[6] = initialM23;
  3163. result.m[7] = initialM24;
  3164. result.m[8] = initialM31;
  3165. result.m[9] = initialM32;
  3166. result.m[10] = initialM33;
  3167. result.m[11] = initialM34;
  3168. result.m[12] = initialM41;
  3169. result.m[13] = initialM42;
  3170. result.m[14] = initialM43;
  3171. result.m[15] = initialM44;
  3172. return result;
  3173. };
  3174. /**
  3175. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3176. */
  3177. Matrix.Compose = function (scale, rotation, translation) {
  3178. var result = Matrix.Identity();
  3179. Matrix.ComposeToRef(scale, rotation, translation, result);
  3180. return result;
  3181. };
  3182. /**
  3183. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3184. */
  3185. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3186. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3187. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3188. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3189. result.setTranslation(translation);
  3190. };
  3191. /**
  3192. * Returns a new indentity Matrix.
  3193. */
  3194. Matrix.Identity = function () {
  3195. 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);
  3196. };
  3197. /**
  3198. * Sets the passed "result" as an identity matrix.
  3199. */
  3200. Matrix.IdentityToRef = function (result) {
  3201. 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);
  3202. };
  3203. /**
  3204. * Returns a new zero Matrix.
  3205. */
  3206. Matrix.Zero = function () {
  3207. 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);
  3208. };
  3209. /**
  3210. * Returns a new rotation matrix for "angle" radians around the X axis.
  3211. */
  3212. Matrix.RotationX = function (angle) {
  3213. var result = new Matrix();
  3214. Matrix.RotationXToRef(angle, result);
  3215. return result;
  3216. };
  3217. /**
  3218. * Returns a new Matrix as the passed inverted one.
  3219. */
  3220. Matrix.Invert = function (source) {
  3221. var result = new Matrix();
  3222. source.invertToRef(result);
  3223. return result;
  3224. };
  3225. /**
  3226. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3227. */
  3228. Matrix.RotationXToRef = function (angle, result) {
  3229. var s = Math.sin(angle);
  3230. var c = Math.cos(angle);
  3231. result.m[0] = 1.0;
  3232. result.m[15] = 1.0;
  3233. result.m[5] = c;
  3234. result.m[10] = c;
  3235. result.m[9] = -s;
  3236. result.m[6] = s;
  3237. result.m[1] = 0.0;
  3238. result.m[2] = 0.0;
  3239. result.m[3] = 0.0;
  3240. result.m[4] = 0.0;
  3241. result.m[7] = 0.0;
  3242. result.m[8] = 0.0;
  3243. result.m[11] = 0.0;
  3244. result.m[12] = 0.0;
  3245. result.m[13] = 0.0;
  3246. result.m[14] = 0.0;
  3247. result._markAsUpdated();
  3248. };
  3249. /**
  3250. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3251. */
  3252. Matrix.RotationY = function (angle) {
  3253. var result = new Matrix();
  3254. Matrix.RotationYToRef(angle, result);
  3255. return result;
  3256. };
  3257. /**
  3258. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3259. */
  3260. Matrix.RotationYToRef = function (angle, result) {
  3261. var s = Math.sin(angle);
  3262. var c = Math.cos(angle);
  3263. result.m[5] = 1.0;
  3264. result.m[15] = 1.0;
  3265. result.m[0] = c;
  3266. result.m[2] = -s;
  3267. result.m[8] = s;
  3268. result.m[10] = c;
  3269. result.m[1] = 0.0;
  3270. result.m[3] = 0.0;
  3271. result.m[4] = 0.0;
  3272. result.m[6] = 0.0;
  3273. result.m[7] = 0.0;
  3274. result.m[9] = 0.0;
  3275. result.m[11] = 0.0;
  3276. result.m[12] = 0.0;
  3277. result.m[13] = 0.0;
  3278. result.m[14] = 0.0;
  3279. result._markAsUpdated();
  3280. };
  3281. /**
  3282. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3283. */
  3284. Matrix.RotationZ = function (angle) {
  3285. var result = new Matrix();
  3286. Matrix.RotationZToRef(angle, result);
  3287. return result;
  3288. };
  3289. /**
  3290. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3291. */
  3292. Matrix.RotationZToRef = function (angle, result) {
  3293. var s = Math.sin(angle);
  3294. var c = Math.cos(angle);
  3295. result.m[10] = 1.0;
  3296. result.m[15] = 1.0;
  3297. result.m[0] = c;
  3298. result.m[1] = s;
  3299. result.m[4] = -s;
  3300. result.m[5] = c;
  3301. result.m[2] = 0.0;
  3302. result.m[3] = 0.0;
  3303. result.m[6] = 0.0;
  3304. result.m[7] = 0.0;
  3305. result.m[8] = 0.0;
  3306. result.m[9] = 0.0;
  3307. result.m[11] = 0.0;
  3308. result.m[12] = 0.0;
  3309. result.m[13] = 0.0;
  3310. result.m[14] = 0.0;
  3311. result._markAsUpdated();
  3312. };
  3313. /**
  3314. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3315. */
  3316. Matrix.RotationAxis = function (axis, angle) {
  3317. var result = Matrix.Zero();
  3318. Matrix.RotationAxisToRef(axis, angle, result);
  3319. return result;
  3320. };
  3321. /**
  3322. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3323. */
  3324. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3325. var s = Math.sin(-angle);
  3326. var c = Math.cos(-angle);
  3327. var c1 = 1 - c;
  3328. axis.normalize();
  3329. result.m[0] = (axis.x * axis.x) * c1 + c;
  3330. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3331. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3332. result.m[3] = 0.0;
  3333. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3334. result.m[5] = (axis.y * axis.y) * c1 + c;
  3335. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3336. result.m[7] = 0.0;
  3337. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3338. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3339. result.m[10] = (axis.z * axis.z) * c1 + c;
  3340. result.m[11] = 0.0;
  3341. result.m[15] = 1.0;
  3342. result._markAsUpdated();
  3343. };
  3344. /**
  3345. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3346. */
  3347. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3348. var result = new Matrix();
  3349. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3350. return result;
  3351. };
  3352. /**
  3353. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3354. */
  3355. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3356. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3357. this._tempQuaternion.toRotationMatrix(result);
  3358. };
  3359. /**
  3360. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3361. */
  3362. Matrix.Scaling = function (x, y, z) {
  3363. var result = Matrix.Zero();
  3364. Matrix.ScalingToRef(x, y, z, result);
  3365. return result;
  3366. };
  3367. /**
  3368. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3369. */
  3370. Matrix.ScalingToRef = function (x, y, z, result) {
  3371. result.m[0] = x;
  3372. result.m[1] = 0.0;
  3373. result.m[2] = 0.0;
  3374. result.m[3] = 0.0;
  3375. result.m[4] = 0.0;
  3376. result.m[5] = y;
  3377. result.m[6] = 0.0;
  3378. result.m[7] = 0.0;
  3379. result.m[8] = 0.0;
  3380. result.m[9] = 0.0;
  3381. result.m[10] = z;
  3382. result.m[11] = 0.0;
  3383. result.m[12] = 0.0;
  3384. result.m[13] = 0.0;
  3385. result.m[14] = 0.0;
  3386. result.m[15] = 1.0;
  3387. result._markAsUpdated();
  3388. };
  3389. /**
  3390. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3391. */
  3392. Matrix.Translation = function (x, y, z) {
  3393. var result = Matrix.Identity();
  3394. Matrix.TranslationToRef(x, y, z, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3399. */
  3400. Matrix.TranslationToRef = function (x, y, z, result) {
  3401. 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);
  3402. };
  3403. /**
  3404. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3405. */
  3406. Matrix.Lerp = function (startValue, endValue, gradient) {
  3407. var result = Matrix.Zero();
  3408. for (var index = 0; index < 16; index++) {
  3409. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3410. }
  3411. result._markAsUpdated();
  3412. return result;
  3413. };
  3414. /**
  3415. * Returns a new Matrix whose values are computed by :
  3416. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3417. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3418. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3419. */
  3420. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3421. var startScale = new Vector3(0, 0, 0);
  3422. var startRotation = new Quaternion();
  3423. var startTranslation = new Vector3(0, 0, 0);
  3424. startValue.decompose(startScale, startRotation, startTranslation);
  3425. var endScale = new Vector3(0, 0, 0);
  3426. var endRotation = new Quaternion();
  3427. var endTranslation = new Vector3(0, 0, 0);
  3428. endValue.decompose(endScale, endRotation, endTranslation);
  3429. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3430. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3431. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3432. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3433. };
  3434. /**
  3435. * 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".
  3436. * This methods works for a Left-Handed system.
  3437. */
  3438. Matrix.LookAtLH = function (eye, target, up) {
  3439. var result = Matrix.Zero();
  3440. Matrix.LookAtLHToRef(eye, target, up, result);
  3441. return result;
  3442. };
  3443. /**
  3444. * 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".
  3445. * This methods works for a Left-Handed system.
  3446. */
  3447. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3448. // Z axis
  3449. target.subtractToRef(eye, this._zAxis);
  3450. this._zAxis.normalize();
  3451. // X axis
  3452. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3453. if (this._xAxis.lengthSquared() === 0) {
  3454. this._xAxis.x = 1.0;
  3455. }
  3456. else {
  3457. this._xAxis.normalize();
  3458. }
  3459. // Y axis
  3460. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3461. this._yAxis.normalize();
  3462. // Eye angles
  3463. var ex = -Vector3.Dot(this._xAxis, eye);
  3464. var ey = -Vector3.Dot(this._yAxis, eye);
  3465. var ez = -Vector3.Dot(this._zAxis, eye);
  3466. 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);
  3467. };
  3468. /**
  3469. * 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".
  3470. * This methods works for a Right-Handed system.
  3471. */
  3472. Matrix.LookAtRH = function (eye, target, up) {
  3473. var result = Matrix.Zero();
  3474. Matrix.LookAtRHToRef(eye, target, up, result);
  3475. return result;
  3476. };
  3477. /**
  3478. * 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".
  3479. * This methods works for a Left-Handed system.
  3480. */
  3481. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3482. // Z axis
  3483. eye.subtractToRef(target, this._zAxis);
  3484. this._zAxis.normalize();
  3485. // X axis
  3486. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3487. if (this._xAxis.lengthSquared() === 0) {
  3488. this._xAxis.x = 1.0;
  3489. }
  3490. else {
  3491. this._xAxis.normalize();
  3492. }
  3493. // Y axis
  3494. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3495. this._yAxis.normalize();
  3496. // Eye angles
  3497. var ex = -Vector3.Dot(this._xAxis, eye);
  3498. var ey = -Vector3.Dot(this._yAxis, eye);
  3499. var ez = -Vector3.Dot(this._zAxis, eye);
  3500. 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);
  3501. };
  3502. /**
  3503. * 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.
  3504. */
  3505. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3506. var matrix = Matrix.Zero();
  3507. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3508. return matrix;
  3509. };
  3510. /**
  3511. * 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.
  3512. */
  3513. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3514. var n = znear;
  3515. var f = zfar;
  3516. var a = 2.0 / width;
  3517. var b = 2.0 / height;
  3518. var c = 2.0 / (f - n);
  3519. var d = -(f + n) / (f - n);
  3520. 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);
  3521. };
  3522. /**
  3523. * 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.
  3524. */
  3525. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3526. var matrix = Matrix.Zero();
  3527. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3528. return matrix;
  3529. };
  3530. /**
  3531. * 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.
  3532. */
  3533. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3534. var n = znear;
  3535. var f = zfar;
  3536. var a = 2.0 / (right - left);
  3537. var b = 2.0 / (top - bottom);
  3538. var c = 2.0 / (f - n);
  3539. var d = -(f + n) / (f - n);
  3540. var i0 = (left + right) / (left - right);
  3541. var i1 = (top + bottom) / (bottom - top);
  3542. 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);
  3543. };
  3544. /**
  3545. * 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.
  3546. */
  3547. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3548. var matrix = Matrix.Zero();
  3549. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3550. return matrix;
  3551. };
  3552. /**
  3553. * 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.
  3554. */
  3555. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3556. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3557. result.m[10] *= -1.0;
  3558. };
  3559. /**
  3560. * 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.
  3561. */
  3562. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3563. var matrix = Matrix.Zero();
  3564. var n = znear;
  3565. var f = zfar;
  3566. var a = 2.0 * n / width;
  3567. var b = 2.0 * n / height;
  3568. var c = (f + n) / (f - n);
  3569. var d = -2.0 * f * n / (f - n);
  3570. 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);
  3571. return matrix;
  3572. };
  3573. /**
  3574. * 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.
  3575. */
  3576. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3577. var matrix = Matrix.Zero();
  3578. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3579. return matrix;
  3580. };
  3581. /**
  3582. * 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.
  3583. */
  3584. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3585. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3586. var n = znear;
  3587. var f = zfar;
  3588. var t = 1.0 / (Math.tan(fov * 0.5));
  3589. var a = isVerticalFovFixed ? (t / aspect) : t;
  3590. var b = isVerticalFovFixed ? t : (t * aspect);
  3591. var c = (f + n) / (f - n);
  3592. var d = -2.0 * f * n / (f - n);
  3593. 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);
  3594. };
  3595. /**
  3596. * 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.
  3597. */
  3598. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3599. var matrix = Matrix.Zero();
  3600. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3601. return matrix;
  3602. };
  3603. /**
  3604. * 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.
  3605. */
  3606. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3607. //alternatively this could be expressed as:
  3608. // m = PerspectiveFovLHToRef
  3609. // m[10] *= -1.0;
  3610. // m[11] *= -1.0;
  3611. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3612. var n = znear;
  3613. var f = zfar;
  3614. var t = 1.0 / (Math.tan(fov * 0.5));
  3615. var a = isVerticalFovFixed ? (t / aspect) : t;
  3616. var b = isVerticalFovFixed ? t : (t * aspect);
  3617. var c = -(f + n) / (f - n);
  3618. var d = -2 * f * n / (f - n);
  3619. 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);
  3620. };
  3621. /**
  3622. * 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.
  3623. */
  3624. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3625. if (rightHanded === void 0) { rightHanded = false; }
  3626. var rightHandedFactor = rightHanded ? -1 : 1;
  3627. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3628. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3629. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3630. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3631. var xScale = 2.0 / (leftTan + rightTan);
  3632. var yScale = 2.0 / (upTan + downTan);
  3633. result.m[0] = xScale;
  3634. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3635. result.m[5] = yScale;
  3636. result.m[6] = result.m[7] = 0.0;
  3637. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3638. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3639. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3640. result.m[10] = -zfar / (znear - zfar);
  3641. result.m[11] = 1.0 * rightHandedFactor;
  3642. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3643. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3644. // result.m[14] = (znear * zfar) / (znear - zfar);
  3645. result._markAsUpdated();
  3646. };
  3647. /**
  3648. * Returns the final transformation matrix : world * view * projection * viewport
  3649. */
  3650. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3651. var cw = viewport.width;
  3652. var ch = viewport.height;
  3653. var cx = viewport.x;
  3654. var cy = viewport.y;
  3655. 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);
  3656. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3657. };
  3658. /**
  3659. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3660. */
  3661. Matrix.GetAsMatrix2x2 = function (matrix) {
  3662. return new Float32Array([
  3663. matrix.m[0], matrix.m[1],
  3664. matrix.m[4], matrix.m[5]
  3665. ]);
  3666. };
  3667. /**
  3668. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3669. */
  3670. Matrix.GetAsMatrix3x3 = function (matrix) {
  3671. return new Float32Array([
  3672. matrix.m[0], matrix.m[1], matrix.m[2],
  3673. matrix.m[4], matrix.m[5], matrix.m[6],
  3674. matrix.m[8], matrix.m[9], matrix.m[10]
  3675. ]);
  3676. };
  3677. /**
  3678. * Compute the transpose of the passed Matrix.
  3679. * Returns a new Matrix.
  3680. */
  3681. Matrix.Transpose = function (matrix) {
  3682. var result = new Matrix();
  3683. result.m[0] = matrix.m[0];
  3684. result.m[1] = matrix.m[4];
  3685. result.m[2] = matrix.m[8];
  3686. result.m[3] = matrix.m[12];
  3687. result.m[4] = matrix.m[1];
  3688. result.m[5] = matrix.m[5];
  3689. result.m[6] = matrix.m[9];
  3690. result.m[7] = matrix.m[13];
  3691. result.m[8] = matrix.m[2];
  3692. result.m[9] = matrix.m[6];
  3693. result.m[10] = matrix.m[10];
  3694. result.m[11] = matrix.m[14];
  3695. result.m[12] = matrix.m[3];
  3696. result.m[13] = matrix.m[7];
  3697. result.m[14] = matrix.m[11];
  3698. result.m[15] = matrix.m[15];
  3699. return result;
  3700. };
  3701. /**
  3702. * Returns a new Matrix as the reflection matrix across the passed plane.
  3703. */
  3704. Matrix.Reflection = function (plane) {
  3705. var matrix = new Matrix();
  3706. Matrix.ReflectionToRef(plane, matrix);
  3707. return matrix;
  3708. };
  3709. /**
  3710. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3711. */
  3712. Matrix.ReflectionToRef = function (plane, result) {
  3713. plane.normalize();
  3714. var x = plane.normal.x;
  3715. var y = plane.normal.y;
  3716. var z = plane.normal.z;
  3717. var temp = -2 * x;
  3718. var temp2 = -2 * y;
  3719. var temp3 = -2 * z;
  3720. result.m[0] = (temp * x) + 1;
  3721. result.m[1] = temp2 * x;
  3722. result.m[2] = temp3 * x;
  3723. result.m[3] = 0.0;
  3724. result.m[4] = temp * y;
  3725. result.m[5] = (temp2 * y) + 1;
  3726. result.m[6] = temp3 * y;
  3727. result.m[7] = 0.0;
  3728. result.m[8] = temp * z;
  3729. result.m[9] = temp2 * z;
  3730. result.m[10] = (temp3 * z) + 1;
  3731. result.m[11] = 0.0;
  3732. result.m[12] = temp * plane.d;
  3733. result.m[13] = temp2 * plane.d;
  3734. result.m[14] = temp3 * plane.d;
  3735. result.m[15] = 1.0;
  3736. result._markAsUpdated();
  3737. };
  3738. /**
  3739. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3740. */
  3741. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3742. result.m[0] = xaxis.x;
  3743. result.m[1] = xaxis.y;
  3744. result.m[2] = xaxis.z;
  3745. result.m[3] = 0.0;
  3746. result.m[4] = yaxis.x;
  3747. result.m[5] = yaxis.y;
  3748. result.m[6] = yaxis.z;
  3749. result.m[7] = 0.0;
  3750. result.m[8] = zaxis.x;
  3751. result.m[9] = zaxis.y;
  3752. result.m[10] = zaxis.z;
  3753. result.m[11] = 0.0;
  3754. result.m[12] = 0.0;
  3755. result.m[13] = 0.0;
  3756. result.m[14] = 0.0;
  3757. result.m[15] = 1.0;
  3758. result._markAsUpdated();
  3759. };
  3760. /**
  3761. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3762. */
  3763. Matrix.FromQuaternionToRef = function (quat, result) {
  3764. var xx = quat.x * quat.x;
  3765. var yy = quat.y * quat.y;
  3766. var zz = quat.z * quat.z;
  3767. var xy = quat.x * quat.y;
  3768. var zw = quat.z * quat.w;
  3769. var zx = quat.z * quat.x;
  3770. var yw = quat.y * quat.w;
  3771. var yz = quat.y * quat.z;
  3772. var xw = quat.x * quat.w;
  3773. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3774. result.m[1] = 2.0 * (xy + zw);
  3775. result.m[2] = 2.0 * (zx - yw);
  3776. result.m[3] = 0.0;
  3777. result.m[4] = 2.0 * (xy - zw);
  3778. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3779. result.m[6] = 2.0 * (yz + xw);
  3780. result.m[7] = 0.0;
  3781. result.m[8] = 2.0 * (zx + yw);
  3782. result.m[9] = 2.0 * (yz - xw);
  3783. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3784. result.m[11] = 0.0;
  3785. result.m[12] = 0.0;
  3786. result.m[13] = 0.0;
  3787. result.m[14] = 0.0;
  3788. result.m[15] = 1.0;
  3789. result._markAsUpdated();
  3790. };
  3791. return Matrix;
  3792. }());
  3793. Matrix._tempQuaternion = new Quaternion();
  3794. Matrix._xAxis = Vector3.Zero();
  3795. Matrix._yAxis = Vector3.Zero();
  3796. Matrix._zAxis = Vector3.Zero();
  3797. Matrix._updateFlagSeed = 0;
  3798. BABYLON.Matrix = Matrix;
  3799. var Plane = (function () {
  3800. /**
  3801. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3802. */
  3803. function Plane(a, b, c, d) {
  3804. this.normal = new Vector3(a, b, c);
  3805. this.d = d;
  3806. }
  3807. /**
  3808. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3809. */
  3810. Plane.prototype.asArray = function () {
  3811. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3812. };
  3813. // Methods
  3814. /**
  3815. * Returns a new plane copied from the current Plane.
  3816. */
  3817. Plane.prototype.clone = function () {
  3818. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3819. };
  3820. /**
  3821. * Returns the string "Plane".
  3822. */
  3823. Plane.prototype.getClassName = function () {
  3824. return "Plane";
  3825. };
  3826. /**
  3827. * Returns the Plane hash code.
  3828. */
  3829. Plane.prototype.getHashCode = function () {
  3830. var hash = this.normal.getHashCode();
  3831. hash = (hash * 397) ^ (this.d || 0);
  3832. return hash;
  3833. };
  3834. /**
  3835. * Normalize the current Plane in place.
  3836. * Returns the updated Plane.
  3837. */
  3838. Plane.prototype.normalize = function () {
  3839. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3840. var magnitude = 0.0;
  3841. if (norm !== 0) {
  3842. magnitude = 1.0 / norm;
  3843. }
  3844. this.normal.x *= magnitude;
  3845. this.normal.y *= magnitude;
  3846. this.normal.z *= magnitude;
  3847. this.d *= magnitude;
  3848. return this;
  3849. };
  3850. /**
  3851. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3852. */
  3853. Plane.prototype.transform = function (transformation) {
  3854. var transposedMatrix = Matrix.Transpose(transformation);
  3855. var x = this.normal.x;
  3856. var y = this.normal.y;
  3857. var z = this.normal.z;
  3858. var d = this.d;
  3859. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3860. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3861. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3862. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3863. return new Plane(normalX, normalY, normalZ, finalD);
  3864. };
  3865. /**
  3866. * Returns the dot product (float) of the point coordinates and the plane normal.
  3867. */
  3868. Plane.prototype.dotCoordinate = function (point) {
  3869. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3870. };
  3871. /**
  3872. * Updates the current Plane from the plane defined by the three passed points.
  3873. * Returns the updated Plane.
  3874. */
  3875. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3876. var x1 = point2.x - point1.x;
  3877. var y1 = point2.y - point1.y;
  3878. var z1 = point2.z - point1.z;
  3879. var x2 = point3.x - point1.x;
  3880. var y2 = point3.y - point1.y;
  3881. var z2 = point3.z - point1.z;
  3882. var yz = (y1 * z2) - (z1 * y2);
  3883. var xz = (z1 * x2) - (x1 * z2);
  3884. var xy = (x1 * y2) - (y1 * x2);
  3885. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3886. var invPyth;
  3887. if (pyth !== 0) {
  3888. invPyth = 1.0 / pyth;
  3889. }
  3890. else {
  3891. invPyth = 0.0;
  3892. }
  3893. this.normal.x = yz * invPyth;
  3894. this.normal.y = xz * invPyth;
  3895. this.normal.z = xy * invPyth;
  3896. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3897. return this;
  3898. };
  3899. /**
  3900. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3901. */
  3902. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3903. var dot = Vector3.Dot(this.normal, direction);
  3904. return (dot <= epsilon);
  3905. };
  3906. /**
  3907. * Returns the signed distance (float) from the passed point to the Plane.
  3908. */
  3909. Plane.prototype.signedDistanceTo = function (point) {
  3910. return Vector3.Dot(point, this.normal) + this.d;
  3911. };
  3912. // Statics
  3913. /**
  3914. * Returns a new Plane from the passed array.
  3915. */
  3916. Plane.FromArray = function (array) {
  3917. return new Plane(array[0], array[1], array[2], array[3]);
  3918. };
  3919. /**
  3920. * Returns a new Plane defined by the three passed points.
  3921. */
  3922. Plane.FromPoints = function (point1, point2, point3) {
  3923. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3924. result.copyFromPoints(point1, point2, point3);
  3925. return result;
  3926. };
  3927. /**
  3928. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3929. * Note : the vector "normal" is updated because normalized.
  3930. */
  3931. Plane.FromPositionAndNormal = function (origin, normal) {
  3932. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3933. normal.normalize();
  3934. result.normal = normal;
  3935. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3936. return result;
  3937. };
  3938. /**
  3939. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3940. */
  3941. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3942. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3943. return Vector3.Dot(point, normal) + d;
  3944. };
  3945. return Plane;
  3946. }());
  3947. BABYLON.Plane = Plane;
  3948. var Viewport = (function () {
  3949. /**
  3950. * Creates a Viewport object located at (x, y) and sized (width, height).
  3951. */
  3952. function Viewport(x, y, width, height) {
  3953. this.x = x;
  3954. this.y = y;
  3955. this.width = width;
  3956. this.height = height;
  3957. }
  3958. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3959. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3960. };
  3961. /**
  3962. * Returns a new Viewport copied from the current one.
  3963. */
  3964. Viewport.prototype.clone = function () {
  3965. return new Viewport(this.x, this.y, this.width, this.height);
  3966. };
  3967. return Viewport;
  3968. }());
  3969. BABYLON.Viewport = Viewport;
  3970. var Frustum = (function () {
  3971. function Frustum() {
  3972. }
  3973. /**
  3974. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3975. */
  3976. Frustum.GetPlanes = function (transform) {
  3977. var frustumPlanes = [];
  3978. for (var index = 0; index < 6; index++) {
  3979. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3980. }
  3981. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3982. return frustumPlanes;
  3983. };
  3984. /**
  3985. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3986. */
  3987. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3988. // Near
  3989. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3990. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3991. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3992. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3993. frustumPlanes[0].normalize();
  3994. // Far
  3995. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3996. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3997. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3998. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3999. frustumPlanes[1].normalize();
  4000. // Left
  4001. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4002. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4003. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4004. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4005. frustumPlanes[2].normalize();
  4006. // Right
  4007. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4008. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4009. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4010. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4011. frustumPlanes[3].normalize();
  4012. // Top
  4013. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4014. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4015. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4016. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4017. frustumPlanes[4].normalize();
  4018. // Bottom
  4019. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4020. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4021. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4022. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4023. frustumPlanes[5].normalize();
  4024. };
  4025. return Frustum;
  4026. }());
  4027. BABYLON.Frustum = Frustum;
  4028. var Space;
  4029. (function (Space) {
  4030. Space[Space["LOCAL"] = 0] = "LOCAL";
  4031. Space[Space["WORLD"] = 1] = "WORLD";
  4032. Space[Space["BONE"] = 2] = "BONE";
  4033. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4034. var Axis = (function () {
  4035. function Axis() {
  4036. }
  4037. return Axis;
  4038. }());
  4039. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4040. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4041. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4042. BABYLON.Axis = Axis;
  4043. ;
  4044. var BezierCurve = (function () {
  4045. function BezierCurve() {
  4046. }
  4047. /**
  4048. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4049. */
  4050. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4051. // Extract X (which is equal to time here)
  4052. var f0 = 1 - 3 * x2 + 3 * x1;
  4053. var f1 = 3 * x2 - 6 * x1;
  4054. var f2 = 3 * x1;
  4055. var refinedT = t;
  4056. for (var i = 0; i < 5; i++) {
  4057. var refinedT2 = refinedT * refinedT;
  4058. var refinedT3 = refinedT2 * refinedT;
  4059. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4060. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4061. refinedT -= (x - t) * slope;
  4062. refinedT = Math.min(1, Math.max(0, refinedT));
  4063. }
  4064. // Resolve cubic bezier for the given x
  4065. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4066. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4067. Math.pow(refinedT, 3);
  4068. };
  4069. return BezierCurve;
  4070. }());
  4071. BABYLON.BezierCurve = BezierCurve;
  4072. var Orientation;
  4073. (function (Orientation) {
  4074. Orientation[Orientation["CW"] = 0] = "CW";
  4075. Orientation[Orientation["CCW"] = 1] = "CCW";
  4076. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4077. var Angle = (function () {
  4078. /**
  4079. * Creates an Angle object of "radians" radians (float).
  4080. */
  4081. function Angle(radians) {
  4082. var _this = this;
  4083. /**
  4084. * Returns the Angle value in degrees (float).
  4085. */
  4086. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4087. /**
  4088. * Returns the Angle value in radians (float).
  4089. */
  4090. this.radians = function () { return _this._radians; };
  4091. this._radians = radians;
  4092. if (this._radians < 0.0)
  4093. this._radians += (2.0 * Math.PI);
  4094. }
  4095. /**
  4096. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4097. */
  4098. Angle.BetweenTwoPoints = function (a, b) {
  4099. var delta = b.subtract(a);
  4100. var theta = Math.atan2(delta.y, delta.x);
  4101. return new Angle(theta);
  4102. };
  4103. /**
  4104. * Returns a new Angle object from the passed float in radians.
  4105. */
  4106. Angle.FromRadians = function (radians) {
  4107. return new Angle(radians);
  4108. };
  4109. /**
  4110. * Returns a new Angle object from the passed float in degrees.
  4111. */
  4112. Angle.FromDegrees = function (degrees) {
  4113. return new Angle(degrees * Math.PI / 180.0);
  4114. };
  4115. return Angle;
  4116. }());
  4117. BABYLON.Angle = Angle;
  4118. var Arc2 = (function () {
  4119. /**
  4120. * Creates an Arc object from the three passed points : start, middle and end.
  4121. */
  4122. function Arc2(startPoint, midPoint, endPoint) {
  4123. this.startPoint = startPoint;
  4124. this.midPoint = midPoint;
  4125. this.endPoint = endPoint;
  4126. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4127. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4128. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4129. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4130. 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);
  4131. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4132. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4133. var a1 = this.startAngle.degrees();
  4134. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4135. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4136. // angles correction
  4137. if (a2 - a1 > +180.0)
  4138. a2 -= 360.0;
  4139. if (a2 - a1 < -180.0)
  4140. a2 += 360.0;
  4141. if (a3 - a2 > +180.0)
  4142. a3 -= 360.0;
  4143. if (a3 - a2 < -180.0)
  4144. a3 += 360.0;
  4145. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4146. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4147. }
  4148. return Arc2;
  4149. }());
  4150. BABYLON.Arc2 = Arc2;
  4151. var Path2 = (function () {
  4152. /**
  4153. * Creates a Path2 object from the starting 2D coordinates x and y.
  4154. */
  4155. function Path2(x, y) {
  4156. this._points = new Array();
  4157. this._length = 0.0;
  4158. this.closed = false;
  4159. this._points.push(new Vector2(x, y));
  4160. }
  4161. /**
  4162. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4163. * Returns the updated Path2.
  4164. */
  4165. Path2.prototype.addLineTo = function (x, y) {
  4166. if (closed) {
  4167. //Tools.Error("cannot add lines to closed paths");
  4168. return this;
  4169. }
  4170. var newPoint = new Vector2(x, y);
  4171. var previousPoint = this._points[this._points.length - 1];
  4172. this._points.push(newPoint);
  4173. this._length += newPoint.subtract(previousPoint).length();
  4174. return this;
  4175. };
  4176. /**
  4177. * 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.
  4178. * Returns the updated Path2.
  4179. */
  4180. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4181. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4182. if (closed) {
  4183. //Tools.Error("cannot add arcs to closed paths");
  4184. return this;
  4185. }
  4186. var startPoint = this._points[this._points.length - 1];
  4187. var midPoint = new Vector2(midX, midY);
  4188. var endPoint = new Vector2(endX, endY);
  4189. var arc = new Arc2(startPoint, midPoint, endPoint);
  4190. var increment = arc.angle.radians() / numberOfSegments;
  4191. if (arc.orientation === Orientation.CW)
  4192. increment *= -1;
  4193. var currentAngle = arc.startAngle.radians() + increment;
  4194. for (var i = 0; i < numberOfSegments; i++) {
  4195. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4196. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4197. this.addLineTo(x, y);
  4198. currentAngle += increment;
  4199. }
  4200. return this;
  4201. };
  4202. /**
  4203. * Closes the Path2.
  4204. * Returns the Path2.
  4205. */
  4206. Path2.prototype.close = function () {
  4207. this.closed = true;
  4208. return this;
  4209. };
  4210. /**
  4211. * Returns the Path2 total length (float).
  4212. */
  4213. Path2.prototype.length = function () {
  4214. var result = this._length;
  4215. if (!this.closed) {
  4216. var lastPoint = this._points[this._points.length - 1];
  4217. var firstPoint = this._points[0];
  4218. result += (firstPoint.subtract(lastPoint).length());
  4219. }
  4220. return result;
  4221. };
  4222. /**
  4223. * Returns the Path2 internal array of points.
  4224. */
  4225. Path2.prototype.getPoints = function () {
  4226. return this._points;
  4227. };
  4228. /**
  4229. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4230. */
  4231. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4232. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4233. //Tools.Error("normalized length position should be between 0 and 1.");
  4234. return Vector2.Zero();
  4235. }
  4236. var lengthPosition = normalizedLengthPosition * this.length();
  4237. var previousOffset = 0;
  4238. for (var i = 0; i < this._points.length; i++) {
  4239. var j = (i + 1) % this._points.length;
  4240. var a = this._points[i];
  4241. var b = this._points[j];
  4242. var bToA = b.subtract(a);
  4243. var nextOffset = (bToA.length() + previousOffset);
  4244. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4245. var dir = bToA.normalize();
  4246. var localOffset = lengthPosition - previousOffset;
  4247. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4248. }
  4249. previousOffset = nextOffset;
  4250. }
  4251. //Tools.Error("internal error");
  4252. return Vector2.Zero();
  4253. };
  4254. /**
  4255. * Returns a new Path2 starting at the coordinates (x, y).
  4256. */
  4257. Path2.StartingAt = function (x, y) {
  4258. return new Path2(x, y);
  4259. };
  4260. return Path2;
  4261. }());
  4262. BABYLON.Path2 = Path2;
  4263. var Path3D = (function () {
  4264. /**
  4265. * new Path3D(path, normal, raw)
  4266. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4267. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4268. * path : an array of Vector3, the curve axis of the Path3D
  4269. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4270. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4271. */
  4272. function Path3D(path, firstNormal, raw) {
  4273. this.path = path;
  4274. this._curve = new Array();
  4275. this._distances = new Array();
  4276. this._tangents = new Array();
  4277. this._normals = new Array();
  4278. this._binormals = new Array();
  4279. for (var p = 0; p < path.length; p++) {
  4280. this._curve[p] = path[p].clone(); // hard copy
  4281. }
  4282. this._raw = raw || false;
  4283. this._compute(firstNormal);
  4284. }
  4285. /**
  4286. * Returns the Path3D array of successive Vector3 designing its curve.
  4287. */
  4288. Path3D.prototype.getCurve = function () {
  4289. return this._curve;
  4290. };
  4291. /**
  4292. * Returns an array populated with tangent vectors on each Path3D curve point.
  4293. */
  4294. Path3D.prototype.getTangents = function () {
  4295. return this._tangents;
  4296. };
  4297. /**
  4298. * Returns an array populated with normal vectors on each Path3D curve point.
  4299. */
  4300. Path3D.prototype.getNormals = function () {
  4301. return this._normals;
  4302. };
  4303. /**
  4304. * Returns an array populated with binormal vectors on each Path3D curve point.
  4305. */
  4306. Path3D.prototype.getBinormals = function () {
  4307. return this._binormals;
  4308. };
  4309. /**
  4310. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4311. */
  4312. Path3D.prototype.getDistances = function () {
  4313. return this._distances;
  4314. };
  4315. /**
  4316. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4317. * Returns the same object updated.
  4318. */
  4319. Path3D.prototype.update = function (path, firstNormal) {
  4320. for (var p = 0; p < path.length; p++) {
  4321. this._curve[p].x = path[p].x;
  4322. this._curve[p].y = path[p].y;
  4323. this._curve[p].z = path[p].z;
  4324. }
  4325. this._compute(firstNormal);
  4326. return this;
  4327. };
  4328. // private function compute() : computes tangents, normals and binormals
  4329. Path3D.prototype._compute = function (firstNormal) {
  4330. var l = this._curve.length;
  4331. // first and last tangents
  4332. this._tangents[0] = this._getFirstNonNullVector(0);
  4333. if (!this._raw) {
  4334. this._tangents[0].normalize();
  4335. }
  4336. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4337. if (!this._raw) {
  4338. this._tangents[l - 1].normalize();
  4339. }
  4340. // normals and binormals at first point : arbitrary vector with _normalVector()
  4341. var tg0 = this._tangents[0];
  4342. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4343. this._normals[0] = pp0;
  4344. if (!this._raw) {
  4345. this._normals[0].normalize();
  4346. }
  4347. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4348. if (!this._raw) {
  4349. this._binormals[0].normalize();
  4350. }
  4351. this._distances[0] = 0.0;
  4352. // normals and binormals : next points
  4353. var prev; // previous vector (segment)
  4354. var cur; // current vector (segment)
  4355. var curTang; // current tangent
  4356. // previous normal
  4357. var prevBinor; // previous binormal
  4358. for (var i = 1; i < l; i++) {
  4359. // tangents
  4360. prev = this._getLastNonNullVector(i);
  4361. if (i < l - 1) {
  4362. cur = this._getFirstNonNullVector(i);
  4363. this._tangents[i] = prev.add(cur);
  4364. this._tangents[i].normalize();
  4365. }
  4366. this._distances[i] = this._distances[i - 1] + prev.length();
  4367. // normals and binormals
  4368. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4369. curTang = this._tangents[i];
  4370. prevBinor = this._binormals[i - 1];
  4371. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4372. if (!this._raw) {
  4373. this._normals[i].normalize();
  4374. }
  4375. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4376. if (!this._raw) {
  4377. this._binormals[i].normalize();
  4378. }
  4379. }
  4380. };
  4381. // private function getFirstNonNullVector(index)
  4382. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4383. Path3D.prototype._getFirstNonNullVector = function (index) {
  4384. var i = 1;
  4385. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4386. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4387. i++;
  4388. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4389. }
  4390. return nNVector;
  4391. };
  4392. // private function getLastNonNullVector(index)
  4393. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4394. Path3D.prototype._getLastNonNullVector = function (index) {
  4395. var i = 1;
  4396. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4397. while (nLVector.length() === 0 && index > i + 1) {
  4398. i++;
  4399. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4400. }
  4401. return nLVector;
  4402. };
  4403. // private function normalVector(v0, vt, va) :
  4404. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4405. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4406. Path3D.prototype._normalVector = function (v0, vt, va) {
  4407. var normal0;
  4408. var tgl = vt.length();
  4409. if (tgl === 0.0) {
  4410. tgl = 1.0;
  4411. }
  4412. if (va === undefined || va === null) {
  4413. var point;
  4414. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4415. point = new Vector3(0.0, -1.0, 0.0);
  4416. }
  4417. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4418. point = new Vector3(1.0, 0.0, 0.0);
  4419. }
  4420. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4421. point = new Vector3(0.0, 0.0, 1.0);
  4422. }
  4423. normal0 = Vector3.Cross(vt, point);
  4424. }
  4425. else {
  4426. normal0 = Vector3.Cross(vt, va);
  4427. Vector3.CrossToRef(normal0, vt, normal0);
  4428. }
  4429. normal0.normalize();
  4430. return normal0;
  4431. };
  4432. return Path3D;
  4433. }());
  4434. BABYLON.Path3D = Path3D;
  4435. var Curve3 = (function () {
  4436. /**
  4437. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4438. * A Curve3 is designed from a series of successive Vector3.
  4439. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4440. */
  4441. function Curve3(points) {
  4442. this._length = 0.0;
  4443. this._points = points;
  4444. this._length = this._computeLength(points);
  4445. }
  4446. /**
  4447. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4448. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4449. * @param v1 (Vector3) the control point
  4450. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4451. * @param nbPoints (integer) the wanted number of points in the curve
  4452. */
  4453. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4454. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4455. var bez = new Array();
  4456. var equation = function (t, val0, val1, val2) {
  4457. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4458. return res;
  4459. };
  4460. for (var i = 0; i <= nbPoints; i++) {
  4461. 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)));
  4462. }
  4463. return new Curve3(bez);
  4464. };
  4465. /**
  4466. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4467. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4468. * @param v1 (Vector3) the first control point
  4469. * @param v2 (Vector3) the second control point
  4470. * @param v3 (Vector3) the end point of the Cubic Bezier
  4471. * @param nbPoints (integer) the wanted number of points in the curve
  4472. */
  4473. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4474. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4475. var bez = new Array();
  4476. var equation = function (t, val0, val1, val2, val3) {
  4477. 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;
  4478. return res;
  4479. };
  4480. for (var i = 0; i <= nbPoints; i++) {
  4481. 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)));
  4482. }
  4483. return new Curve3(bez);
  4484. };
  4485. /**
  4486. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4487. * @param p1 (Vector3) the origin point of the Hermite Spline
  4488. * @param t1 (Vector3) the tangent vector at the origin point
  4489. * @param p2 (Vector3) the end point of the Hermite Spline
  4490. * @param t2 (Vector3) the tangent vector at the end point
  4491. * @param nbPoints (integer) the wanted number of points in the curve
  4492. */
  4493. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4494. var hermite = new Array();
  4495. var step = 1.0 / nbPoints;
  4496. for (var i = 0; i <= nbPoints; i++) {
  4497. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4498. }
  4499. return new Curve3(hermite);
  4500. };
  4501. /**
  4502. * Returns a Curve3 object along a CatmullRom Spline curve :
  4503. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4504. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4505. */
  4506. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4507. var totalPoints = new Array();
  4508. totalPoints.push(points[0].clone());
  4509. Array.prototype.push.apply(totalPoints, points);
  4510. totalPoints.push(points[points.length - 1].clone());
  4511. var catmullRom = new Array();
  4512. var step = 1.0 / nbPoints;
  4513. for (var i = 0; i < totalPoints.length - 3; i++) {
  4514. var amount = 0.0;
  4515. for (var c = 0; c < nbPoints; c++) {
  4516. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4517. amount += step;
  4518. }
  4519. }
  4520. i--;
  4521. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4522. return new Curve3(catmullRom);
  4523. };
  4524. /**
  4525. * Returns the Curve3 stored array of successive Vector3
  4526. */
  4527. Curve3.prototype.getPoints = function () {
  4528. return this._points;
  4529. };
  4530. /**
  4531. * Returns the computed length (float) of the curve.
  4532. */
  4533. Curve3.prototype.length = function () {
  4534. return this._length;
  4535. };
  4536. /**
  4537. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4538. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4539. * curveA and curveB keep unchanged.
  4540. */
  4541. Curve3.prototype.continue = function (curve) {
  4542. var lastPoint = this._points[this._points.length - 1];
  4543. var continuedPoints = this._points.slice();
  4544. var curvePoints = curve.getPoints();
  4545. for (var i = 1; i < curvePoints.length; i++) {
  4546. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4547. }
  4548. var continuedCurve = new Curve3(continuedPoints);
  4549. return continuedCurve;
  4550. };
  4551. Curve3.prototype._computeLength = function (path) {
  4552. var l = 0;
  4553. for (var i = 1; i < path.length; i++) {
  4554. l += (path[i].subtract(path[i - 1])).length();
  4555. }
  4556. return l;
  4557. };
  4558. return Curve3;
  4559. }());
  4560. BABYLON.Curve3 = Curve3;
  4561. // SphericalHarmonics
  4562. var SphericalHarmonics = (function () {
  4563. function SphericalHarmonics() {
  4564. this.L00 = Vector3.Zero();
  4565. this.L1_1 = Vector3.Zero();
  4566. this.L10 = Vector3.Zero();
  4567. this.L11 = Vector3.Zero();
  4568. this.L2_2 = Vector3.Zero();
  4569. this.L2_1 = Vector3.Zero();
  4570. this.L20 = Vector3.Zero();
  4571. this.L21 = Vector3.Zero();
  4572. this.L22 = Vector3.Zero();
  4573. }
  4574. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4575. var colorVector = new Vector3(color.r, color.g, color.b);
  4576. var c = colorVector.scale(deltaSolidAngle);
  4577. this.L00 = this.L00.add(c.scale(0.282095));
  4578. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4579. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4580. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4581. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4582. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4583. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4584. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4585. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4586. };
  4587. SphericalHarmonics.prototype.scale = function (scale) {
  4588. this.L00 = this.L00.scale(scale);
  4589. this.L1_1 = this.L1_1.scale(scale);
  4590. this.L10 = this.L10.scale(scale);
  4591. this.L11 = this.L11.scale(scale);
  4592. this.L2_2 = this.L2_2.scale(scale);
  4593. this.L2_1 = this.L2_1.scale(scale);
  4594. this.L20 = this.L20.scale(scale);
  4595. this.L21 = this.L21.scale(scale);
  4596. this.L22 = this.L22.scale(scale);
  4597. };
  4598. return SphericalHarmonics;
  4599. }());
  4600. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4601. // SphericalPolynomial
  4602. var SphericalPolynomial = (function () {
  4603. function SphericalPolynomial() {
  4604. this.x = Vector3.Zero();
  4605. this.y = Vector3.Zero();
  4606. this.z = Vector3.Zero();
  4607. this.xx = Vector3.Zero();
  4608. this.yy = Vector3.Zero();
  4609. this.zz = Vector3.Zero();
  4610. this.xy = Vector3.Zero();
  4611. this.yz = Vector3.Zero();
  4612. this.zx = Vector3.Zero();
  4613. }
  4614. SphericalPolynomial.prototype.addAmbient = function (color) {
  4615. var colorVector = new Vector3(color.r, color.g, color.b);
  4616. this.xx = this.xx.add(colorVector);
  4617. this.yy = this.yy.add(colorVector);
  4618. this.zz = this.zz.add(colorVector);
  4619. };
  4620. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4621. var result = new SphericalPolynomial();
  4622. result.x = harmonics.L11.scale(1.02333);
  4623. result.y = harmonics.L1_1.scale(1.02333);
  4624. result.z = harmonics.L10.scale(1.02333);
  4625. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4626. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4627. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4628. result.yz = harmonics.L2_1.scale(0.858086);
  4629. result.zx = harmonics.L21.scale(0.858086);
  4630. result.xy = harmonics.L2_2.scale(0.858086);
  4631. return result;
  4632. };
  4633. return SphericalPolynomial;
  4634. }());
  4635. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4636. // Vertex formats
  4637. var PositionNormalVertex = (function () {
  4638. function PositionNormalVertex(position, normal) {
  4639. if (position === void 0) { position = Vector3.Zero(); }
  4640. if (normal === void 0) { normal = Vector3.Up(); }
  4641. this.position = position;
  4642. this.normal = normal;
  4643. }
  4644. PositionNormalVertex.prototype.clone = function () {
  4645. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4646. };
  4647. return PositionNormalVertex;
  4648. }());
  4649. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4650. var PositionNormalTextureVertex = (function () {
  4651. function PositionNormalTextureVertex(position, normal, uv) {
  4652. if (position === void 0) { position = Vector3.Zero(); }
  4653. if (normal === void 0) { normal = Vector3.Up(); }
  4654. if (uv === void 0) { uv = Vector2.Zero(); }
  4655. this.position = position;
  4656. this.normal = normal;
  4657. this.uv = uv;
  4658. }
  4659. PositionNormalTextureVertex.prototype.clone = function () {
  4660. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4661. };
  4662. return PositionNormalTextureVertex;
  4663. }());
  4664. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4665. // Temporary pre-allocated objects for engine internal use
  4666. // usage in any internal function :
  4667. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4668. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4669. var Tmp = (function () {
  4670. function Tmp() {
  4671. }
  4672. return Tmp;
  4673. }());
  4674. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4675. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4676. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4677. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4678. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4679. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4680. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4681. Matrix.Zero(), Matrix.Zero(),
  4682. Matrix.Zero(), Matrix.Zero(),
  4683. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4684. BABYLON.Tmp = Tmp;
  4685. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4686. var MathTmp = (function () {
  4687. function MathTmp() {
  4688. }
  4689. return MathTmp;
  4690. }());
  4691. MathTmp.Vector3 = [Vector3.Zero()];
  4692. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4693. MathTmp.Quaternion = [Quaternion.Zero()];
  4694. })(BABYLON || (BABYLON = {}));
  4695. //# sourceMappingURL=babylon.math.js.map
  4696. //# sourceMappingURL=babylon.mixins.js.map
  4697. var BABYLON;
  4698. (function (BABYLON) {
  4699. function generateSerializableMember(type, sourceName) {
  4700. return function (target, propertyKey) {
  4701. if (!target.__serializableMembers) {
  4702. target.__serializableMembers = {};
  4703. }
  4704. if (!target.__serializableMembers[propertyKey]) {
  4705. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4706. }
  4707. };
  4708. }
  4709. function generateExpandMember(setCallback) {
  4710. return function (target, propertyKey) {
  4711. if (setCallback) {
  4712. var key = "_" + propertyKey;
  4713. Object.defineProperty(target, propertyKey, {
  4714. get: function () {
  4715. return this[key];
  4716. },
  4717. set: function (value) {
  4718. if (this[key] === value) {
  4719. return;
  4720. }
  4721. this[key] = value;
  4722. target[setCallback].apply(this);
  4723. },
  4724. enumerable: true,
  4725. configurable: true
  4726. });
  4727. }
  4728. };
  4729. }
  4730. function expandToProperty(callback) {
  4731. return generateExpandMember(callback);
  4732. }
  4733. BABYLON.expandToProperty = expandToProperty;
  4734. function serialize(sourceName) {
  4735. return generateSerializableMember(0, sourceName); // value member
  4736. }
  4737. BABYLON.serialize = serialize;
  4738. function serializeAsTexture(sourceName) {
  4739. return generateSerializableMember(1, sourceName); // texture member
  4740. }
  4741. BABYLON.serializeAsTexture = serializeAsTexture;
  4742. function serializeAsColor3(sourceName) {
  4743. return generateSerializableMember(2, sourceName); // color3 member
  4744. }
  4745. BABYLON.serializeAsColor3 = serializeAsColor3;
  4746. function serializeAsFresnelParameters(sourceName) {
  4747. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4748. }
  4749. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4750. function serializeAsVector2(sourceName) {
  4751. return generateSerializableMember(4, sourceName); // vector2 member
  4752. }
  4753. BABYLON.serializeAsVector2 = serializeAsVector2;
  4754. function serializeAsVector3(sourceName) {
  4755. return generateSerializableMember(5, sourceName); // vector3 member
  4756. }
  4757. BABYLON.serializeAsVector3 = serializeAsVector3;
  4758. function serializeAsMeshReference(sourceName) {
  4759. return generateSerializableMember(6, sourceName); // mesh reference member
  4760. }
  4761. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4762. function serializeAsColorCurves(sourceName) {
  4763. return generateSerializableMember(7, sourceName); // color curves
  4764. }
  4765. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4766. var SerializationHelper = (function () {
  4767. function SerializationHelper() {
  4768. }
  4769. SerializationHelper.Serialize = function (entity, serializationObject) {
  4770. if (!serializationObject) {
  4771. serializationObject = {};
  4772. }
  4773. // Tags
  4774. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4775. // Properties
  4776. for (var property in entity.__serializableMembers) {
  4777. var propertyDescriptor = entity.__serializableMembers[property];
  4778. var targetPropertyName = propertyDescriptor.sourceName || property;
  4779. var propertyType = propertyDescriptor.type;
  4780. var sourceProperty = entity[property];
  4781. if (sourceProperty !== undefined && sourceProperty !== null) {
  4782. switch (propertyType) {
  4783. case 0:
  4784. serializationObject[targetPropertyName] = sourceProperty;
  4785. break;
  4786. case 1:
  4787. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4788. break;
  4789. case 2:
  4790. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4791. break;
  4792. case 3:
  4793. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4794. break;
  4795. case 4:
  4796. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4797. break;
  4798. case 5:
  4799. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4800. break;
  4801. case 6:
  4802. serializationObject[targetPropertyName] = sourceProperty.id;
  4803. break;
  4804. case 7:
  4805. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4806. break;
  4807. }
  4808. }
  4809. }
  4810. return serializationObject;
  4811. };
  4812. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4813. var destination = creationFunction();
  4814. // Tags
  4815. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4816. // Properties
  4817. for (var property in destination.__serializableMembers) {
  4818. var propertyDescriptor = destination.__serializableMembers[property];
  4819. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4820. var propertyType = propertyDescriptor.type;
  4821. if (sourceProperty !== undefined && sourceProperty !== null) {
  4822. switch (propertyType) {
  4823. case 0:
  4824. destination[property] = sourceProperty;
  4825. break;
  4826. case 1:
  4827. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4828. break;
  4829. case 2:
  4830. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4831. break;
  4832. case 3:
  4833. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4834. break;
  4835. case 4:
  4836. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4837. break;
  4838. case 5:
  4839. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4840. break;
  4841. case 6:
  4842. destination[property] = scene.getLastMeshByID(sourceProperty);
  4843. break;
  4844. case 7:
  4845. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4846. break;
  4847. }
  4848. }
  4849. }
  4850. return destination;
  4851. };
  4852. SerializationHelper.Clone = function (creationFunction, source) {
  4853. var destination = creationFunction();
  4854. // Tags
  4855. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4856. // Properties
  4857. for (var property in destination.__serializableMembers) {
  4858. var propertyDescriptor = destination.__serializableMembers[property];
  4859. var sourceProperty = source[property];
  4860. var propertyType = propertyDescriptor.type;
  4861. if (sourceProperty !== undefined && sourceProperty !== null) {
  4862. switch (propertyType) {
  4863. case 0: // Value
  4864. case 6:
  4865. destination[property] = sourceProperty;
  4866. break;
  4867. case 1: // Texture
  4868. case 2: // Color3
  4869. case 3: // FresnelParameters
  4870. case 4: // Vector2
  4871. case 5: // Vector3
  4872. case 7:
  4873. destination[property] = sourceProperty.clone();
  4874. break;
  4875. }
  4876. }
  4877. }
  4878. return destination;
  4879. };
  4880. return SerializationHelper;
  4881. }());
  4882. BABYLON.SerializationHelper = SerializationHelper;
  4883. })(BABYLON || (BABYLON = {}));
  4884. //# sourceMappingURL=babylon.decorators.js.map
  4885. var BABYLON;
  4886. (function (BABYLON) {
  4887. /**
  4888. * A class serves as a medium between the observable and its observers
  4889. */
  4890. var EventState = (function () {
  4891. /**
  4892. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4893. */
  4894. function EventState(mask, skipNextObservers) {
  4895. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4896. this.initalize(mask, skipNextObservers);
  4897. }
  4898. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4899. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4900. this.mask = mask;
  4901. this.skipNextObservers = skipNextObservers;
  4902. return this;
  4903. };
  4904. return EventState;
  4905. }());
  4906. BABYLON.EventState = EventState;
  4907. /**
  4908. * Represent an Observer registered to a given Observable object.
  4909. */
  4910. var Observer = (function () {
  4911. function Observer(callback, mask) {
  4912. this.callback = callback;
  4913. this.mask = mask;
  4914. }
  4915. return Observer;
  4916. }());
  4917. BABYLON.Observer = Observer;
  4918. /**
  4919. * The Observable class is a simple implementation of the Observable pattern.
  4920. * 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.
  4921. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4922. * 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).
  4923. * 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.
  4924. */
  4925. var Observable = (function () {
  4926. function Observable() {
  4927. this._observers = new Array();
  4928. this._eventState = new EventState(0);
  4929. }
  4930. /**
  4931. * Create a new Observer with the specified callback
  4932. * @param callback the callback that will be executed for that Observer
  4933. * @param mask the mask used to filter observers
  4934. * @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.
  4935. */
  4936. Observable.prototype.add = function (callback, mask, insertFirst) {
  4937. if (mask === void 0) { mask = -1; }
  4938. if (insertFirst === void 0) { insertFirst = false; }
  4939. if (!callback) {
  4940. return null;
  4941. }
  4942. var observer = new Observer(callback, mask);
  4943. if (insertFirst) {
  4944. this._observers.unshift(observer);
  4945. }
  4946. else {
  4947. this._observers.push(observer);
  4948. }
  4949. return observer;
  4950. };
  4951. /**
  4952. * Remove an Observer from the Observable object
  4953. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4954. */
  4955. Observable.prototype.remove = function (observer) {
  4956. var index = this._observers.indexOf(observer);
  4957. if (index !== -1) {
  4958. this._observers.splice(index, 1);
  4959. return true;
  4960. }
  4961. return false;
  4962. };
  4963. /**
  4964. * Remove a callback from the Observable object
  4965. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4966. */
  4967. Observable.prototype.removeCallback = function (callback) {
  4968. for (var index = 0; index < this._observers.length; index++) {
  4969. if (this._observers[index].callback === callback) {
  4970. this._observers.splice(index, 1);
  4971. return true;
  4972. }
  4973. }
  4974. return false;
  4975. };
  4976. /**
  4977. * Notify all Observers by calling their respective callback with the given data
  4978. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4979. * @param eventData
  4980. * @param mask
  4981. */
  4982. Observable.prototype.notifyObservers = function (eventData, mask) {
  4983. if (mask === void 0) { mask = -1; }
  4984. var state = this._eventState;
  4985. state.mask = mask;
  4986. state.skipNextObservers = false;
  4987. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4988. var obs = _a[_i];
  4989. if (obs.mask & mask) {
  4990. obs.callback(eventData, state);
  4991. }
  4992. if (state.skipNextObservers) {
  4993. return false;
  4994. }
  4995. }
  4996. return true;
  4997. };
  4998. /**
  4999. * return true is the Observable has at least one Observer registered
  5000. */
  5001. Observable.prototype.hasObservers = function () {
  5002. return this._observers.length > 0;
  5003. };
  5004. /**
  5005. * Clear the list of observers
  5006. */
  5007. Observable.prototype.clear = function () {
  5008. this._observers = new Array();
  5009. };
  5010. /**
  5011. * Clone the current observable
  5012. */
  5013. Observable.prototype.clone = function () {
  5014. var result = new Observable();
  5015. result._observers = this._observers.slice(0);
  5016. return result;
  5017. };
  5018. /**
  5019. * Does this observable handles observer registered with a given mask
  5020. * @param {number} trigger - the mask to be tested
  5021. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5022. **/
  5023. Observable.prototype.hasSpecificMask = function (mask) {
  5024. if (mask === void 0) { mask = -1; }
  5025. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5026. var obs = _a[_i];
  5027. if (obs.mask & mask && obs.mask === mask) {
  5028. return true;
  5029. }
  5030. }
  5031. return false;
  5032. };
  5033. return Observable;
  5034. }());
  5035. BABYLON.Observable = Observable;
  5036. })(BABYLON || (BABYLON = {}));
  5037. //# sourceMappingURL=babylon.observable.js.map
  5038. var BABYLON;
  5039. (function (BABYLON) {
  5040. var SmartArray = (function () {
  5041. function SmartArray(capacity) {
  5042. this.length = 0;
  5043. this._duplicateId = 0;
  5044. this.data = new Array(capacity);
  5045. this._id = SmartArray._GlobalId++;
  5046. }
  5047. SmartArray.prototype.push = function (value) {
  5048. this.data[this.length++] = value;
  5049. if (this.length > this.data.length) {
  5050. this.data.length *= 2;
  5051. }
  5052. if (!value.__smartArrayFlags) {
  5053. value.__smartArrayFlags = {};
  5054. }
  5055. value.__smartArrayFlags[this._id] = this._duplicateId;
  5056. };
  5057. SmartArray.prototype.forEach = function (func) {
  5058. for (var index = 0; index < this.length; index++) {
  5059. func(this.data[index]);
  5060. }
  5061. };
  5062. SmartArray.prototype.pushNoDuplicate = function (value) {
  5063. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5064. return false;
  5065. }
  5066. this.push(value);
  5067. return true;
  5068. };
  5069. SmartArray.prototype.sort = function (compareFn) {
  5070. this.data.sort(compareFn);
  5071. };
  5072. SmartArray.prototype.reset = function () {
  5073. this.length = 0;
  5074. this._duplicateId++;
  5075. };
  5076. SmartArray.prototype.dispose = function () {
  5077. this.reset();
  5078. this.data.length = 0;
  5079. };
  5080. SmartArray.prototype.concat = function (array) {
  5081. if (array.length === 0) {
  5082. return;
  5083. }
  5084. if (this.length + array.length > this.data.length) {
  5085. this.data.length = (this.length + array.length) * 2;
  5086. }
  5087. for (var index = 0; index < array.length; index++) {
  5088. this.data[this.length++] = (array.data || array)[index];
  5089. }
  5090. };
  5091. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5092. if (array.length === 0) {
  5093. return;
  5094. }
  5095. if (this.length + array.length > this.data.length) {
  5096. this.data.length = (this.length + array.length) * 2;
  5097. }
  5098. for (var index = 0; index < array.length; index++) {
  5099. var item = (array.data || array)[index];
  5100. this.pushNoDuplicate(item);
  5101. }
  5102. };
  5103. SmartArray.prototype.indexOf = function (value) {
  5104. var position = this.data.indexOf(value);
  5105. if (position >= this.length) {
  5106. return -1;
  5107. }
  5108. return position;
  5109. };
  5110. SmartArray.prototype.contains = function (value) {
  5111. return this.data.indexOf(value) !== -1;
  5112. };
  5113. return SmartArray;
  5114. }());
  5115. // Statics
  5116. SmartArray._GlobalId = 0;
  5117. BABYLON.SmartArray = SmartArray;
  5118. })(BABYLON || (BABYLON = {}));
  5119. //# sourceMappingURL=babylon.smartArray.js.map
  5120. var BABYLON;
  5121. (function (BABYLON) {
  5122. // Screenshots
  5123. var screenshotCanvas;
  5124. var cloneValue = function (source, destinationObject) {
  5125. if (!source)
  5126. return null;
  5127. if (source instanceof BABYLON.Mesh) {
  5128. return null;
  5129. }
  5130. if (source instanceof BABYLON.SubMesh) {
  5131. return source.clone(destinationObject);
  5132. }
  5133. else if (source.clone) {
  5134. return source.clone();
  5135. }
  5136. return null;
  5137. };
  5138. var Tools = (function () {
  5139. function Tools() {
  5140. }
  5141. ;
  5142. Tools.Instantiate = function (className) {
  5143. var arr = className.split(".");
  5144. var fn = (window || this);
  5145. for (var i = 0, len = arr.length; i < len; i++) {
  5146. fn = fn[arr[i]];
  5147. }
  5148. if (typeof fn !== "function") {
  5149. return null;
  5150. }
  5151. return fn;
  5152. };
  5153. Tools.SetImmediate = function (action) {
  5154. if (window.setImmediate) {
  5155. window.setImmediate(action);
  5156. }
  5157. else {
  5158. setTimeout(action, 1);
  5159. }
  5160. };
  5161. Tools.IsExponentOfTwo = function (value) {
  5162. var count = 1;
  5163. do {
  5164. count *= 2;
  5165. } while (count < value);
  5166. return count === value;
  5167. };
  5168. Tools.GetExponentOfTwo = function (value, max) {
  5169. var count = 1;
  5170. do {
  5171. count *= 2;
  5172. } while (count < value);
  5173. if (count > max)
  5174. count = max;
  5175. return count;
  5176. };
  5177. Tools.GetFilename = function (path) {
  5178. var index = path.lastIndexOf("/");
  5179. if (index < 0)
  5180. return path;
  5181. return path.substring(index + 1);
  5182. };
  5183. Tools.GetDOMTextContent = function (element) {
  5184. var result = "";
  5185. var child = element.firstChild;
  5186. while (child) {
  5187. if (child.nodeType === 3) {
  5188. result += child.textContent;
  5189. }
  5190. child = child.nextSibling;
  5191. }
  5192. return result;
  5193. };
  5194. Tools.ToDegrees = function (angle) {
  5195. return angle * 180 / Math.PI;
  5196. };
  5197. Tools.ToRadians = function (angle) {
  5198. return angle * Math.PI / 180;
  5199. };
  5200. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5201. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5202. var output = "";
  5203. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5204. var i = 0;
  5205. var bytes = new Uint8Array(buffer);
  5206. while (i < bytes.length) {
  5207. chr1 = bytes[i++];
  5208. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5209. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5210. enc1 = chr1 >> 2;
  5211. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5212. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5213. enc4 = chr3 & 63;
  5214. if (isNaN(chr2)) {
  5215. enc3 = enc4 = 64;
  5216. }
  5217. else if (isNaN(chr3)) {
  5218. enc4 = 64;
  5219. }
  5220. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5221. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5222. }
  5223. return "data:image/png;base64," + output;
  5224. };
  5225. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5226. if (bias === void 0) { bias = null; }
  5227. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5228. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5229. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5230. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5231. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5232. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5233. }
  5234. if (bias) {
  5235. minimum.x -= minimum.x * bias.x + bias.y;
  5236. minimum.y -= minimum.y * bias.x + bias.y;
  5237. minimum.z -= minimum.z * bias.x + bias.y;
  5238. maximum.x += maximum.x * bias.x + bias.y;
  5239. maximum.y += maximum.y * bias.x + bias.y;
  5240. maximum.z += maximum.z * bias.x + bias.y;
  5241. }
  5242. return {
  5243. minimum: minimum,
  5244. maximum: maximum
  5245. };
  5246. };
  5247. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5248. if (bias === void 0) { bias = null; }
  5249. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5250. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5251. if (!stride) {
  5252. stride = 3;
  5253. }
  5254. for (var index = start; index < start + count; index++) {
  5255. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5256. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5257. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5258. }
  5259. if (bias) {
  5260. minimum.x -= minimum.x * bias.x + bias.y;
  5261. minimum.y -= minimum.y * bias.x + bias.y;
  5262. minimum.z -= minimum.z * bias.x + bias.y;
  5263. maximum.x += maximum.x * bias.x + bias.y;
  5264. maximum.y += maximum.y * bias.x + bias.y;
  5265. maximum.z += maximum.z * bias.x + bias.y;
  5266. }
  5267. return {
  5268. minimum: minimum,
  5269. maximum: maximum
  5270. };
  5271. };
  5272. Tools.Vector2ArrayFeeder = function (array) {
  5273. return function (index) {
  5274. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5275. var length = isFloatArray ? array.length / 2 : array.length;
  5276. if (index >= length) {
  5277. return null;
  5278. }
  5279. if (isFloatArray) {
  5280. var fa = array;
  5281. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5282. }
  5283. var a = array;
  5284. return a[index];
  5285. };
  5286. };
  5287. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5288. if (bias === void 0) { bias = null; }
  5289. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5290. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5291. var i = 0;
  5292. var cur = feeder(i++);
  5293. while (cur) {
  5294. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5295. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5296. cur = feeder(i++);
  5297. }
  5298. if (bias) {
  5299. minimum.x -= minimum.x * bias.x + bias.y;
  5300. minimum.y -= minimum.y * bias.x + bias.y;
  5301. maximum.x += maximum.x * bias.x + bias.y;
  5302. maximum.y += maximum.y * bias.x + bias.y;
  5303. }
  5304. return {
  5305. minimum: minimum,
  5306. maximum: maximum
  5307. };
  5308. };
  5309. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5310. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5311. return undefined;
  5312. return Array.isArray(obj) ? obj : [obj];
  5313. };
  5314. // Misc.
  5315. Tools.GetPointerPrefix = function () {
  5316. var eventPrefix = "pointer";
  5317. // Check if pointer events are supported
  5318. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5319. eventPrefix = "mouse";
  5320. }
  5321. return eventPrefix;
  5322. };
  5323. /**
  5324. * @param func - the function to be called
  5325. * @param requester - the object that will request the next frame. Falls back to window.
  5326. */
  5327. Tools.QueueNewFrame = function (func, requester) {
  5328. if (requester === void 0) { requester = window; }
  5329. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5330. /*if(requester.isPresenting) {
  5331. return;
  5332. } else*/ if (requester.requestAnimationFrame)
  5333. requester.requestAnimationFrame(func);
  5334. else if (requester.msRequestAnimationFrame)
  5335. requester.msRequestAnimationFrame(func);
  5336. else if (requester.webkitRequestAnimationFrame)
  5337. requester.webkitRequestAnimationFrame(func);
  5338. else if (requester.mozRequestAnimationFrame)
  5339. requester.mozRequestAnimationFrame(func);
  5340. else if (requester.oRequestAnimationFrame)
  5341. requester.oRequestAnimationFrame(func);
  5342. else {
  5343. window.setTimeout(func, 16);
  5344. }
  5345. };
  5346. Tools.RequestFullscreen = function (element) {
  5347. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5348. if (!requestFunction)
  5349. return;
  5350. requestFunction.call(element);
  5351. };
  5352. Tools.ExitFullscreen = function () {
  5353. if (document.exitFullscreen) {
  5354. document.exitFullscreen();
  5355. }
  5356. else if (document.mozCancelFullScreen) {
  5357. document.mozCancelFullScreen();
  5358. }
  5359. else if (document.webkitCancelFullScreen) {
  5360. document.webkitCancelFullScreen();
  5361. }
  5362. else if (document.msCancelFullScreen) {
  5363. document.msCancelFullScreen();
  5364. }
  5365. };
  5366. Tools.SetCorsBehavior = function (url, img) {
  5367. if (Tools.CorsBehavior) {
  5368. switch (typeof (Tools.CorsBehavior)) {
  5369. case "function":
  5370. var result = Tools.CorsBehavior(url);
  5371. if (result) {
  5372. img.crossOrigin = result;
  5373. }
  5374. break;
  5375. case "string":
  5376. default:
  5377. img.crossOrigin = Tools.CorsBehavior;
  5378. break;
  5379. }
  5380. }
  5381. };
  5382. // External files
  5383. Tools.CleanUrl = function (url) {
  5384. url = url.replace(/#/mg, "%23");
  5385. return url;
  5386. };
  5387. Tools.LoadImage = function (url, onload, onerror, database) {
  5388. if (url instanceof ArrayBuffer) {
  5389. url = Tools.EncodeArrayBufferTobase64(url);
  5390. }
  5391. url = Tools.CleanUrl(url);
  5392. var img = new Image();
  5393. if (url.substr(0, 5) !== "data:") {
  5394. Tools.SetCorsBehavior(url, img);
  5395. }
  5396. img.onload = function () {
  5397. onload(img);
  5398. };
  5399. img.onerror = function (err) {
  5400. Tools.Error("Error while trying to load image: " + url);
  5401. if (Tools.UseFallbackTexture) {
  5402. img.src = Tools.fallbackTexture;
  5403. onload(img);
  5404. }
  5405. else {
  5406. onerror();
  5407. }
  5408. };
  5409. var noIndexedDB = function () {
  5410. img.src = url;
  5411. };
  5412. var loadFromIndexedDB = function () {
  5413. database.loadImageFromDB(url, img);
  5414. };
  5415. //ANY database to do!
  5416. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5417. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5418. }
  5419. else {
  5420. if (url.indexOf("file:") === -1) {
  5421. noIndexedDB();
  5422. }
  5423. else {
  5424. var textureName = url.substring(5).toLowerCase();
  5425. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5426. try {
  5427. var blobURL;
  5428. try {
  5429. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5430. }
  5431. catch (ex) {
  5432. // Chrome doesn't support oneTimeOnly parameter
  5433. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5434. }
  5435. img.src = blobURL;
  5436. }
  5437. catch (e) {
  5438. img.src = null;
  5439. }
  5440. }
  5441. else {
  5442. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5443. img.src = Tools.fallbackTexture;
  5444. }
  5445. }
  5446. }
  5447. return img;
  5448. };
  5449. //ANY
  5450. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5451. url = Tools.CleanUrl(url);
  5452. var noIndexedDB = function () {
  5453. var request = new XMLHttpRequest();
  5454. var loadUrl = Tools.BaseUrl + url;
  5455. request.open('GET', loadUrl, true);
  5456. if (useArrayBuffer) {
  5457. request.responseType = "arraybuffer";
  5458. }
  5459. request.onprogress = progressCallBack;
  5460. request.onreadystatechange = function () {
  5461. if (request.readyState === 4) {
  5462. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5463. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5464. callback(!useArrayBuffer ? request.responseText : request.response);
  5465. }
  5466. else {
  5467. if (onError) {
  5468. onError();
  5469. }
  5470. else {
  5471. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5472. }
  5473. }
  5474. }
  5475. };
  5476. request.send(null);
  5477. };
  5478. var loadFromIndexedDB = function () {
  5479. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5480. };
  5481. if (url.indexOf("file:") !== -1) {
  5482. var fileName = url.substring(5).toLowerCase();
  5483. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5484. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5485. }
  5486. else {
  5487. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5488. }
  5489. }
  5490. else {
  5491. // Caching all files
  5492. if (database && database.enableSceneOffline) {
  5493. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5494. }
  5495. else {
  5496. noIndexedDB();
  5497. }
  5498. }
  5499. };
  5500. /**
  5501. * Load a script (identified by an url). When the url returns, the
  5502. * content of this file is added into a new script element, attached to the DOM (body element)
  5503. */
  5504. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5505. var head = document.getElementsByTagName('head')[0];
  5506. var script = document.createElement('script');
  5507. script.type = 'text/javascript';
  5508. script.src = scriptUrl;
  5509. var self = this;
  5510. script.onload = function () {
  5511. if (onSuccess) {
  5512. onSuccess();
  5513. }
  5514. };
  5515. script.onerror = function () {
  5516. if (onError) {
  5517. onError();
  5518. }
  5519. };
  5520. head.appendChild(script);
  5521. };
  5522. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5523. var reader = new FileReader();
  5524. reader.onload = function (e) {
  5525. //target doesn't have result from ts 1.3
  5526. callback(e.target['result']);
  5527. };
  5528. reader.onprogress = progressCallback;
  5529. reader.readAsDataURL(fileToLoad);
  5530. };
  5531. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5532. var reader = new FileReader();
  5533. reader.onerror = function (e) {
  5534. Tools.Log("Error while reading file: " + fileToLoad.name);
  5535. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5536. };
  5537. reader.onload = function (e) {
  5538. //target doesn't have result from ts 1.3
  5539. callback(e.target['result']);
  5540. };
  5541. reader.onprogress = progressCallBack;
  5542. if (!useArrayBuffer) {
  5543. // Asynchronous read
  5544. reader.readAsText(fileToLoad);
  5545. }
  5546. else {
  5547. reader.readAsArrayBuffer(fileToLoad);
  5548. }
  5549. };
  5550. //returns a downloadable url to a file content.
  5551. Tools.FileAsURL = function (content) {
  5552. var fileBlob = new Blob([content]);
  5553. var url = window.URL || window.webkitURL;
  5554. var link = url.createObjectURL(fileBlob);
  5555. return link;
  5556. };
  5557. // Misc.
  5558. Tools.Format = function (value, decimals) {
  5559. if (decimals === void 0) { decimals = 2; }
  5560. return value.toFixed(decimals);
  5561. };
  5562. Tools.CheckExtends = function (v, min, max) {
  5563. if (v.x < min.x)
  5564. min.x = v.x;
  5565. if (v.y < min.y)
  5566. min.y = v.y;
  5567. if (v.z < min.z)
  5568. min.z = v.z;
  5569. if (v.x > max.x)
  5570. max.x = v.x;
  5571. if (v.y > max.y)
  5572. max.y = v.y;
  5573. if (v.z > max.z)
  5574. max.z = v.z;
  5575. };
  5576. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5577. for (var prop in source) {
  5578. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5579. continue;
  5580. }
  5581. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5582. continue;
  5583. }
  5584. var sourceValue = source[prop];
  5585. var typeOfSourceValue = typeof sourceValue;
  5586. if (typeOfSourceValue === "function") {
  5587. continue;
  5588. }
  5589. if (typeOfSourceValue === "object") {
  5590. if (sourceValue instanceof Array) {
  5591. destination[prop] = [];
  5592. if (sourceValue.length > 0) {
  5593. if (typeof sourceValue[0] == "object") {
  5594. for (var index = 0; index < sourceValue.length; index++) {
  5595. var clonedValue = cloneValue(sourceValue[index], destination);
  5596. if (destination[prop].indexOf(clonedValue) === -1) {
  5597. destination[prop].push(clonedValue);
  5598. }
  5599. }
  5600. }
  5601. else {
  5602. destination[prop] = sourceValue.slice(0);
  5603. }
  5604. }
  5605. }
  5606. else {
  5607. destination[prop] = cloneValue(sourceValue, destination);
  5608. }
  5609. }
  5610. else {
  5611. destination[prop] = sourceValue;
  5612. }
  5613. }
  5614. };
  5615. Tools.IsEmpty = function (obj) {
  5616. for (var i in obj) {
  5617. return false;
  5618. }
  5619. return true;
  5620. };
  5621. Tools.RegisterTopRootEvents = function (events) {
  5622. for (var index = 0; index < events.length; index++) {
  5623. var event = events[index];
  5624. window.addEventListener(event.name, event.handler, false);
  5625. try {
  5626. if (window.parent) {
  5627. window.parent.addEventListener(event.name, event.handler, false);
  5628. }
  5629. }
  5630. catch (e) {
  5631. // Silently fails...
  5632. }
  5633. }
  5634. };
  5635. Tools.UnregisterTopRootEvents = function (events) {
  5636. for (var index = 0; index < events.length; index++) {
  5637. var event = events[index];
  5638. window.removeEventListener(event.name, event.handler);
  5639. try {
  5640. if (window.parent) {
  5641. window.parent.removeEventListener(event.name, event.handler);
  5642. }
  5643. }
  5644. catch (e) {
  5645. // Silently fails...
  5646. }
  5647. }
  5648. };
  5649. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5650. if (mimeType === void 0) { mimeType = "image/png"; }
  5651. // Read the contents of the framebuffer
  5652. var numberOfChannelsByLine = width * 4;
  5653. var halfHeight = height / 2;
  5654. //Reading datas from WebGL
  5655. var data = engine.readPixels(0, 0, width, height);
  5656. //To flip image on Y axis.
  5657. for (var i = 0; i < halfHeight; i++) {
  5658. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5659. var currentCell = j + i * numberOfChannelsByLine;
  5660. var targetLine = height - i - 1;
  5661. var targetCell = j + targetLine * numberOfChannelsByLine;
  5662. var temp = data[currentCell];
  5663. data[currentCell] = data[targetCell];
  5664. data[targetCell] = temp;
  5665. }
  5666. }
  5667. // Create a 2D canvas to store the result
  5668. if (!screenshotCanvas) {
  5669. screenshotCanvas = document.createElement('canvas');
  5670. }
  5671. screenshotCanvas.width = width;
  5672. screenshotCanvas.height = height;
  5673. var context = screenshotCanvas.getContext('2d');
  5674. // Copy the pixels to a 2D canvas
  5675. var imageData = context.createImageData(width, height);
  5676. var castData = (imageData.data);
  5677. castData.set(data);
  5678. context.putImageData(imageData, 0, 0);
  5679. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5680. };
  5681. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5682. if (mimeType === void 0) { mimeType = "image/png"; }
  5683. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5684. if (successCallback) {
  5685. successCallback(base64Image);
  5686. }
  5687. else {
  5688. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5689. if (("download" in document.createElement("a"))) {
  5690. var a = window.document.createElement("a");
  5691. a.href = base64Image;
  5692. var date = new Date();
  5693. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5694. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5695. window.document.body.appendChild(a);
  5696. a.addEventListener("click", function () {
  5697. a.parentElement.removeChild(a);
  5698. });
  5699. a.click();
  5700. //Or opening a new tab with the image if it is not possible to automatically start download.
  5701. }
  5702. else {
  5703. var newWindow = window.open("");
  5704. var img = newWindow.document.createElement("img");
  5705. img.src = base64Image;
  5706. newWindow.document.body.appendChild(img);
  5707. }
  5708. }
  5709. };
  5710. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5711. if (mimeType === void 0) { mimeType = "image/png"; }
  5712. var width;
  5713. var height;
  5714. // If a precision value is specified
  5715. if (size.precision) {
  5716. width = Math.round(engine.getRenderWidth() * size.precision);
  5717. height = Math.round(width / engine.getAspectRatio(camera));
  5718. }
  5719. else if (size.width && size.height) {
  5720. width = size.width;
  5721. height = size.height;
  5722. }
  5723. else if (size.width && !size.height) {
  5724. width = size.width;
  5725. height = Math.round(width / engine.getAspectRatio(camera));
  5726. }
  5727. else if (size.height && !size.width) {
  5728. height = size.height;
  5729. width = Math.round(height * engine.getAspectRatio(camera));
  5730. }
  5731. else if (!isNaN(size)) {
  5732. height = size;
  5733. width = size;
  5734. }
  5735. else {
  5736. Tools.Error("Invalid 'size' parameter !");
  5737. return;
  5738. }
  5739. if (!screenshotCanvas) {
  5740. screenshotCanvas = document.createElement('canvas');
  5741. }
  5742. screenshotCanvas.width = width;
  5743. screenshotCanvas.height = height;
  5744. var renderContext = screenshotCanvas.getContext("2d");
  5745. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5746. var newWidth = width;
  5747. var newHeight = newWidth / ratio;
  5748. if (newHeight > height) {
  5749. newHeight = height;
  5750. newWidth = newHeight * ratio;
  5751. }
  5752. var offsetX = Math.max(0, width - newWidth) / 2;
  5753. var offsetY = Math.max(0, height - newHeight) / 2;
  5754. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5755. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5756. };
  5757. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5758. if (mimeType === void 0) { mimeType = "image/png"; }
  5759. if (samples === void 0) { samples = 1; }
  5760. var width;
  5761. var height;
  5762. //If a precision value is specified
  5763. if (size.precision) {
  5764. width = Math.round(engine.getRenderWidth() * size.precision);
  5765. height = Math.round(width / engine.getAspectRatio(camera));
  5766. size = { width: width, height: height };
  5767. }
  5768. else if (size.width && size.height) {
  5769. width = size.width;
  5770. height = size.height;
  5771. }
  5772. else if (size.width && !size.height) {
  5773. width = size.width;
  5774. height = Math.round(width / engine.getAspectRatio(camera));
  5775. size = { width: width, height: height };
  5776. }
  5777. else if (size.height && !size.width) {
  5778. height = size.height;
  5779. width = Math.round(height * engine.getAspectRatio(camera));
  5780. size = { width: width, height: height };
  5781. }
  5782. else if (!isNaN(size)) {
  5783. height = size;
  5784. width = size;
  5785. }
  5786. else {
  5787. Tools.Error("Invalid 'size' parameter !");
  5788. return;
  5789. }
  5790. var scene = camera.getScene();
  5791. var previousCamera = null;
  5792. if (scene.activeCamera !== camera) {
  5793. previousCamera = scene.activeCamera;
  5794. scene.activeCamera = camera;
  5795. }
  5796. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5797. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5798. texture.renderList = scene.meshes;
  5799. texture.samples = samples;
  5800. texture.onAfterRenderObservable.add(function () {
  5801. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5802. });
  5803. scene.incrementRenderId();
  5804. scene.resetCachedMaterial();
  5805. texture.render(true);
  5806. texture.dispose();
  5807. if (previousCamera) {
  5808. scene.activeCamera = previousCamera;
  5809. }
  5810. camera.getProjectionMatrix(true); // Force cache refresh;
  5811. };
  5812. // XHR response validator for local file scenario
  5813. Tools.ValidateXHRData = function (xhr, dataType) {
  5814. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5815. if (dataType === void 0) { dataType = 7; }
  5816. try {
  5817. if (dataType & 1) {
  5818. if (xhr.responseText && xhr.responseText.length > 0) {
  5819. return true;
  5820. }
  5821. else if (dataType === 1) {
  5822. return false;
  5823. }
  5824. }
  5825. if (dataType & 2) {
  5826. // Check header width and height since there is no "TGA" magic number
  5827. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5828. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5829. return true;
  5830. }
  5831. else if (dataType === 2) {
  5832. return false;
  5833. }
  5834. }
  5835. if (dataType & 4) {
  5836. // Check for the "DDS" magic number
  5837. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5838. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5839. return true;
  5840. }
  5841. else {
  5842. return false;
  5843. }
  5844. }
  5845. }
  5846. catch (e) {
  5847. // Global protection
  5848. }
  5849. return false;
  5850. };
  5851. /**
  5852. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5853. * Be aware Math.random() could cause collisions, but:
  5854. * "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"
  5855. */
  5856. Tools.RandomId = function () {
  5857. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5858. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5859. return v.toString(16);
  5860. });
  5861. };
  5862. Object.defineProperty(Tools, "NoneLogLevel", {
  5863. get: function () {
  5864. return Tools._NoneLogLevel;
  5865. },
  5866. enumerable: true,
  5867. configurable: true
  5868. });
  5869. Object.defineProperty(Tools, "MessageLogLevel", {
  5870. get: function () {
  5871. return Tools._MessageLogLevel;
  5872. },
  5873. enumerable: true,
  5874. configurable: true
  5875. });
  5876. Object.defineProperty(Tools, "WarningLogLevel", {
  5877. get: function () {
  5878. return Tools._WarningLogLevel;
  5879. },
  5880. enumerable: true,
  5881. configurable: true
  5882. });
  5883. Object.defineProperty(Tools, "ErrorLogLevel", {
  5884. get: function () {
  5885. return Tools._ErrorLogLevel;
  5886. },
  5887. enumerable: true,
  5888. configurable: true
  5889. });
  5890. Object.defineProperty(Tools, "AllLogLevel", {
  5891. get: function () {
  5892. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5893. },
  5894. enumerable: true,
  5895. configurable: true
  5896. });
  5897. Tools._AddLogEntry = function (entry) {
  5898. Tools._LogCache = entry + Tools._LogCache;
  5899. if (Tools.OnNewCacheEntry) {
  5900. Tools.OnNewCacheEntry(entry);
  5901. }
  5902. };
  5903. Tools._FormatMessage = function (message) {
  5904. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5905. var date = new Date();
  5906. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5907. };
  5908. Tools._LogDisabled = function (message) {
  5909. // nothing to do
  5910. };
  5911. Tools._LogEnabled = function (message) {
  5912. var formattedMessage = Tools._FormatMessage(message);
  5913. console.log("BJS - " + formattedMessage);
  5914. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5915. Tools._AddLogEntry(entry);
  5916. };
  5917. Tools._WarnDisabled = function (message) {
  5918. // nothing to do
  5919. };
  5920. Tools._WarnEnabled = function (message) {
  5921. var formattedMessage = Tools._FormatMessage(message);
  5922. console.warn("BJS - " + formattedMessage);
  5923. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5924. Tools._AddLogEntry(entry);
  5925. };
  5926. Tools._ErrorDisabled = function (message) {
  5927. // nothing to do
  5928. };
  5929. Tools._ErrorEnabled = function (message) {
  5930. Tools.errorsCount++;
  5931. var formattedMessage = Tools._FormatMessage(message);
  5932. console.error("BJS - " + formattedMessage);
  5933. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5934. Tools._AddLogEntry(entry);
  5935. };
  5936. Object.defineProperty(Tools, "LogCache", {
  5937. get: function () {
  5938. return Tools._LogCache;
  5939. },
  5940. enumerable: true,
  5941. configurable: true
  5942. });
  5943. Tools.ClearLogCache = function () {
  5944. Tools._LogCache = "";
  5945. Tools.errorsCount = 0;
  5946. };
  5947. Object.defineProperty(Tools, "LogLevels", {
  5948. set: function (level) {
  5949. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5950. Tools.Log = Tools._LogEnabled;
  5951. }
  5952. else {
  5953. Tools.Log = Tools._LogDisabled;
  5954. }
  5955. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5956. Tools.Warn = Tools._WarnEnabled;
  5957. }
  5958. else {
  5959. Tools.Warn = Tools._WarnDisabled;
  5960. }
  5961. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5962. Tools.Error = Tools._ErrorEnabled;
  5963. }
  5964. else {
  5965. Tools.Error = Tools._ErrorDisabled;
  5966. }
  5967. },
  5968. enumerable: true,
  5969. configurable: true
  5970. });
  5971. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5972. get: function () {
  5973. return Tools._PerformanceNoneLogLevel;
  5974. },
  5975. enumerable: true,
  5976. configurable: true
  5977. });
  5978. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5979. get: function () {
  5980. return Tools._PerformanceUserMarkLogLevel;
  5981. },
  5982. enumerable: true,
  5983. configurable: true
  5984. });
  5985. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5986. get: function () {
  5987. return Tools._PerformanceConsoleLogLevel;
  5988. },
  5989. enumerable: true,
  5990. configurable: true
  5991. });
  5992. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5993. set: function (level) {
  5994. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5995. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5996. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5997. return;
  5998. }
  5999. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6000. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6001. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6002. return;
  6003. }
  6004. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6005. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6006. },
  6007. enumerable: true,
  6008. configurable: true
  6009. });
  6010. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6011. };
  6012. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6013. };
  6014. Tools._StartUserMark = function (counterName, condition) {
  6015. if (condition === void 0) { condition = true; }
  6016. if (!condition || !Tools._performance.mark) {
  6017. return;
  6018. }
  6019. Tools._performance.mark(counterName + "-Begin");
  6020. };
  6021. Tools._EndUserMark = function (counterName, condition) {
  6022. if (condition === void 0) { condition = true; }
  6023. if (!condition || !Tools._performance.mark) {
  6024. return;
  6025. }
  6026. Tools._performance.mark(counterName + "-End");
  6027. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6028. };
  6029. Tools._StartPerformanceConsole = function (counterName, condition) {
  6030. if (condition === void 0) { condition = true; }
  6031. if (!condition) {
  6032. return;
  6033. }
  6034. Tools._StartUserMark(counterName, condition);
  6035. if (console.time) {
  6036. console.time(counterName);
  6037. }
  6038. };
  6039. Tools._EndPerformanceConsole = function (counterName, condition) {
  6040. if (condition === void 0) { condition = true; }
  6041. if (!condition) {
  6042. return;
  6043. }
  6044. Tools._EndUserMark(counterName, condition);
  6045. if (console.time) {
  6046. console.timeEnd(counterName);
  6047. }
  6048. };
  6049. Object.defineProperty(Tools, "Now", {
  6050. get: function () {
  6051. if (window.performance && window.performance.now) {
  6052. return window.performance.now();
  6053. }
  6054. return new Date().getTime();
  6055. },
  6056. enumerable: true,
  6057. configurable: true
  6058. });
  6059. /**
  6060. * This method will return the name of the class used to create the instance of the given object.
  6061. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6062. * @param object the object to get the class name from
  6063. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6064. */
  6065. Tools.getClassName = function (object, isType) {
  6066. if (isType === void 0) { isType = false; }
  6067. var name = null;
  6068. if (!isType && object.getClassName) {
  6069. name = object.getClassName();
  6070. }
  6071. else {
  6072. if (object instanceof Object) {
  6073. var classObj = isType ? object : Object.getPrototypeOf(object);
  6074. name = classObj.constructor["__bjsclassName__"];
  6075. }
  6076. if (!name) {
  6077. name = typeof object;
  6078. }
  6079. }
  6080. return name;
  6081. };
  6082. Tools.first = function (array, predicate) {
  6083. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6084. var el = array_1[_i];
  6085. if (predicate(el)) {
  6086. return el;
  6087. }
  6088. }
  6089. };
  6090. /**
  6091. * This method will return the name of the full name of the class, including its owning module (if any).
  6092. * 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).
  6093. * @param object the object to get the class name from
  6094. * @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.
  6095. */
  6096. Tools.getFullClassName = function (object, isType) {
  6097. if (isType === void 0) { isType = false; }
  6098. var className = null;
  6099. var moduleName = null;
  6100. if (!isType && object.getClassName) {
  6101. className = object.getClassName();
  6102. }
  6103. else {
  6104. if (object instanceof Object) {
  6105. var classObj = isType ? object : Object.getPrototypeOf(object);
  6106. className = classObj.constructor["__bjsclassName__"];
  6107. moduleName = classObj.constructor["__bjsmoduleName__"];
  6108. }
  6109. if (!className) {
  6110. className = typeof object;
  6111. }
  6112. }
  6113. if (!className) {
  6114. return null;
  6115. }
  6116. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6117. };
  6118. /**
  6119. * 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.
  6120. * @param array
  6121. */
  6122. Tools.arrayOrStringFeeder = function (array) {
  6123. return function (index) {
  6124. if (index >= array.length) {
  6125. return null;
  6126. }
  6127. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6128. if (val && val.getHashCode) {
  6129. val = val.getHashCode();
  6130. }
  6131. if (typeof val === "string") {
  6132. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6133. }
  6134. return val;
  6135. };
  6136. };
  6137. /**
  6138. * Compute the hashCode of a stream of number
  6139. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6140. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6141. * @return the hash code computed
  6142. */
  6143. Tools.hashCodeFromStream = function (feeder) {
  6144. // Based from here: http://stackoverflow.com/a/7616484/802124
  6145. var hash = 0;
  6146. var index = 0;
  6147. var chr = feeder(index++);
  6148. while (chr != null) {
  6149. hash = ((hash << 5) - hash) + chr;
  6150. hash |= 0; // Convert to 32bit integer
  6151. chr = feeder(index++);
  6152. }
  6153. return hash;
  6154. };
  6155. return Tools;
  6156. }());
  6157. Tools.BaseUrl = "";
  6158. Tools.CorsBehavior = "anonymous";
  6159. Tools.UseFallbackTexture = true;
  6160. // Used in case of a texture loading problem
  6161. 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";
  6162. // Logs
  6163. Tools._NoneLogLevel = 0;
  6164. Tools._MessageLogLevel = 1;
  6165. Tools._WarningLogLevel = 2;
  6166. Tools._ErrorLogLevel = 4;
  6167. Tools._LogCache = "";
  6168. Tools.errorsCount = 0;
  6169. Tools.Log = Tools._LogEnabled;
  6170. Tools.Warn = Tools._WarnEnabled;
  6171. Tools.Error = Tools._ErrorEnabled;
  6172. // Performances
  6173. Tools._PerformanceNoneLogLevel = 0;
  6174. Tools._PerformanceUserMarkLogLevel = 1;
  6175. Tools._PerformanceConsoleLogLevel = 2;
  6176. Tools._performance = window.performance;
  6177. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6178. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6179. BABYLON.Tools = Tools;
  6180. /**
  6181. * This class is used to track a performance counter which is number based.
  6182. * The user has access to many properties which give statistics of different nature
  6183. *
  6184. * The implementer can track two kinds of Performance Counter: time and count
  6185. * 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.
  6186. * 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.
  6187. */
  6188. var PerfCounter = (function () {
  6189. function PerfCounter() {
  6190. this._startMonitoringTime = 0;
  6191. this._min = 0;
  6192. this._max = 0;
  6193. this._average = 0;
  6194. this._lastSecAverage = 0;
  6195. this._current = 0;
  6196. this._totalValueCount = 0;
  6197. this._totalAccumulated = 0;
  6198. this._lastSecAccumulated = 0;
  6199. this._lastSecTime = 0;
  6200. this._lastSecValueCount = 0;
  6201. }
  6202. Object.defineProperty(PerfCounter.prototype, "min", {
  6203. /**
  6204. * Returns the smallest value ever
  6205. */
  6206. get: function () {
  6207. return this._min;
  6208. },
  6209. enumerable: true,
  6210. configurable: true
  6211. });
  6212. Object.defineProperty(PerfCounter.prototype, "max", {
  6213. /**
  6214. * Returns the biggest value ever
  6215. */
  6216. get: function () {
  6217. return this._max;
  6218. },
  6219. enumerable: true,
  6220. configurable: true
  6221. });
  6222. Object.defineProperty(PerfCounter.prototype, "average", {
  6223. /**
  6224. * Returns the average value since the performance counter is running
  6225. */
  6226. get: function () {
  6227. return this._average;
  6228. },
  6229. enumerable: true,
  6230. configurable: true
  6231. });
  6232. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6233. /**
  6234. * Returns the average value of the last second the counter was monitored
  6235. */
  6236. get: function () {
  6237. return this._lastSecAverage;
  6238. },
  6239. enumerable: true,
  6240. configurable: true
  6241. });
  6242. Object.defineProperty(PerfCounter.prototype, "current", {
  6243. /**
  6244. * Returns the current value
  6245. */
  6246. get: function () {
  6247. return this._current;
  6248. },
  6249. enumerable: true,
  6250. configurable: true
  6251. });
  6252. Object.defineProperty(PerfCounter.prototype, "total", {
  6253. get: function () {
  6254. return this._totalAccumulated;
  6255. },
  6256. enumerable: true,
  6257. configurable: true
  6258. });
  6259. /**
  6260. * Call this method to start monitoring a new frame.
  6261. * 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.
  6262. */
  6263. PerfCounter.prototype.fetchNewFrame = function () {
  6264. this._totalValueCount++;
  6265. this._current = 0;
  6266. this._lastSecValueCount++;
  6267. };
  6268. /**
  6269. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6270. * @param newCount the count value to add to the monitored count
  6271. * @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.
  6272. */
  6273. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6274. if (!PerfCounter.Enabled) {
  6275. return;
  6276. }
  6277. this._current += newCount;
  6278. if (fetchResult) {
  6279. this._fetchResult();
  6280. }
  6281. };
  6282. /**
  6283. * Start monitoring this performance counter
  6284. */
  6285. PerfCounter.prototype.beginMonitoring = function () {
  6286. if (!PerfCounter.Enabled) {
  6287. return;
  6288. }
  6289. this._startMonitoringTime = Tools.Now;
  6290. };
  6291. /**
  6292. * Compute the time lapsed since the previous beginMonitoring() call.
  6293. * @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
  6294. */
  6295. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6296. if (newFrame === void 0) { newFrame = true; }
  6297. if (!PerfCounter.Enabled) {
  6298. return;
  6299. }
  6300. if (newFrame) {
  6301. this.fetchNewFrame();
  6302. }
  6303. var currentTime = Tools.Now;
  6304. this._current = currentTime - this._startMonitoringTime;
  6305. if (newFrame) {
  6306. this._fetchResult();
  6307. }
  6308. };
  6309. PerfCounter.prototype._fetchResult = function () {
  6310. this._totalAccumulated += this._current;
  6311. this._lastSecAccumulated += this._current;
  6312. // Min/Max update
  6313. this._min = Math.min(this._min, this._current);
  6314. this._max = Math.max(this._max, this._current);
  6315. this._average = this._totalAccumulated / this._totalValueCount;
  6316. // Reset last sec?
  6317. var now = Tools.Now;
  6318. if ((now - this._lastSecTime) > 1000) {
  6319. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6320. this._lastSecTime = now;
  6321. this._lastSecAccumulated = 0;
  6322. this._lastSecValueCount = 0;
  6323. }
  6324. };
  6325. return PerfCounter;
  6326. }());
  6327. PerfCounter.Enabled = true;
  6328. BABYLON.PerfCounter = PerfCounter;
  6329. /**
  6330. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6331. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6332. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6333. * @param name The name of the class, case should be preserved
  6334. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6335. */
  6336. function className(name, module) {
  6337. return function (target) {
  6338. target["__bjsclassName__"] = name;
  6339. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6340. };
  6341. }
  6342. BABYLON.className = className;
  6343. /**
  6344. * An implementation of a loop for asynchronous functions.
  6345. */
  6346. var AsyncLoop = (function () {
  6347. /**
  6348. * Constroctor.
  6349. * @param iterations the number of iterations.
  6350. * @param _fn the function to run each iteration
  6351. * @param _successCallback the callback that will be called upon succesful execution
  6352. * @param offset starting offset.
  6353. */
  6354. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6355. if (offset === void 0) { offset = 0; }
  6356. this.iterations = iterations;
  6357. this._fn = _fn;
  6358. this._successCallback = _successCallback;
  6359. this.index = offset - 1;
  6360. this._done = false;
  6361. }
  6362. /**
  6363. * Execute the next iteration. Must be called after the last iteration was finished.
  6364. */
  6365. AsyncLoop.prototype.executeNext = function () {
  6366. if (!this._done) {
  6367. if (this.index + 1 < this.iterations) {
  6368. ++this.index;
  6369. this._fn(this);
  6370. }
  6371. else {
  6372. this.breakLoop();
  6373. }
  6374. }
  6375. };
  6376. /**
  6377. * Break the loop and run the success callback.
  6378. */
  6379. AsyncLoop.prototype.breakLoop = function () {
  6380. this._done = true;
  6381. this._successCallback();
  6382. };
  6383. /**
  6384. * Helper function
  6385. */
  6386. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6387. if (offset === void 0) { offset = 0; }
  6388. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6389. loop.executeNext();
  6390. return loop;
  6391. };
  6392. /**
  6393. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6394. * @param iterations total number of iterations
  6395. * @param syncedIterations number of synchronous iterations in each async iteration.
  6396. * @param fn the function to call each iteration.
  6397. * @param callback a success call back that will be called when iterating stops.
  6398. * @param breakFunction a break condition (optional)
  6399. * @param timeout timeout settings for the setTimeout function. default - 0.
  6400. * @constructor
  6401. */
  6402. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6403. if (timeout === void 0) { timeout = 0; }
  6404. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6405. if (breakFunction && breakFunction())
  6406. loop.breakLoop();
  6407. else {
  6408. setTimeout(function () {
  6409. for (var i = 0; i < syncedIterations; ++i) {
  6410. var iteration = (loop.index * syncedIterations) + i;
  6411. if (iteration >= iterations)
  6412. break;
  6413. fn(iteration);
  6414. if (breakFunction && breakFunction()) {
  6415. loop.breakLoop();
  6416. break;
  6417. }
  6418. }
  6419. loop.executeNext();
  6420. }, timeout);
  6421. }
  6422. }, callback);
  6423. };
  6424. return AsyncLoop;
  6425. }());
  6426. BABYLON.AsyncLoop = AsyncLoop;
  6427. })(BABYLON || (BABYLON = {}));
  6428. //# sourceMappingURL=babylon.tools.js.map
  6429. var BABYLON;
  6430. (function (BABYLON) {
  6431. var Internals;
  6432. (function (Internals) {
  6433. var _AlphaState = (function () {
  6434. /**
  6435. * Initializes the state.
  6436. */
  6437. function _AlphaState() {
  6438. this._isAlphaBlendDirty = false;
  6439. this._isBlendFunctionParametersDirty = false;
  6440. this._alphaBlend = false;
  6441. this._blendFunctionParameters = new Array(4);
  6442. this.reset();
  6443. }
  6444. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6445. get: function () {
  6446. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6447. },
  6448. enumerable: true,
  6449. configurable: true
  6450. });
  6451. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6452. get: function () {
  6453. return this._alphaBlend;
  6454. },
  6455. set: function (value) {
  6456. if (this._alphaBlend === value) {
  6457. return;
  6458. }
  6459. this._alphaBlend = value;
  6460. this._isAlphaBlendDirty = true;
  6461. },
  6462. enumerable: true,
  6463. configurable: true
  6464. });
  6465. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6466. if (this._blendFunctionParameters[0] === value0 &&
  6467. this._blendFunctionParameters[1] === value1 &&
  6468. this._blendFunctionParameters[2] === value2 &&
  6469. this._blendFunctionParameters[3] === value3) {
  6470. return;
  6471. }
  6472. this._blendFunctionParameters[0] = value0;
  6473. this._blendFunctionParameters[1] = value1;
  6474. this._blendFunctionParameters[2] = value2;
  6475. this._blendFunctionParameters[3] = value3;
  6476. this._isBlendFunctionParametersDirty = true;
  6477. };
  6478. _AlphaState.prototype.reset = function () {
  6479. this._alphaBlend = false;
  6480. this._blendFunctionParameters[0] = null;
  6481. this._blendFunctionParameters[1] = null;
  6482. this._blendFunctionParameters[2] = null;
  6483. this._blendFunctionParameters[3] = null;
  6484. this._isAlphaBlendDirty = true;
  6485. this._isBlendFunctionParametersDirty = false;
  6486. };
  6487. _AlphaState.prototype.apply = function (gl) {
  6488. if (!this.isDirty) {
  6489. return;
  6490. }
  6491. // Alpha blend
  6492. if (this._isAlphaBlendDirty) {
  6493. if (this._alphaBlend) {
  6494. gl.enable(gl.BLEND);
  6495. }
  6496. else {
  6497. gl.disable(gl.BLEND);
  6498. }
  6499. this._isAlphaBlendDirty = false;
  6500. }
  6501. // Alpha function
  6502. if (this._isBlendFunctionParametersDirty) {
  6503. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6504. this._isBlendFunctionParametersDirty = false;
  6505. }
  6506. };
  6507. return _AlphaState;
  6508. }());
  6509. Internals._AlphaState = _AlphaState;
  6510. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6511. })(BABYLON || (BABYLON = {}));
  6512. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6513. var BABYLON;
  6514. (function (BABYLON) {
  6515. var Internals;
  6516. (function (Internals) {
  6517. var _DepthCullingState = (function () {
  6518. /**
  6519. * Initializes the state.
  6520. */
  6521. function _DepthCullingState() {
  6522. this._isDepthTestDirty = false;
  6523. this._isDepthMaskDirty = false;
  6524. this._isDepthFuncDirty = false;
  6525. this._isCullFaceDirty = false;
  6526. this._isCullDirty = false;
  6527. this._isZOffsetDirty = false;
  6528. this.reset();
  6529. }
  6530. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6531. get: function () {
  6532. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6533. },
  6534. enumerable: true,
  6535. configurable: true
  6536. });
  6537. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6538. get: function () {
  6539. return this._zOffset;
  6540. },
  6541. set: function (value) {
  6542. if (this._zOffset === value) {
  6543. return;
  6544. }
  6545. this._zOffset = value;
  6546. this._isZOffsetDirty = true;
  6547. },
  6548. enumerable: true,
  6549. configurable: true
  6550. });
  6551. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6552. get: function () {
  6553. return this._cullFace;
  6554. },
  6555. set: function (value) {
  6556. if (this._cullFace === value) {
  6557. return;
  6558. }
  6559. this._cullFace = value;
  6560. this._isCullFaceDirty = true;
  6561. },
  6562. enumerable: true,
  6563. configurable: true
  6564. });
  6565. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6566. get: function () {
  6567. return this._cull;
  6568. },
  6569. set: function (value) {
  6570. if (this._cull === value) {
  6571. return;
  6572. }
  6573. this._cull = value;
  6574. this._isCullDirty = true;
  6575. },
  6576. enumerable: true,
  6577. configurable: true
  6578. });
  6579. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6580. get: function () {
  6581. return this._depthFunc;
  6582. },
  6583. set: function (value) {
  6584. if (this._depthFunc === value) {
  6585. return;
  6586. }
  6587. this._depthFunc = value;
  6588. this._isDepthFuncDirty = true;
  6589. },
  6590. enumerable: true,
  6591. configurable: true
  6592. });
  6593. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6594. get: function () {
  6595. return this._depthMask;
  6596. },
  6597. set: function (value) {
  6598. if (this._depthMask === value) {
  6599. return;
  6600. }
  6601. this._depthMask = value;
  6602. this._isDepthMaskDirty = true;
  6603. },
  6604. enumerable: true,
  6605. configurable: true
  6606. });
  6607. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6608. get: function () {
  6609. return this._depthTest;
  6610. },
  6611. set: function (value) {
  6612. if (this._depthTest === value) {
  6613. return;
  6614. }
  6615. this._depthTest = value;
  6616. this._isDepthTestDirty = true;
  6617. },
  6618. enumerable: true,
  6619. configurable: true
  6620. });
  6621. _DepthCullingState.prototype.reset = function () {
  6622. this._depthMask = true;
  6623. this._depthTest = true;
  6624. this._depthFunc = null;
  6625. this._cullFace = null;
  6626. this._cull = null;
  6627. this._zOffset = 0;
  6628. this._isDepthTestDirty = true;
  6629. this._isDepthMaskDirty = true;
  6630. this._isDepthFuncDirty = false;
  6631. this._isCullFaceDirty = false;
  6632. this._isCullDirty = false;
  6633. this._isZOffsetDirty = false;
  6634. };
  6635. _DepthCullingState.prototype.apply = function (gl) {
  6636. if (!this.isDirty) {
  6637. return;
  6638. }
  6639. // Cull
  6640. if (this._isCullDirty) {
  6641. if (this.cull) {
  6642. gl.enable(gl.CULL_FACE);
  6643. }
  6644. else {
  6645. gl.disable(gl.CULL_FACE);
  6646. }
  6647. this._isCullDirty = false;
  6648. }
  6649. // Cull face
  6650. if (this._isCullFaceDirty) {
  6651. gl.cullFace(this.cullFace);
  6652. this._isCullFaceDirty = false;
  6653. }
  6654. // Depth mask
  6655. if (this._isDepthMaskDirty) {
  6656. gl.depthMask(this.depthMask);
  6657. this._isDepthMaskDirty = false;
  6658. }
  6659. // Depth test
  6660. if (this._isDepthTestDirty) {
  6661. if (this.depthTest) {
  6662. gl.enable(gl.DEPTH_TEST);
  6663. }
  6664. else {
  6665. gl.disable(gl.DEPTH_TEST);
  6666. }
  6667. this._isDepthTestDirty = false;
  6668. }
  6669. // Depth func
  6670. if (this._isDepthFuncDirty) {
  6671. gl.depthFunc(this.depthFunc);
  6672. this._isDepthFuncDirty = false;
  6673. }
  6674. // zOffset
  6675. if (this._isZOffsetDirty) {
  6676. if (this.zOffset) {
  6677. gl.enable(gl.POLYGON_OFFSET_FILL);
  6678. gl.polygonOffset(this.zOffset, 0);
  6679. }
  6680. else {
  6681. gl.disable(gl.POLYGON_OFFSET_FILL);
  6682. }
  6683. this._isZOffsetDirty = false;
  6684. }
  6685. };
  6686. return _DepthCullingState;
  6687. }());
  6688. Internals._DepthCullingState = _DepthCullingState;
  6689. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6690. })(BABYLON || (BABYLON = {}));
  6691. //# sourceMappingURL=babylon.depthCullingState.js.map
  6692. var BABYLON;
  6693. (function (BABYLON) {
  6694. var Internals;
  6695. (function (Internals) {
  6696. var _StencilState = (function () {
  6697. function _StencilState() {
  6698. this._isStencilTestDirty = false;
  6699. this._isStencilMaskDirty = false;
  6700. this._isStencilFuncDirty = false;
  6701. this._isStencilOpDirty = false;
  6702. this.reset();
  6703. }
  6704. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6705. get: function () {
  6706. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6707. },
  6708. enumerable: true,
  6709. configurable: true
  6710. });
  6711. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6712. get: function () {
  6713. return this._stencilFunc;
  6714. },
  6715. set: function (value) {
  6716. if (this._stencilFunc === value) {
  6717. return;
  6718. }
  6719. this._stencilFunc = value;
  6720. this._isStencilFuncDirty = true;
  6721. },
  6722. enumerable: true,
  6723. configurable: true
  6724. });
  6725. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6726. get: function () {
  6727. return this._stencilFuncRef;
  6728. },
  6729. set: function (value) {
  6730. if (this._stencilFuncRef === value) {
  6731. return;
  6732. }
  6733. this._stencilFuncRef = value;
  6734. this._isStencilFuncDirty = true;
  6735. },
  6736. enumerable: true,
  6737. configurable: true
  6738. });
  6739. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6740. get: function () {
  6741. return this._stencilFuncMask;
  6742. },
  6743. set: function (value) {
  6744. if (this._stencilFuncMask === value) {
  6745. return;
  6746. }
  6747. this._stencilFuncMask = value;
  6748. this._isStencilFuncDirty = true;
  6749. },
  6750. enumerable: true,
  6751. configurable: true
  6752. });
  6753. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6754. get: function () {
  6755. return this._stencilOpStencilFail;
  6756. },
  6757. set: function (value) {
  6758. if (this._stencilOpStencilFail === value) {
  6759. return;
  6760. }
  6761. this._stencilOpStencilFail = value;
  6762. this._isStencilOpDirty = true;
  6763. },
  6764. enumerable: true,
  6765. configurable: true
  6766. });
  6767. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6768. get: function () {
  6769. return this._stencilOpDepthFail;
  6770. },
  6771. set: function (value) {
  6772. if (this._stencilOpDepthFail === value) {
  6773. return;
  6774. }
  6775. this._stencilOpDepthFail = value;
  6776. this._isStencilOpDirty = true;
  6777. },
  6778. enumerable: true,
  6779. configurable: true
  6780. });
  6781. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6782. get: function () {
  6783. return this._stencilOpStencilDepthPass;
  6784. },
  6785. set: function (value) {
  6786. if (this._stencilOpStencilDepthPass === value) {
  6787. return;
  6788. }
  6789. this._stencilOpStencilDepthPass = value;
  6790. this._isStencilOpDirty = true;
  6791. },
  6792. enumerable: true,
  6793. configurable: true
  6794. });
  6795. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6796. get: function () {
  6797. return this._stencilMask;
  6798. },
  6799. set: function (value) {
  6800. if (this._stencilMask === value) {
  6801. return;
  6802. }
  6803. this._stencilMask = value;
  6804. this._isStencilMaskDirty = true;
  6805. },
  6806. enumerable: true,
  6807. configurable: true
  6808. });
  6809. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6810. get: function () {
  6811. return this._stencilTest;
  6812. },
  6813. set: function (value) {
  6814. if (this._stencilTest === value) {
  6815. return;
  6816. }
  6817. this._stencilTest = value;
  6818. this._isStencilTestDirty = true;
  6819. },
  6820. enumerable: true,
  6821. configurable: true
  6822. });
  6823. _StencilState.prototype.reset = function () {
  6824. this._stencilTest = false;
  6825. this._stencilMask = 0xFF;
  6826. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6827. this._stencilFuncRef = 1;
  6828. this._stencilFuncMask = 0xFF;
  6829. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6830. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6831. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6832. this._isStencilTestDirty = true;
  6833. this._isStencilMaskDirty = true;
  6834. this._isStencilFuncDirty = true;
  6835. this._isStencilOpDirty = true;
  6836. };
  6837. _StencilState.prototype.apply = function (gl) {
  6838. if (!this.isDirty) {
  6839. return;
  6840. }
  6841. // Stencil test
  6842. if (this._isStencilTestDirty) {
  6843. if (this.stencilTest) {
  6844. gl.enable(gl.STENCIL_TEST);
  6845. }
  6846. else {
  6847. gl.disable(gl.STENCIL_TEST);
  6848. }
  6849. this._isStencilTestDirty = false;
  6850. }
  6851. // Stencil mask
  6852. if (this._isStencilMaskDirty) {
  6853. gl.stencilMask(this.stencilMask);
  6854. this._isStencilMaskDirty = false;
  6855. }
  6856. // Stencil func
  6857. if (this._isStencilFuncDirty) {
  6858. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6859. this._isStencilFuncDirty = false;
  6860. }
  6861. // Stencil op
  6862. if (this._isStencilOpDirty) {
  6863. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6864. this._isStencilOpDirty = false;
  6865. }
  6866. };
  6867. return _StencilState;
  6868. }());
  6869. Internals._StencilState = _StencilState;
  6870. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6871. })(BABYLON || (BABYLON = {}));
  6872. //# sourceMappingURL=babylon.stencilState.js.map
  6873. var BABYLON;
  6874. (function (BABYLON) {
  6875. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6876. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6877. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6878. gl.compileShader(shader);
  6879. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6880. throw new Error(gl.getShaderInfoLog(shader));
  6881. }
  6882. return shader;
  6883. };
  6884. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6885. var magFilter = gl.NEAREST;
  6886. var minFilter = gl.NEAREST;
  6887. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6888. magFilter = gl.LINEAR;
  6889. if (generateMipMaps) {
  6890. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6891. }
  6892. else {
  6893. minFilter = gl.LINEAR;
  6894. }
  6895. }
  6896. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6897. magFilter = gl.LINEAR;
  6898. if (generateMipMaps) {
  6899. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6900. }
  6901. else {
  6902. minFilter = gl.LINEAR;
  6903. }
  6904. }
  6905. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6906. magFilter = gl.NEAREST;
  6907. if (generateMipMaps) {
  6908. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6909. }
  6910. else {
  6911. minFilter = gl.NEAREST;
  6912. }
  6913. }
  6914. return {
  6915. min: minFilter,
  6916. mag: magFilter
  6917. };
  6918. };
  6919. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6920. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6921. var engine = scene.getEngine();
  6922. if (!engine) {
  6923. return;
  6924. }
  6925. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6926. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6927. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6928. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6929. texture._baseWidth = width;
  6930. texture._baseHeight = height;
  6931. texture._width = potWidth;
  6932. texture._height = potHeight;
  6933. texture.isReady = true;
  6934. processFunction(potWidth, potHeight);
  6935. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6937. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6938. if (!noMipmap && !isCompressed) {
  6939. gl.generateMipmap(gl.TEXTURE_2D);
  6940. }
  6941. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6942. engine.resetTextureCache();
  6943. scene._removePendingData(texture);
  6944. texture.onLoadedCallbacks.forEach(function (callback) {
  6945. callback();
  6946. });
  6947. texture.onLoadedCallbacks = [];
  6948. };
  6949. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6950. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6951. var img;
  6952. var onload = function () {
  6953. loadedImages[index] = img;
  6954. loadedImages._internalCount++;
  6955. scene._removePendingData(img);
  6956. if (loadedImages._internalCount === 6) {
  6957. onfinish(loadedImages);
  6958. }
  6959. };
  6960. var onerror = function () {
  6961. scene._removePendingData(img);
  6962. if (onErrorCallBack) {
  6963. onErrorCallBack();
  6964. }
  6965. };
  6966. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6967. scene._addPendingData(img);
  6968. };
  6969. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6970. if (onError === void 0) { onError = null; }
  6971. var loadedImages = [];
  6972. loadedImages._internalCount = 0;
  6973. for (var index = 0; index < 6; index++) {
  6974. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6975. }
  6976. };
  6977. var InstancingAttributeInfo = (function () {
  6978. function InstancingAttributeInfo() {
  6979. }
  6980. return InstancingAttributeInfo;
  6981. }());
  6982. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6983. var EngineCapabilities = (function () {
  6984. function EngineCapabilities() {
  6985. }
  6986. return EngineCapabilities;
  6987. }());
  6988. BABYLON.EngineCapabilities = EngineCapabilities;
  6989. /**
  6990. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6991. */
  6992. var Engine = (function () {
  6993. /**
  6994. * @constructor
  6995. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6996. * @param {boolean} [antialias] - enable antialias
  6997. * @param options - further options to be sent to the getContext function
  6998. */
  6999. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7000. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7001. var _this = this;
  7002. // Public members
  7003. this.isFullscreen = false;
  7004. this.isPointerLock = false;
  7005. this.cullBackFaces = true;
  7006. this.renderEvenInBackground = true;
  7007. this.preventCacheWipeBetweenFrames = false;
  7008. // To enable/disable IDB support and avoid XHR on .manifest
  7009. this.enableOfflineSupport = BABYLON.Database;
  7010. this.scenes = new Array();
  7011. this._windowIsBackground = false;
  7012. this._webGLVersion = 1.0;
  7013. this._badOS = false;
  7014. this._drawCalls = new BABYLON.PerfCounter();
  7015. this._renderingQueueLaunched = false;
  7016. this._activeRenderLoops = [];
  7017. // FPS
  7018. this.fpsRange = 60;
  7019. this.previousFramesDuration = [];
  7020. this.fps = 60;
  7021. this.deltaTime = 0;
  7022. // States
  7023. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7024. this._stencilState = new BABYLON.Internals._StencilState();
  7025. this._alphaState = new BABYLON.Internals._AlphaState();
  7026. this._alphaMode = Engine.ALPHA_DISABLE;
  7027. // Cache
  7028. this._loadedTexturesCache = new Array();
  7029. this._maxTextureChannels = 16;
  7030. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7031. this._compiledEffects = {};
  7032. this._vertexAttribArraysEnabled = [];
  7033. this._uintIndicesCurrentlySet = false;
  7034. this._currentBoundBuffer = new Array();
  7035. this._currentBufferPointers = [];
  7036. this._currentInstanceLocations = new Array();
  7037. this._currentInstanceBuffers = new Array();
  7038. this._vaoRecordInProgress = false;
  7039. this._mustWipeVertexAttributes = false;
  7040. // Hardware supported Compressed Textures
  7041. this._texturesSupported = new Array();
  7042. this._onVRFullScreenTriggered = function () {
  7043. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7044. //get the old size before we change
  7045. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7046. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7047. //get the width and height, change the render size
  7048. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7049. var width, height;
  7050. _this.setHardwareScalingLevel(1);
  7051. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7052. }
  7053. else {
  7054. //When the specs are implemented, need to uncomment this.
  7055. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7056. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7057. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7058. _this._vrDisplayEnabled = undefined;
  7059. }
  7060. };
  7061. this._renderingCanvas = canvas;
  7062. Engine.Instances.push(this);
  7063. options = options || {};
  7064. if (antialias != null) {
  7065. options.antialias = antialias;
  7066. }
  7067. if (options.preserveDrawingBuffer === undefined) {
  7068. options.preserveDrawingBuffer = false;
  7069. }
  7070. if (options.audioEngine === undefined) {
  7071. options.audioEngine = true;
  7072. }
  7073. if (options.stencil === undefined) {
  7074. options.stencil = true;
  7075. }
  7076. // GL
  7077. if (!options.disableWebGL2Support) {
  7078. try {
  7079. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7080. if (this._gl) {
  7081. this._webGLVersion = 2.0;
  7082. }
  7083. }
  7084. catch (e) {
  7085. // Do nothing
  7086. }
  7087. }
  7088. if (!this._gl) {
  7089. if (!canvas) {
  7090. throw new Error("The provided canvas is null or undefined.");
  7091. }
  7092. try {
  7093. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7094. }
  7095. catch (e) {
  7096. throw new Error("WebGL not supported");
  7097. }
  7098. }
  7099. if (!this._gl) {
  7100. throw new Error("WebGL not supported");
  7101. }
  7102. this._onBlur = function () {
  7103. _this._windowIsBackground = true;
  7104. };
  7105. this._onFocus = function () {
  7106. _this._windowIsBackground = false;
  7107. };
  7108. window.addEventListener("blur", this._onBlur);
  7109. window.addEventListener("focus", this._onFocus);
  7110. // Viewport
  7111. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7112. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7113. this.resize();
  7114. // Caps
  7115. this._isStencilEnable = options.stencil;
  7116. this._caps = new EngineCapabilities();
  7117. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7118. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7119. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7120. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7121. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7122. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7123. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7124. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7125. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7126. // Infos
  7127. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7128. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7129. if (rendererInfo != null) {
  7130. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7131. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7132. }
  7133. if (!this._glVendor) {
  7134. this._glVendor = "Unknown vendor";
  7135. }
  7136. if (!this._glRenderer) {
  7137. this._glRenderer = "Unknown renderer";
  7138. }
  7139. // Extensions
  7140. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7141. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7142. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7143. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7144. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7145. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7146. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7147. 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');
  7148. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7149. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7150. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7151. this._caps.highPrecisionShaderSupported = true;
  7152. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7153. // Checks if some of the format renders first to allow the use of webgl inspector.
  7154. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7155. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7156. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7157. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7158. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7159. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7160. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7161. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7162. // Vertex array object
  7163. if (this._webGLVersion > 1) {
  7164. this._caps.vertexArrayObject = true;
  7165. }
  7166. else {
  7167. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7168. if (vertexArrayObjectExtension != null) {
  7169. this._caps.vertexArrayObject = true;
  7170. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7171. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7172. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7173. }
  7174. else {
  7175. this._caps.vertexArrayObject = false;
  7176. }
  7177. }
  7178. // Instances count
  7179. if (this._webGLVersion > 1) {
  7180. this._caps.instancedArrays = true;
  7181. }
  7182. else {
  7183. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7184. if (instanceExtension != null) {
  7185. this._caps.instancedArrays = true;
  7186. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7187. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7188. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7189. }
  7190. else {
  7191. this._caps.instancedArrays = false;
  7192. }
  7193. }
  7194. // Intelligently add supported compressed formats in order to check for.
  7195. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7196. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7197. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7198. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7199. if (this._caps.astc)
  7200. this.texturesSupported.push('-astc.ktx');
  7201. if (this._caps.s3tc)
  7202. this.texturesSupported.push('-dxt.ktx');
  7203. if (this._caps.pvrtc)
  7204. this.texturesSupported.push('-pvrtc.ktx');
  7205. if (this._caps.etc2)
  7206. this.texturesSupported.push('-etc2.ktx');
  7207. if (this._caps.etc1)
  7208. this.texturesSupported.push('-etc1.ktx');
  7209. if (this._gl.getShaderPrecisionFormat) {
  7210. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7211. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7212. }
  7213. // Depth buffer
  7214. this.setDepthBuffer(true);
  7215. this.setDepthFunctionToLessOrEqual();
  7216. this.setDepthWrite(true);
  7217. // Fullscreen
  7218. this._onFullscreenChange = function () {
  7219. if (document.fullscreen !== undefined) {
  7220. _this.isFullscreen = document.fullscreen;
  7221. }
  7222. else if (document.mozFullScreen !== undefined) {
  7223. _this.isFullscreen = document.mozFullScreen;
  7224. }
  7225. else if (document.webkitIsFullScreen !== undefined) {
  7226. _this.isFullscreen = document.webkitIsFullScreen;
  7227. }
  7228. else if (document.msIsFullScreen !== undefined) {
  7229. _this.isFullscreen = document.msIsFullScreen;
  7230. }
  7231. // Pointer lock
  7232. if (_this.isFullscreen && _this._pointerLockRequested) {
  7233. canvas.requestPointerLock = canvas.requestPointerLock ||
  7234. canvas.msRequestPointerLock ||
  7235. canvas.mozRequestPointerLock ||
  7236. canvas.webkitRequestPointerLock;
  7237. if (canvas.requestPointerLock) {
  7238. canvas.requestPointerLock();
  7239. }
  7240. }
  7241. };
  7242. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7243. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7244. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7245. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7246. // Pointer lock
  7247. this._onPointerLockChange = function () {
  7248. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7249. document.webkitPointerLockElement === canvas ||
  7250. document.msPointerLockElement === canvas ||
  7251. document.pointerLockElement === canvas);
  7252. };
  7253. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7254. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7255. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7256. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7257. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7258. Engine.audioEngine = new BABYLON.AudioEngine();
  7259. }
  7260. //Load WebVR Devices
  7261. if (options.autoEnableWebVR) {
  7262. this.initWebVR();
  7263. }
  7264. //Detect if we are running on a faulty buggy OS.
  7265. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7266. //ua sniffing is the tool of the devil.
  7267. this._badOS = regexp.test(navigator.userAgent);
  7268. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7269. }
  7270. Object.defineProperty(Engine, "LastCreatedEngine", {
  7271. get: function () {
  7272. if (Engine.Instances.length === 0) {
  7273. return null;
  7274. }
  7275. return Engine.Instances[Engine.Instances.length - 1];
  7276. },
  7277. enumerable: true,
  7278. configurable: true
  7279. });
  7280. Object.defineProperty(Engine, "LastCreatedScene", {
  7281. get: function () {
  7282. var lastCreatedEngine = Engine.LastCreatedEngine;
  7283. if (!lastCreatedEngine) {
  7284. return null;
  7285. }
  7286. if (lastCreatedEngine.scenes.length === 0) {
  7287. return null;
  7288. }
  7289. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7290. },
  7291. enumerable: true,
  7292. configurable: true
  7293. });
  7294. /**
  7295. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7296. */
  7297. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7298. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7299. var engine = Engine.Instances[engineIndex];
  7300. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7301. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7302. }
  7303. }
  7304. };
  7305. Object.defineProperty(Engine, "NEVER", {
  7306. get: function () {
  7307. return Engine._NEVER;
  7308. },
  7309. enumerable: true,
  7310. configurable: true
  7311. });
  7312. Object.defineProperty(Engine, "ALWAYS", {
  7313. get: function () {
  7314. return Engine._ALWAYS;
  7315. },
  7316. enumerable: true,
  7317. configurable: true
  7318. });
  7319. Object.defineProperty(Engine, "LESS", {
  7320. get: function () {
  7321. return Engine._LESS;
  7322. },
  7323. enumerable: true,
  7324. configurable: true
  7325. });
  7326. Object.defineProperty(Engine, "EQUAL", {
  7327. get: function () {
  7328. return Engine._EQUAL;
  7329. },
  7330. enumerable: true,
  7331. configurable: true
  7332. });
  7333. Object.defineProperty(Engine, "LEQUAL", {
  7334. get: function () {
  7335. return Engine._LEQUAL;
  7336. },
  7337. enumerable: true,
  7338. configurable: true
  7339. });
  7340. Object.defineProperty(Engine, "GREATER", {
  7341. get: function () {
  7342. return Engine._GREATER;
  7343. },
  7344. enumerable: true,
  7345. configurable: true
  7346. });
  7347. Object.defineProperty(Engine, "GEQUAL", {
  7348. get: function () {
  7349. return Engine._GEQUAL;
  7350. },
  7351. enumerable: true,
  7352. configurable: true
  7353. });
  7354. Object.defineProperty(Engine, "NOTEQUAL", {
  7355. get: function () {
  7356. return Engine._NOTEQUAL;
  7357. },
  7358. enumerable: true,
  7359. configurable: true
  7360. });
  7361. Object.defineProperty(Engine, "KEEP", {
  7362. get: function () {
  7363. return Engine._KEEP;
  7364. },
  7365. enumerable: true,
  7366. configurable: true
  7367. });
  7368. Object.defineProperty(Engine, "REPLACE", {
  7369. get: function () {
  7370. return Engine._REPLACE;
  7371. },
  7372. enumerable: true,
  7373. configurable: true
  7374. });
  7375. Object.defineProperty(Engine, "INCR", {
  7376. get: function () {
  7377. return Engine._INCR;
  7378. },
  7379. enumerable: true,
  7380. configurable: true
  7381. });
  7382. Object.defineProperty(Engine, "DECR", {
  7383. get: function () {
  7384. return Engine._DECR;
  7385. },
  7386. enumerable: true,
  7387. configurable: true
  7388. });
  7389. Object.defineProperty(Engine, "INVERT", {
  7390. get: function () {
  7391. return Engine._INVERT;
  7392. },
  7393. enumerable: true,
  7394. configurable: true
  7395. });
  7396. Object.defineProperty(Engine, "INCR_WRAP", {
  7397. get: function () {
  7398. return Engine._INCR_WRAP;
  7399. },
  7400. enumerable: true,
  7401. configurable: true
  7402. });
  7403. Object.defineProperty(Engine, "DECR_WRAP", {
  7404. get: function () {
  7405. return Engine._DECR_WRAP;
  7406. },
  7407. enumerable: true,
  7408. configurable: true
  7409. });
  7410. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7411. get: function () {
  7412. return Engine._ALPHA_DISABLE;
  7413. },
  7414. enumerable: true,
  7415. configurable: true
  7416. });
  7417. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7418. get: function () {
  7419. return Engine._ALPHA_ONEONE;
  7420. },
  7421. enumerable: true,
  7422. configurable: true
  7423. });
  7424. Object.defineProperty(Engine, "ALPHA_ADD", {
  7425. get: function () {
  7426. return Engine._ALPHA_ADD;
  7427. },
  7428. enumerable: true,
  7429. configurable: true
  7430. });
  7431. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7432. get: function () {
  7433. return Engine._ALPHA_COMBINE;
  7434. },
  7435. enumerable: true,
  7436. configurable: true
  7437. });
  7438. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7439. get: function () {
  7440. return Engine._ALPHA_SUBTRACT;
  7441. },
  7442. enumerable: true,
  7443. configurable: true
  7444. });
  7445. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7446. get: function () {
  7447. return Engine._ALPHA_MULTIPLY;
  7448. },
  7449. enumerable: true,
  7450. configurable: true
  7451. });
  7452. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7453. get: function () {
  7454. return Engine._ALPHA_MAXIMIZED;
  7455. },
  7456. enumerable: true,
  7457. configurable: true
  7458. });
  7459. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7460. get: function () {
  7461. return Engine._ALPHA_PREMULTIPLIED;
  7462. },
  7463. enumerable: true,
  7464. configurable: true
  7465. });
  7466. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7467. get: function () {
  7468. return Engine._DELAYLOADSTATE_NONE;
  7469. },
  7470. enumerable: true,
  7471. configurable: true
  7472. });
  7473. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7474. get: function () {
  7475. return Engine._DELAYLOADSTATE_LOADED;
  7476. },
  7477. enumerable: true,
  7478. configurable: true
  7479. });
  7480. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7481. get: function () {
  7482. return Engine._DELAYLOADSTATE_LOADING;
  7483. },
  7484. enumerable: true,
  7485. configurable: true
  7486. });
  7487. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7488. get: function () {
  7489. return Engine._DELAYLOADSTATE_NOTLOADED;
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. });
  7494. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7495. get: function () {
  7496. return Engine._TEXTUREFORMAT_ALPHA;
  7497. },
  7498. enumerable: true,
  7499. configurable: true
  7500. });
  7501. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7502. get: function () {
  7503. return Engine._TEXTUREFORMAT_LUMINANCE;
  7504. },
  7505. enumerable: true,
  7506. configurable: true
  7507. });
  7508. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7509. get: function () {
  7510. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7511. },
  7512. enumerable: true,
  7513. configurable: true
  7514. });
  7515. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7516. get: function () {
  7517. return Engine._TEXTUREFORMAT_RGB;
  7518. },
  7519. enumerable: true,
  7520. configurable: true
  7521. });
  7522. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7523. get: function () {
  7524. return Engine._TEXTUREFORMAT_RGBA;
  7525. },
  7526. enumerable: true,
  7527. configurable: true
  7528. });
  7529. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7530. get: function () {
  7531. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7532. },
  7533. enumerable: true,
  7534. configurable: true
  7535. });
  7536. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7537. get: function () {
  7538. return Engine._TEXTURETYPE_FLOAT;
  7539. },
  7540. enumerable: true,
  7541. configurable: true
  7542. });
  7543. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7544. get: function () {
  7545. return Engine._TEXTURETYPE_HALF_FLOAT;
  7546. },
  7547. enumerable: true,
  7548. configurable: true
  7549. });
  7550. Object.defineProperty(Engine, "Version", {
  7551. get: function () {
  7552. return "3.0-alpha";
  7553. },
  7554. enumerable: true,
  7555. configurable: true
  7556. });
  7557. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7558. get: function () {
  7559. return this._texturesSupported;
  7560. },
  7561. enumerable: true,
  7562. configurable: true
  7563. });
  7564. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7565. get: function () {
  7566. return this._textureFormatInUse;
  7567. },
  7568. enumerable: true,
  7569. configurable: true
  7570. });
  7571. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7572. get: function () {
  7573. return this._webGLVersion;
  7574. },
  7575. enumerable: true,
  7576. configurable: true
  7577. });
  7578. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7579. /**
  7580. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7581. */
  7582. get: function () {
  7583. return this._isStencilEnable;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Engine.prototype._prepareWorkingCanvas = function () {
  7589. if (this._workingCanvas) {
  7590. return;
  7591. }
  7592. this._workingCanvas = document.createElement("canvas");
  7593. this._workingContext = this._workingCanvas.getContext("2d");
  7594. };
  7595. Engine.prototype.resetTextureCache = function () {
  7596. for (var index = 0; index < this._maxTextureChannels; index++) {
  7597. this._activeTexturesCache[index] = null;
  7598. }
  7599. };
  7600. Engine.prototype.getGlInfo = function () {
  7601. return {
  7602. vendor: this._glVendor,
  7603. renderer: this._glRenderer,
  7604. version: this._glVersion
  7605. };
  7606. };
  7607. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7608. if (useScreen === void 0) { useScreen = false; }
  7609. var viewport = camera.viewport;
  7610. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7611. };
  7612. Engine.prototype.getRenderWidth = function (useScreen) {
  7613. if (useScreen === void 0) { useScreen = false; }
  7614. if (!useScreen && this._currentRenderTarget) {
  7615. return this._currentRenderTarget._width;
  7616. }
  7617. return this._renderingCanvas.width;
  7618. };
  7619. Engine.prototype.getRenderHeight = function (useScreen) {
  7620. if (useScreen === void 0) { useScreen = false; }
  7621. if (!useScreen && this._currentRenderTarget) {
  7622. return this._currentRenderTarget._height;
  7623. }
  7624. return this._renderingCanvas.height;
  7625. };
  7626. Engine.prototype.getRenderingCanvas = function () {
  7627. return this._renderingCanvas;
  7628. };
  7629. Engine.prototype.getRenderingCanvasClientRect = function () {
  7630. return this._renderingCanvas.getBoundingClientRect();
  7631. };
  7632. Engine.prototype.setHardwareScalingLevel = function (level) {
  7633. this._hardwareScalingLevel = level;
  7634. this.resize();
  7635. };
  7636. Engine.prototype.getHardwareScalingLevel = function () {
  7637. return this._hardwareScalingLevel;
  7638. };
  7639. Engine.prototype.getLoadedTexturesCache = function () {
  7640. return this._loadedTexturesCache;
  7641. };
  7642. Engine.prototype.getCaps = function () {
  7643. return this._caps;
  7644. };
  7645. Object.defineProperty(Engine.prototype, "drawCalls", {
  7646. get: function () {
  7647. return this._drawCalls.current;
  7648. },
  7649. enumerable: true,
  7650. configurable: true
  7651. });
  7652. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7653. get: function () {
  7654. return this._drawCalls;
  7655. },
  7656. enumerable: true,
  7657. configurable: true
  7658. });
  7659. Engine.prototype.getDepthFunction = function () {
  7660. return this._depthCullingState.depthFunc;
  7661. };
  7662. Engine.prototype.setDepthFunction = function (depthFunc) {
  7663. this._depthCullingState.depthFunc = depthFunc;
  7664. };
  7665. Engine.prototype.setDepthFunctionToGreater = function () {
  7666. this._depthCullingState.depthFunc = this._gl.GREATER;
  7667. };
  7668. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7669. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7670. };
  7671. Engine.prototype.setDepthFunctionToLess = function () {
  7672. this._depthCullingState.depthFunc = this._gl.LESS;
  7673. };
  7674. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7675. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7676. };
  7677. Engine.prototype.getStencilBuffer = function () {
  7678. return this._stencilState.stencilTest;
  7679. };
  7680. Engine.prototype.setStencilBuffer = function (enable) {
  7681. this._stencilState.stencilTest = enable;
  7682. };
  7683. Engine.prototype.getStencilMask = function () {
  7684. return this._stencilState.stencilMask;
  7685. };
  7686. Engine.prototype.setStencilMask = function (mask) {
  7687. this._stencilState.stencilMask = mask;
  7688. };
  7689. Engine.prototype.getStencilFunction = function () {
  7690. return this._stencilState.stencilFunc;
  7691. };
  7692. Engine.prototype.getStencilFunctionReference = function () {
  7693. return this._stencilState.stencilFuncRef;
  7694. };
  7695. Engine.prototype.getStencilFunctionMask = function () {
  7696. return this._stencilState.stencilFuncMask;
  7697. };
  7698. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7699. this._stencilState.stencilFunc = stencilFunc;
  7700. };
  7701. Engine.prototype.setStencilFunctionReference = function (reference) {
  7702. this._stencilState.stencilFuncRef = reference;
  7703. };
  7704. Engine.prototype.setStencilFunctionMask = function (mask) {
  7705. this._stencilState.stencilFuncMask = mask;
  7706. };
  7707. Engine.prototype.getStencilOperationFail = function () {
  7708. return this._stencilState.stencilOpStencilFail;
  7709. };
  7710. Engine.prototype.getStencilOperationDepthFail = function () {
  7711. return this._stencilState.stencilOpDepthFail;
  7712. };
  7713. Engine.prototype.getStencilOperationPass = function () {
  7714. return this._stencilState.stencilOpStencilDepthPass;
  7715. };
  7716. Engine.prototype.setStencilOperationFail = function (operation) {
  7717. this._stencilState.stencilOpStencilFail = operation;
  7718. };
  7719. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7720. this._stencilState.stencilOpDepthFail = operation;
  7721. };
  7722. Engine.prototype.setStencilOperationPass = function (operation) {
  7723. this._stencilState.stencilOpStencilDepthPass = operation;
  7724. };
  7725. /**
  7726. * stop executing a render loop function and remove it from the execution array
  7727. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7728. */
  7729. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7730. if (!renderFunction) {
  7731. this._activeRenderLoops = [];
  7732. return;
  7733. }
  7734. var index = this._activeRenderLoops.indexOf(renderFunction);
  7735. if (index >= 0) {
  7736. this._activeRenderLoops.splice(index, 1);
  7737. }
  7738. };
  7739. Engine.prototype._renderLoop = function () {
  7740. var shouldRender = true;
  7741. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7742. shouldRender = false;
  7743. }
  7744. if (shouldRender) {
  7745. // Start new frame
  7746. this.beginFrame();
  7747. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7748. var renderFunction = this._activeRenderLoops[index];
  7749. renderFunction();
  7750. }
  7751. // Present
  7752. this.endFrame();
  7753. }
  7754. if (this._activeRenderLoops.length > 0) {
  7755. // Register new frame
  7756. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7757. }
  7758. else {
  7759. this._renderingQueueLaunched = false;
  7760. }
  7761. };
  7762. /**
  7763. * Register and execute a render loop. The engine can have more than one render function.
  7764. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7765. * @example
  7766. * engine.runRenderLoop(function () {
  7767. * scene.render()
  7768. * })
  7769. */
  7770. Engine.prototype.runRenderLoop = function (renderFunction) {
  7771. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7772. return;
  7773. }
  7774. this._activeRenderLoops.push(renderFunction);
  7775. if (!this._renderingQueueLaunched) {
  7776. this._renderingQueueLaunched = true;
  7777. this._bindedRenderFunction = this._renderLoop.bind(this);
  7778. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7779. }
  7780. };
  7781. /**
  7782. * Toggle full screen mode.
  7783. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7784. * @param {any} options - an options object to be sent to the requestFullscreen function
  7785. */
  7786. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7787. if (this.isFullscreen) {
  7788. BABYLON.Tools.ExitFullscreen();
  7789. }
  7790. else {
  7791. this._pointerLockRequested = requestPointerLock;
  7792. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7793. }
  7794. };
  7795. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7796. if (stencil === void 0) { stencil = false; }
  7797. this.applyStates();
  7798. var mode = 0;
  7799. if (backBuffer && color) {
  7800. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7801. mode |= this._gl.COLOR_BUFFER_BIT;
  7802. }
  7803. if (depth) {
  7804. this._gl.clearDepth(1.0);
  7805. mode |= this._gl.DEPTH_BUFFER_BIT;
  7806. }
  7807. if (stencil) {
  7808. this._gl.clearStencil(0);
  7809. mode |= this._gl.STENCIL_BUFFER_BIT;
  7810. }
  7811. this._gl.clear(mode);
  7812. };
  7813. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7814. var gl = this._gl;
  7815. // Save state
  7816. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7817. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7818. // Change state
  7819. gl.enable(gl.SCISSOR_TEST);
  7820. gl.scissor(x, y, width, height);
  7821. // Clear
  7822. this.clear(clearColor, true, true, true);
  7823. // Restore state
  7824. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7825. if (curScissor === true) {
  7826. gl.enable(gl.SCISSOR_TEST);
  7827. }
  7828. else {
  7829. gl.disable(gl.SCISSOR_TEST);
  7830. }
  7831. };
  7832. /**
  7833. * Set the WebGL's viewport
  7834. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7835. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7836. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7837. */
  7838. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7839. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7840. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7841. var x = viewport.x || 0;
  7842. var y = viewport.y || 0;
  7843. this._cachedViewport = viewport;
  7844. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7845. };
  7846. /**
  7847. * Directly set the WebGL Viewport
  7848. * The x, y, width & height are directly passed to the WebGL call
  7849. * @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.
  7850. */
  7851. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7852. var currentViewport = this._cachedViewport;
  7853. this._cachedViewport = null;
  7854. this._gl.viewport(x, y, width, height);
  7855. return currentViewport;
  7856. };
  7857. Engine.prototype.beginFrame = function () {
  7858. this._measureFps();
  7859. };
  7860. Engine.prototype.endFrame = function () {
  7861. //force a flush in case we are using a bad OS.
  7862. if (this._badOS) {
  7863. this.flushFramebuffer();
  7864. }
  7865. //submit frame to the vr device, if enabled
  7866. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7867. this._vrDisplayEnabled.submitFrame();
  7868. }
  7869. };
  7870. /**
  7871. * resize the view according to the canvas' size.
  7872. * @example
  7873. * window.addEventListener("resize", function () {
  7874. * engine.resize();
  7875. * });
  7876. */
  7877. Engine.prototype.resize = function () {
  7878. // We're not resizing the size of the canvas while in VR mode & presenting
  7879. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  7880. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7881. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7882. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7883. }
  7884. };
  7885. /**
  7886. * force a specific size of the canvas
  7887. * @param {number} width - the new canvas' width
  7888. * @param {number} height - the new canvas' height
  7889. */
  7890. Engine.prototype.setSize = function (width, height) {
  7891. this._renderingCanvas.width = width;
  7892. this._renderingCanvas.height = height;
  7893. for (var index = 0; index < this.scenes.length; index++) {
  7894. var scene = this.scenes[index];
  7895. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7896. var cam = scene.cameras[camIndex];
  7897. cam._currentRenderId = 0;
  7898. }
  7899. }
  7900. };
  7901. //WebVR functions
  7902. Engine.prototype.initWebVR = function () {
  7903. if (!this.vrDisplaysPromise) {
  7904. this._getVRDisplays();
  7905. }
  7906. };
  7907. Engine.prototype.enableVR = function (vrDevice) {
  7908. this._vrDisplayEnabled = vrDevice;
  7909. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7910. };
  7911. Engine.prototype.disableVR = function () {
  7912. if (this._vrDisplayEnabled) {
  7913. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7914. }
  7915. };
  7916. Engine.prototype._getVRDisplays = function () {
  7917. var _this = this;
  7918. var getWebVRDevices = function (devices) {
  7919. var size = devices.length;
  7920. var i = 0;
  7921. _this._vrDisplays = devices.filter(function (device) {
  7922. return devices[i] instanceof VRDisplay;
  7923. });
  7924. return _this._vrDisplays;
  7925. };
  7926. //using a key due to typescript
  7927. if (navigator.getVRDisplays) {
  7928. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7929. }
  7930. };
  7931. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7932. this._currentRenderTarget = texture;
  7933. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  7934. var gl = this._gl;
  7935. if (texture.isCube) {
  7936. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7937. }
  7938. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7939. this.wipeCaches();
  7940. };
  7941. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7942. if (this._currentFramebuffer !== framebuffer) {
  7943. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7944. this._currentFramebuffer = framebuffer;
  7945. }
  7946. };
  7947. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  7948. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7949. this._currentRenderTarget = null;
  7950. // If MSAA, we need to bitblt back to main texture
  7951. var gl = this._gl;
  7952. if (texture._MSAAFramebuffer) {
  7953. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  7954. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  7955. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  7956. }
  7957. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7958. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7959. gl.generateMipmap(gl.TEXTURE_2D);
  7960. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7961. }
  7962. if (onBeforeUnbind) {
  7963. if (texture._MSAAFramebuffer) {
  7964. // Bind the correct framebuffer
  7965. this.bindUnboundFramebuffer(texture._framebuffer);
  7966. }
  7967. onBeforeUnbind();
  7968. }
  7969. this.bindUnboundFramebuffer(null);
  7970. };
  7971. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7972. if (texture.generateMipMaps) {
  7973. var gl = this._gl;
  7974. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7975. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7976. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7977. }
  7978. };
  7979. Engine.prototype.flushFramebuffer = function () {
  7980. this._gl.flush();
  7981. };
  7982. Engine.prototype.restoreDefaultFramebuffer = function () {
  7983. this._currentRenderTarget = null;
  7984. this.bindUnboundFramebuffer(null);
  7985. this.setViewport(this._cachedViewport);
  7986. this.wipeCaches();
  7987. };
  7988. // VBOs
  7989. Engine.prototype._resetVertexBufferBinding = function () {
  7990. this.bindArrayBuffer(null);
  7991. this._cachedVertexBuffers = null;
  7992. };
  7993. Engine.prototype.createVertexBuffer = function (vertices) {
  7994. var vbo = this._gl.createBuffer();
  7995. this.bindArrayBuffer(vbo);
  7996. if (vertices instanceof Float32Array) {
  7997. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7998. }
  7999. else {
  8000. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8001. }
  8002. this._resetVertexBufferBinding();
  8003. vbo.references = 1;
  8004. return vbo;
  8005. };
  8006. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8007. var vbo = this._gl.createBuffer();
  8008. this.bindArrayBuffer(vbo);
  8009. if (vertices instanceof Float32Array) {
  8010. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8011. }
  8012. else {
  8013. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8014. }
  8015. this._resetVertexBufferBinding();
  8016. vbo.references = 1;
  8017. return vbo;
  8018. };
  8019. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8020. this.bindArrayBuffer(vertexBuffer);
  8021. if (offset === undefined) {
  8022. offset = 0;
  8023. }
  8024. if (count === undefined) {
  8025. if (vertices instanceof Float32Array) {
  8026. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8027. }
  8028. else {
  8029. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8030. }
  8031. }
  8032. else {
  8033. if (vertices instanceof Float32Array) {
  8034. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8035. }
  8036. else {
  8037. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8038. }
  8039. }
  8040. this._resetVertexBufferBinding();
  8041. };
  8042. Engine.prototype._resetIndexBufferBinding = function () {
  8043. this.bindIndexBuffer(null);
  8044. this._cachedIndexBuffer = null;
  8045. };
  8046. Engine.prototype.createIndexBuffer = function (indices) {
  8047. var vbo = this._gl.createBuffer();
  8048. this.bindIndexBuffer(vbo);
  8049. // Check for 32 bits indices
  8050. var arrayBuffer;
  8051. var need32Bits = false;
  8052. if (indices instanceof Uint16Array) {
  8053. arrayBuffer = indices;
  8054. }
  8055. else {
  8056. //check 32 bit support
  8057. if (this._caps.uintIndices) {
  8058. if (indices instanceof Uint32Array) {
  8059. arrayBuffer = indices;
  8060. need32Bits = true;
  8061. }
  8062. else {
  8063. //number[] or Int32Array, check if 32 bit is necessary
  8064. for (var index = 0; index < indices.length; index++) {
  8065. if (indices[index] > 65535) {
  8066. need32Bits = true;
  8067. break;
  8068. }
  8069. }
  8070. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8071. }
  8072. }
  8073. else {
  8074. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8075. arrayBuffer = new Uint16Array(indices);
  8076. }
  8077. }
  8078. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8079. this._resetIndexBufferBinding();
  8080. vbo.references = 1;
  8081. vbo.is32Bits = need32Bits;
  8082. return vbo;
  8083. };
  8084. Engine.prototype.bindArrayBuffer = function (buffer) {
  8085. if (!this._vaoRecordInProgress) {
  8086. this._unBindVertexArrayObject();
  8087. }
  8088. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8089. };
  8090. Engine.prototype.bindIndexBuffer = function (buffer) {
  8091. if (!this._vaoRecordInProgress) {
  8092. this._unBindVertexArrayObject();
  8093. }
  8094. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8095. };
  8096. Engine.prototype.bindBuffer = function (buffer, target) {
  8097. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8098. this._gl.bindBuffer(target, buffer);
  8099. this._currentBoundBuffer[target] = buffer;
  8100. }
  8101. };
  8102. Engine.prototype.updateArrayBuffer = function (data) {
  8103. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8104. };
  8105. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8106. var pointer = this._currentBufferPointers[indx];
  8107. var changed = false;
  8108. if (!pointer) {
  8109. changed = true;
  8110. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8111. }
  8112. else {
  8113. if (pointer.buffer !== buffer) {
  8114. pointer.buffer = buffer;
  8115. changed = true;
  8116. }
  8117. if (pointer.size !== size) {
  8118. pointer.size = size;
  8119. changed = true;
  8120. }
  8121. if (pointer.type !== type) {
  8122. pointer.type = type;
  8123. changed = true;
  8124. }
  8125. if (pointer.normalized !== normalized) {
  8126. pointer.normalized = normalized;
  8127. changed = true;
  8128. }
  8129. if (pointer.stride !== stride) {
  8130. pointer.stride = stride;
  8131. changed = true;
  8132. }
  8133. if (pointer.offset !== offset) {
  8134. pointer.offset = offset;
  8135. changed = true;
  8136. }
  8137. }
  8138. if (changed || this._vaoRecordInProgress) {
  8139. this.bindArrayBuffer(buffer);
  8140. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8141. }
  8142. };
  8143. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8144. if (indexBuffer == null) {
  8145. return;
  8146. }
  8147. if (this._cachedIndexBuffer !== indexBuffer) {
  8148. this._cachedIndexBuffer = indexBuffer;
  8149. this.bindIndexBuffer(indexBuffer);
  8150. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8151. }
  8152. };
  8153. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8154. var attributes = effect.getAttributesNames();
  8155. if (!this._vaoRecordInProgress) {
  8156. this._unBindVertexArrayObject();
  8157. }
  8158. this.unbindAllAttributes();
  8159. for (var index = 0; index < attributes.length; index++) {
  8160. var order = effect.getAttributeLocation(index);
  8161. if (order >= 0) {
  8162. var vertexBuffer = vertexBuffers[attributes[index]];
  8163. if (!vertexBuffer) {
  8164. continue;
  8165. }
  8166. this._gl.enableVertexAttribArray(order);
  8167. if (!this._vaoRecordInProgress) {
  8168. this._vertexAttribArraysEnabled[order] = true;
  8169. }
  8170. var buffer = vertexBuffer.getBuffer();
  8171. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8172. if (vertexBuffer.getIsInstanced()) {
  8173. this._gl.vertexAttribDivisor(order, 1);
  8174. if (!this._vaoRecordInProgress) {
  8175. this._currentInstanceLocations.push(order);
  8176. this._currentInstanceBuffers.push(buffer);
  8177. }
  8178. }
  8179. }
  8180. }
  8181. };
  8182. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8183. var vao = this._gl.createVertexArray();
  8184. this._vaoRecordInProgress = true;
  8185. this._gl.bindVertexArray(vao);
  8186. this._mustWipeVertexAttributes = true;
  8187. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8188. this.bindIndexBuffer(indexBuffer);
  8189. this._vaoRecordInProgress = false;
  8190. this._gl.bindVertexArray(null);
  8191. return vao;
  8192. };
  8193. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8194. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8195. this._cachedVertexArrayObject = vertexArrayObject;
  8196. this._gl.bindVertexArray(vertexArrayObject);
  8197. this._cachedVertexBuffers = null;
  8198. this._cachedIndexBuffer = null;
  8199. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8200. this._mustWipeVertexAttributes = true;
  8201. }
  8202. };
  8203. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8204. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8205. this._cachedVertexBuffers = vertexBuffer;
  8206. this._cachedEffectForVertexBuffers = effect;
  8207. var attributesCount = effect.getAttributesCount();
  8208. this._unBindVertexArrayObject();
  8209. this.unbindAllAttributes();
  8210. var offset = 0;
  8211. for (var index = 0; index < attributesCount; index++) {
  8212. if (index < vertexDeclaration.length) {
  8213. var order = effect.getAttributeLocation(index);
  8214. if (order >= 0) {
  8215. this._gl.enableVertexAttribArray(order);
  8216. this._vertexAttribArraysEnabled[order] = true;
  8217. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8218. }
  8219. offset += vertexDeclaration[index] * 4;
  8220. }
  8221. }
  8222. }
  8223. this._bindIndexBufferWithCache(indexBuffer);
  8224. };
  8225. Engine.prototype._unBindVertexArrayObject = function () {
  8226. if (!this._cachedVertexArrayObject) {
  8227. return;
  8228. }
  8229. this._cachedVertexArrayObject = null;
  8230. this._gl.bindVertexArray(null);
  8231. };
  8232. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8233. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8234. this._cachedVertexBuffers = vertexBuffers;
  8235. this._cachedEffectForVertexBuffers = effect;
  8236. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8237. }
  8238. this._bindIndexBufferWithCache(indexBuffer);
  8239. };
  8240. Engine.prototype.unbindInstanceAttributes = function () {
  8241. var boundBuffer;
  8242. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8243. var instancesBuffer = this._currentInstanceBuffers[i];
  8244. if (boundBuffer != instancesBuffer) {
  8245. boundBuffer = instancesBuffer;
  8246. this.bindArrayBuffer(instancesBuffer);
  8247. }
  8248. var offsetLocation = this._currentInstanceLocations[i];
  8249. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8250. }
  8251. this._currentInstanceBuffers.length = 0;
  8252. this._currentInstanceLocations.length = 0;
  8253. };
  8254. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8255. this._gl.deleteVertexArray(vao);
  8256. };
  8257. Engine.prototype._releaseBuffer = function (buffer) {
  8258. buffer.references--;
  8259. if (buffer.references === 0) {
  8260. this._gl.deleteBuffer(buffer);
  8261. return true;
  8262. }
  8263. return false;
  8264. };
  8265. Engine.prototype.createInstancesBuffer = function (capacity) {
  8266. var buffer = this._gl.createBuffer();
  8267. buffer.capacity = capacity;
  8268. this.bindArrayBuffer(buffer);
  8269. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8270. return buffer;
  8271. };
  8272. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8273. this._gl.deleteBuffer(buffer);
  8274. };
  8275. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8276. this.bindArrayBuffer(instancesBuffer);
  8277. if (data) {
  8278. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8279. }
  8280. if (offsetLocations[0].index !== undefined) {
  8281. var stride = 0;
  8282. for (var i = 0; i < offsetLocations.length; i++) {
  8283. var ai = offsetLocations[i];
  8284. stride += ai.attributeSize * 4;
  8285. }
  8286. for (var i = 0; i < offsetLocations.length; i++) {
  8287. var ai = offsetLocations[i];
  8288. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8289. this._gl.enableVertexAttribArray(ai.index);
  8290. this._vertexAttribArraysEnabled[ai.index] = true;
  8291. }
  8292. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8293. this._gl.vertexAttribDivisor(ai.index, 1);
  8294. this._currentInstanceLocations.push(ai.index);
  8295. this._currentInstanceBuffers.push(instancesBuffer);
  8296. }
  8297. }
  8298. else {
  8299. for (var index = 0; index < 4; index++) {
  8300. var offsetLocation = offsetLocations[index];
  8301. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8302. this._gl.enableVertexAttribArray(offsetLocation);
  8303. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8304. }
  8305. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8306. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8307. this._currentInstanceLocations.push(offsetLocation);
  8308. this._currentInstanceBuffers.push(instancesBuffer);
  8309. }
  8310. }
  8311. };
  8312. Engine.prototype.applyStates = function () {
  8313. this._depthCullingState.apply(this._gl);
  8314. this._stencilState.apply(this._gl);
  8315. this._alphaState.apply(this._gl);
  8316. };
  8317. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8318. // Apply states
  8319. this.applyStates();
  8320. this._drawCalls.addCount(1, false);
  8321. // Render
  8322. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8323. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8324. if (instancesCount) {
  8325. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8326. return;
  8327. }
  8328. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8329. };
  8330. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8331. // Apply states
  8332. this.applyStates();
  8333. this._drawCalls.addCount(1, false);
  8334. if (instancesCount) {
  8335. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8336. return;
  8337. }
  8338. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8339. };
  8340. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8341. // Apply states
  8342. this.applyStates();
  8343. this._drawCalls.addCount(1, false);
  8344. if (instancesCount) {
  8345. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8346. return;
  8347. }
  8348. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8349. };
  8350. // Shaders
  8351. Engine.prototype._releaseEffect = function (effect) {
  8352. if (this._compiledEffects[effect._key]) {
  8353. delete this._compiledEffects[effect._key];
  8354. if (effect.getProgram()) {
  8355. this._gl.deleteProgram(effect.getProgram());
  8356. }
  8357. }
  8358. };
  8359. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8360. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8361. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8362. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8363. if (this._compiledEffects[name]) {
  8364. return this._compiledEffects[name];
  8365. }
  8366. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8367. effect._key = name;
  8368. this._compiledEffects[name] = effect;
  8369. return effect;
  8370. };
  8371. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8372. if (uniformsNames === void 0) { uniformsNames = []; }
  8373. if (samplers === void 0) { samplers = []; }
  8374. if (defines === void 0) { defines = ""; }
  8375. return this.createEffect({
  8376. vertex: "particles",
  8377. fragmentElement: fragmentName
  8378. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8379. };
  8380. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8381. context = context || this._gl;
  8382. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8383. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8384. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8385. var shaderProgram = context.createProgram();
  8386. context.attachShader(shaderProgram, vertexShader);
  8387. context.attachShader(shaderProgram, fragmentShader);
  8388. context.linkProgram(shaderProgram);
  8389. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8390. if (!linked) {
  8391. var error = context.getProgramInfoLog(shaderProgram);
  8392. if (error) {
  8393. throw new Error(error);
  8394. }
  8395. }
  8396. context.deleteShader(vertexShader);
  8397. context.deleteShader(fragmentShader);
  8398. return shaderProgram;
  8399. };
  8400. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8401. var results = [];
  8402. for (var index = 0; index < uniformsNames.length; index++) {
  8403. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8404. }
  8405. return results;
  8406. };
  8407. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8408. var results = [];
  8409. for (var index = 0; index < attributesNames.length; index++) {
  8410. try {
  8411. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8412. }
  8413. catch (e) {
  8414. results.push(-1);
  8415. }
  8416. }
  8417. return results;
  8418. };
  8419. Engine.prototype.enableEffect = function (effect) {
  8420. // Use program
  8421. this.setProgram(effect.getProgram());
  8422. this._currentEffect = effect;
  8423. if (effect.onBind) {
  8424. effect.onBind(effect);
  8425. }
  8426. };
  8427. Engine.prototype.setIntArray = function (uniform, array) {
  8428. if (!uniform)
  8429. return;
  8430. this._gl.uniform1iv(uniform, array);
  8431. };
  8432. Engine.prototype.setIntArray2 = function (uniform, array) {
  8433. if (!uniform || array.length % 2 !== 0)
  8434. return;
  8435. this._gl.uniform2iv(uniform, array);
  8436. };
  8437. Engine.prototype.setIntArray3 = function (uniform, array) {
  8438. if (!uniform || array.length % 3 !== 0)
  8439. return;
  8440. this._gl.uniform3iv(uniform, array);
  8441. };
  8442. Engine.prototype.setIntArray4 = function (uniform, array) {
  8443. if (!uniform || array.length % 4 !== 0)
  8444. return;
  8445. this._gl.uniform4iv(uniform, array);
  8446. };
  8447. Engine.prototype.setFloatArray = function (uniform, array) {
  8448. if (!uniform)
  8449. return;
  8450. this._gl.uniform1fv(uniform, array);
  8451. };
  8452. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8453. if (!uniform || array.length % 2 !== 0)
  8454. return;
  8455. this._gl.uniform2fv(uniform, array);
  8456. };
  8457. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8458. if (!uniform || array.length % 3 !== 0)
  8459. return;
  8460. this._gl.uniform3fv(uniform, array);
  8461. };
  8462. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8463. if (!uniform || array.length % 4 !== 0)
  8464. return;
  8465. this._gl.uniform4fv(uniform, array);
  8466. };
  8467. Engine.prototype.setArray = function (uniform, array) {
  8468. if (!uniform)
  8469. return;
  8470. this._gl.uniform1fv(uniform, array);
  8471. };
  8472. Engine.prototype.setArray2 = function (uniform, array) {
  8473. if (!uniform || array.length % 2 !== 0)
  8474. return;
  8475. this._gl.uniform2fv(uniform, array);
  8476. };
  8477. Engine.prototype.setArray3 = function (uniform, array) {
  8478. if (!uniform || array.length % 3 !== 0)
  8479. return;
  8480. this._gl.uniform3fv(uniform, array);
  8481. };
  8482. Engine.prototype.setArray4 = function (uniform, array) {
  8483. if (!uniform || array.length % 4 !== 0)
  8484. return;
  8485. this._gl.uniform4fv(uniform, array);
  8486. };
  8487. Engine.prototype.setMatrices = function (uniform, matrices) {
  8488. if (!uniform)
  8489. return;
  8490. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8491. };
  8492. Engine.prototype.setMatrix = function (uniform, matrix) {
  8493. if (!uniform)
  8494. return;
  8495. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8496. };
  8497. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8498. if (!uniform)
  8499. return;
  8500. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8501. };
  8502. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8503. if (!uniform)
  8504. return;
  8505. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8506. };
  8507. Engine.prototype.setFloat = function (uniform, value) {
  8508. if (!uniform)
  8509. return;
  8510. this._gl.uniform1f(uniform, value);
  8511. };
  8512. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8513. if (!uniform)
  8514. return;
  8515. this._gl.uniform2f(uniform, x, y);
  8516. };
  8517. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8518. if (!uniform)
  8519. return;
  8520. this._gl.uniform3f(uniform, x, y, z);
  8521. };
  8522. Engine.prototype.setBool = function (uniform, bool) {
  8523. if (!uniform)
  8524. return;
  8525. this._gl.uniform1i(uniform, bool);
  8526. };
  8527. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8528. if (!uniform)
  8529. return;
  8530. this._gl.uniform4f(uniform, x, y, z, w);
  8531. };
  8532. Engine.prototype.setColor3 = function (uniform, color3) {
  8533. if (!uniform)
  8534. return;
  8535. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8536. };
  8537. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8538. if (!uniform)
  8539. return;
  8540. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8541. };
  8542. // States
  8543. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8544. if (zOffset === void 0) { zOffset = 0; }
  8545. if (reverseSide === void 0) { reverseSide = false; }
  8546. // Culling
  8547. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8548. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8549. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8550. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8551. if (culling) {
  8552. this._depthCullingState.cullFace = cullFace;
  8553. this._depthCullingState.cull = true;
  8554. }
  8555. else {
  8556. this._depthCullingState.cull = false;
  8557. }
  8558. }
  8559. // Z offset
  8560. this._depthCullingState.zOffset = zOffset;
  8561. };
  8562. Engine.prototype.setDepthBuffer = function (enable) {
  8563. this._depthCullingState.depthTest = enable;
  8564. };
  8565. Engine.prototype.getDepthWrite = function () {
  8566. return this._depthCullingState.depthMask;
  8567. };
  8568. Engine.prototype.setDepthWrite = function (enable) {
  8569. this._depthCullingState.depthMask = enable;
  8570. };
  8571. Engine.prototype.setColorWrite = function (enable) {
  8572. this._gl.colorMask(enable, enable, enable, enable);
  8573. };
  8574. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8575. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8576. if (this._alphaMode === mode) {
  8577. return;
  8578. }
  8579. switch (mode) {
  8580. case Engine.ALPHA_DISABLE:
  8581. this._alphaState.alphaBlend = false;
  8582. break;
  8583. case Engine.ALPHA_PREMULTIPLIED:
  8584. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8585. this._alphaState.alphaBlend = true;
  8586. break;
  8587. case Engine.ALPHA_COMBINE:
  8588. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8589. this._alphaState.alphaBlend = true;
  8590. break;
  8591. case Engine.ALPHA_ONEONE:
  8592. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8593. this._alphaState.alphaBlend = true;
  8594. break;
  8595. case Engine.ALPHA_ADD:
  8596. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8597. this._alphaState.alphaBlend = true;
  8598. break;
  8599. case Engine.ALPHA_SUBTRACT:
  8600. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8601. this._alphaState.alphaBlend = true;
  8602. break;
  8603. case Engine.ALPHA_MULTIPLY:
  8604. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8605. this._alphaState.alphaBlend = true;
  8606. break;
  8607. case Engine.ALPHA_MAXIMIZED:
  8608. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8609. this._alphaState.alphaBlend = true;
  8610. break;
  8611. }
  8612. if (!noDepthWriteChange) {
  8613. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8614. }
  8615. this._alphaMode = mode;
  8616. };
  8617. Engine.prototype.getAlphaMode = function () {
  8618. return this._alphaMode;
  8619. };
  8620. Engine.prototype.setAlphaTesting = function (enable) {
  8621. this._alphaTest = enable;
  8622. };
  8623. Engine.prototype.getAlphaTesting = function () {
  8624. return !!this._alphaTest;
  8625. };
  8626. // Textures
  8627. Engine.prototype.wipeCaches = function () {
  8628. if (this.preventCacheWipeBetweenFrames) {
  8629. return;
  8630. }
  8631. this.resetTextureCache();
  8632. this._currentEffect = null;
  8633. this._stencilState.reset();
  8634. this._depthCullingState.reset();
  8635. this.setDepthFunctionToLessOrEqual();
  8636. this._alphaState.reset();
  8637. this._cachedVertexBuffers = null;
  8638. this._cachedIndexBuffer = null;
  8639. this._cachedEffectForVertexBuffers = null;
  8640. this._unBindVertexArrayObject();
  8641. this.bindIndexBuffer(null);
  8642. this.bindArrayBuffer(null);
  8643. };
  8644. /**
  8645. * Set the compressed texture format to use, based on the formats you have, and the formats
  8646. * supported by the hardware / browser.
  8647. *
  8648. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8649. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8650. * to API arguments needed to compressed textures. This puts the burden on the container
  8651. * generator to house the arcane code for determining these for current & future formats.
  8652. *
  8653. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8654. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8655. *
  8656. * Note: The result of this call is not taken into account when a texture is base64.
  8657. *
  8658. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8659. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8660. *
  8661. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  8662. * @returns The extension selected.
  8663. */
  8664. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8665. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8666. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8667. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8668. return this._textureFormatInUse = this._texturesSupported[i];
  8669. }
  8670. }
  8671. }
  8672. // actively set format to nothing, to allow this to be called more than once
  8673. // and possibly fail the 2nd time
  8674. return this._textureFormatInUse = null;
  8675. };
  8676. /**
  8677. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  8678. * @param {string} urlArg- This contains one of the following:
  8679. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  8680. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  8681. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  8682. *
  8683. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  8684. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  8685. * @param {Scene} scene- Needed for loading to the correct scene.
  8686. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  8687. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  8688. * @param {callback} onError- Optional callback to be called upon failure.
  8689. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  8690. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  8691. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  8692. *
  8693. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  8694. */
  8695. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  8696. var _this = this;
  8697. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8698. if (onLoad === void 0) { onLoad = null; }
  8699. if (onError === void 0) { onError = null; }
  8700. if (buffer === void 0) { buffer = null; }
  8701. var texture = fallBack ? fallBack : this._gl.createTexture();
  8702. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  8703. var fromData = url.substr(0, 5) === "data:";
  8704. var isBase64 = fromData && url.indexOf("base64") !== -1;
  8705. // establish the file extension, if possible
  8706. var lastDot = url.lastIndexOf('.');
  8707. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  8708. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8709. if (isDDS) {
  8710. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  8711. }
  8712. var isTGA = (extension === ".tga");
  8713. // determine if a ktx file should be substituted
  8714. var isKTX = false;
  8715. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  8716. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8717. isKTX = true;
  8718. }
  8719. scene._addPendingData(texture);
  8720. texture.url = url;
  8721. texture.noMipmap = noMipmap;
  8722. texture.references = 1;
  8723. texture.samplingMode = samplingMode;
  8724. texture.onLoadedCallbacks = [];
  8725. if (onLoad) {
  8726. texture.onLoadedCallbacks.push(onLoad);
  8727. }
  8728. if (!fallBack)
  8729. this._loadedTexturesCache.push(texture);
  8730. var onerror = function () {
  8731. scene._removePendingData(texture);
  8732. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  8733. if (isKTX) {
  8734. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  8735. }
  8736. else if (onError) {
  8737. onError();
  8738. }
  8739. };
  8740. var callback;
  8741. // processing for non-image formats
  8742. if (isKTX || isTGA || isDDS) {
  8743. if (isKTX) {
  8744. callback = function (data) {
  8745. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  8746. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  8747. ktx.uploadLevels(_this._gl, !noMipmap);
  8748. }, samplingMode);
  8749. };
  8750. }
  8751. else if (isTGA) {
  8752. callback = function (arrayBuffer) {
  8753. var data = new Uint8Array(arrayBuffer);
  8754. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8755. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8756. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8757. }, samplingMode);
  8758. };
  8759. }
  8760. else if (isDDS) {
  8761. callback = function (data) {
  8762. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8763. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8764. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8765. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8766. }, samplingMode);
  8767. };
  8768. }
  8769. if (!buffer) {
  8770. BABYLON.Tools.LoadFile(url, function (data) {
  8771. callback(data);
  8772. }, null, scene.database, true, onerror);
  8773. }
  8774. else {
  8775. callback(buffer);
  8776. }
  8777. // image format processing
  8778. }
  8779. else {
  8780. var onload = function (img) {
  8781. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8782. var isPot = (img.width === potWidth && img.height === potHeight);
  8783. if (!isPot) {
  8784. _this._prepareWorkingCanvas();
  8785. _this._workingCanvas.width = potWidth;
  8786. _this._workingCanvas.height = potHeight;
  8787. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8788. _this._workingContext.imageSmoothingEnabled = false;
  8789. _this._workingContext.mozImageSmoothingEnabled = false;
  8790. _this._workingContext.oImageSmoothingEnabled = false;
  8791. _this._workingContext.webkitImageSmoothingEnabled = false;
  8792. _this._workingContext.msImageSmoothingEnabled = false;
  8793. }
  8794. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8795. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8796. _this._workingContext.imageSmoothingEnabled = true;
  8797. _this._workingContext.mozImageSmoothingEnabled = true;
  8798. _this._workingContext.oImageSmoothingEnabled = true;
  8799. _this._workingContext.webkitImageSmoothingEnabled = true;
  8800. _this._workingContext.msImageSmoothingEnabled = true;
  8801. }
  8802. }
  8803. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  8804. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8805. }, samplingMode);
  8806. };
  8807. if (!fromData || isBase64)
  8808. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8809. else if (buffer instanceof Array || typeof buffer === "string")
  8810. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8811. else
  8812. onload(buffer);
  8813. }
  8814. return texture;
  8815. };
  8816. Engine.prototype._getInternalFormat = function (format) {
  8817. var internalFormat = this._gl.RGBA;
  8818. switch (format) {
  8819. case Engine.TEXTUREFORMAT_ALPHA:
  8820. internalFormat = this._gl.ALPHA;
  8821. break;
  8822. case Engine.TEXTUREFORMAT_LUMINANCE:
  8823. internalFormat = this._gl.LUMINANCE;
  8824. break;
  8825. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8826. internalFormat = this._gl.LUMINANCE_ALPHA;
  8827. break;
  8828. case Engine.TEXTUREFORMAT_RGB:
  8829. internalFormat = this._gl.RGB;
  8830. break;
  8831. case Engine.TEXTUREFORMAT_RGBA:
  8832. internalFormat = this._gl.RGBA;
  8833. break;
  8834. }
  8835. return internalFormat;
  8836. };
  8837. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8838. if (compression === void 0) { compression = null; }
  8839. var internalFormat = this._getInternalFormat(format);
  8840. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8841. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8842. if (texture._width % 4 !== 0) {
  8843. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8844. }
  8845. if (compression) {
  8846. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8847. }
  8848. else {
  8849. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8850. }
  8851. if (texture.generateMipMaps) {
  8852. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8853. }
  8854. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8855. this.resetTextureCache();
  8856. texture.isReady = true;
  8857. };
  8858. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8859. if (compression === void 0) { compression = null; }
  8860. var texture = this._gl.createTexture();
  8861. texture._baseWidth = width;
  8862. texture._baseHeight = height;
  8863. texture._width = width;
  8864. texture._height = height;
  8865. texture.references = 1;
  8866. this.updateRawTexture(texture, data, format, invertY, compression);
  8867. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8868. // Filters
  8869. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8870. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8871. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8872. if (generateMipMaps) {
  8873. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8874. }
  8875. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8876. texture.samplingMode = samplingMode;
  8877. this._loadedTexturesCache.push(texture);
  8878. return texture;
  8879. };
  8880. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8881. var texture = this._gl.createTexture();
  8882. texture._baseWidth = width;
  8883. texture._baseHeight = height;
  8884. if (generateMipMaps) {
  8885. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8886. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8887. }
  8888. this.resetTextureCache();
  8889. texture._width = width;
  8890. texture._height = height;
  8891. texture.isReady = false;
  8892. texture.generateMipMaps = generateMipMaps;
  8893. texture.references = 1;
  8894. texture.samplingMode = samplingMode;
  8895. this.updateTextureSamplingMode(samplingMode, texture);
  8896. this._loadedTexturesCache.push(texture);
  8897. return texture;
  8898. };
  8899. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8900. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8901. if (texture.isCube) {
  8902. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8903. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8904. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8905. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8906. }
  8907. else {
  8908. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8909. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8910. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8911. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8912. }
  8913. texture.samplingMode = samplingMode;
  8914. };
  8915. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  8916. if (premulAlpha === void 0) { premulAlpha = false; }
  8917. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8918. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8919. if (premulAlpha) {
  8920. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8921. }
  8922. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  8923. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  8924. if (texture.generateMipMaps) {
  8925. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8926. }
  8927. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8928. if (premulAlpha) {
  8929. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8930. }
  8931. this.resetTextureCache();
  8932. texture.isReady = true;
  8933. };
  8934. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8935. if (texture._isDisabled) {
  8936. return;
  8937. }
  8938. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8939. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8940. try {
  8941. // Testing video texture support
  8942. if (this._videoTextureSupported === undefined) {
  8943. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8944. if (this._gl.getError() !== 0) {
  8945. this._videoTextureSupported = false;
  8946. }
  8947. else {
  8948. this._videoTextureSupported = true;
  8949. }
  8950. }
  8951. // Copy video through the current working canvas if video texture is not supported
  8952. if (!this._videoTextureSupported) {
  8953. if (!texture._workingCanvas) {
  8954. texture._workingCanvas = document.createElement("canvas");
  8955. texture._workingContext = texture._workingCanvas.getContext("2d");
  8956. texture._workingCanvas.width = texture._width;
  8957. texture._workingCanvas.height = texture._height;
  8958. }
  8959. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8960. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8961. }
  8962. else {
  8963. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8964. }
  8965. if (texture.generateMipMaps) {
  8966. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8967. }
  8968. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8969. this.resetTextureCache();
  8970. texture.isReady = true;
  8971. }
  8972. catch (ex) {
  8973. // Something unexpected
  8974. // Let's disable the texture
  8975. texture._isDisabled = true;
  8976. }
  8977. };
  8978. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8979. // old version had a "generateMipMaps" arg instead of options.
  8980. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8981. // in the same way, generateDepthBuffer is defaulted to true
  8982. var generateMipMaps = false;
  8983. var generateDepthBuffer = true;
  8984. var generateStencilBuffer = false;
  8985. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8986. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8987. if (options !== undefined) {
  8988. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8989. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8990. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8991. type = options.type === undefined ? type : options.type;
  8992. if (options.samplingMode !== undefined) {
  8993. samplingMode = options.samplingMode;
  8994. }
  8995. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8996. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8997. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8998. }
  8999. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9000. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9001. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9002. }
  9003. }
  9004. var gl = this._gl;
  9005. var texture = gl.createTexture();
  9006. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9007. var width = size.width || size;
  9008. var height = size.height || size;
  9009. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9010. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9011. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9012. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9013. }
  9014. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9016. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9017. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9018. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9019. // Create the framebuffer
  9020. var framebuffer = gl.createFramebuffer();
  9021. this.bindUnboundFramebuffer(framebuffer);
  9022. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9023. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9024. if (generateMipMaps) {
  9025. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9026. }
  9027. // Unbind
  9028. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9029. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9030. this.bindUnboundFramebuffer(null);
  9031. texture._framebuffer = framebuffer;
  9032. texture._baseWidth = width;
  9033. texture._baseHeight = height;
  9034. texture._width = width;
  9035. texture._height = height;
  9036. texture.isReady = true;
  9037. texture.samples = 1;
  9038. texture.generateMipMaps = generateMipMaps;
  9039. texture.references = 1;
  9040. texture.samplingMode = samplingMode;
  9041. texture.type = type;
  9042. texture._generateDepthBuffer = generateDepthBuffer;
  9043. texture._generateStencilBuffer = generateStencilBuffer;
  9044. this.resetTextureCache();
  9045. this._loadedTexturesCache.push(texture);
  9046. return texture;
  9047. };
  9048. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9049. if (samples === void 0) { samples = 1; }
  9050. var depthStencilBuffer = null;
  9051. var gl = this._gl;
  9052. // Create the depth/stencil buffer
  9053. if (generateStencilBuffer) {
  9054. depthStencilBuffer = gl.createRenderbuffer();
  9055. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9056. if (samples > 1) {
  9057. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9058. }
  9059. else {
  9060. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9061. }
  9062. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9063. }
  9064. else if (generateDepthBuffer) {
  9065. depthStencilBuffer = gl.createRenderbuffer();
  9066. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9067. if (samples > 1) {
  9068. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9069. }
  9070. else {
  9071. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9072. }
  9073. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9074. }
  9075. return depthStencilBuffer;
  9076. };
  9077. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9078. if (this.webGLVersion < 2) {
  9079. return 1;
  9080. }
  9081. if (texture.samples === samples) {
  9082. return samples;
  9083. }
  9084. var gl = this._gl;
  9085. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9086. // Dispose previous render buffers
  9087. if (texture._depthStencilBuffer) {
  9088. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9089. }
  9090. if (texture._MSAAFramebuffer) {
  9091. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9092. }
  9093. if (texture._MSAARenderBuffer) {
  9094. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9095. }
  9096. if (samples > 1) {
  9097. texture._MSAAFramebuffer = gl.createFramebuffer();
  9098. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9099. var colorRenderbuffer = gl.createRenderbuffer();
  9100. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9101. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9102. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9103. texture._MSAARenderBuffer = colorRenderbuffer;
  9104. }
  9105. else {
  9106. this.bindUnboundFramebuffer(texture._framebuffer);
  9107. }
  9108. texture.samples = samples;
  9109. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9110. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9111. this.bindUnboundFramebuffer(null);
  9112. return samples;
  9113. };
  9114. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9115. var gl = this._gl;
  9116. var texture = gl.createTexture();
  9117. var generateMipMaps = true;
  9118. var generateDepthBuffer = true;
  9119. var generateStencilBuffer = false;
  9120. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9121. if (options !== undefined) {
  9122. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9123. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9124. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9125. if (options.samplingMode !== undefined) {
  9126. samplingMode = options.samplingMode;
  9127. }
  9128. }
  9129. texture.isCube = true;
  9130. texture.references = 1;
  9131. texture.generateMipMaps = generateMipMaps;
  9132. texture.references = 1;
  9133. texture.samples = 1;
  9134. texture.samplingMode = samplingMode;
  9135. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9136. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9137. for (var face = 0; face < 6; face++) {
  9138. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9139. }
  9140. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9141. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9142. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9143. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9144. // Create the framebuffer
  9145. var framebuffer = gl.createFramebuffer();
  9146. this.bindUnboundFramebuffer(framebuffer);
  9147. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9148. // Mipmaps
  9149. if (texture.generateMipMaps) {
  9150. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9151. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9152. }
  9153. // Unbind
  9154. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9155. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9156. this.bindUnboundFramebuffer(null);
  9157. texture._framebuffer = framebuffer;
  9158. texture._width = size;
  9159. texture._height = size;
  9160. texture.isReady = true;
  9161. this.resetTextureCache();
  9162. this._loadedTexturesCache.push(texture);
  9163. return texture;
  9164. };
  9165. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9166. var _this = this;
  9167. if (onLoad === void 0) { onLoad = null; }
  9168. if (onError === void 0) { onError = null; }
  9169. var gl = this._gl;
  9170. var texture = gl.createTexture();
  9171. texture.isCube = true;
  9172. texture.url = rootUrl;
  9173. texture.references = 1;
  9174. texture.onLoadedCallbacks = [];
  9175. var isKTX = false;
  9176. var lastDot = rootUrl.lastIndexOf('.');
  9177. var extension = rootUrl.substring(lastDot).toLowerCase();
  9178. if (this._textureFormatInUse) {
  9179. extension = this._textureFormatInUse;
  9180. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9181. isKTX = true;
  9182. }
  9183. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9184. if (isDDS) {
  9185. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9186. }
  9187. if (isKTX) {
  9188. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9189. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9190. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9191. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9192. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9193. ktx.uploadLevels(_this._gl, !noMipmap);
  9194. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9195. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9196. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9197. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9198. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9199. _this.resetTextureCache();
  9200. texture._width = ktx.pixelWidth;
  9201. texture._height = ktx.pixelHeight;
  9202. texture.isReady = true;
  9203. }, null, null, true, onError);
  9204. }
  9205. else if (isDDS) {
  9206. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9207. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9208. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9209. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9210. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9211. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9212. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9213. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9214. }
  9215. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9216. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9217. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9218. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9219. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9220. _this.resetTextureCache();
  9221. texture._width = info.width;
  9222. texture._height = info.height;
  9223. texture.isReady = true;
  9224. }, null, null, true, onError);
  9225. }
  9226. else {
  9227. cascadeLoad(rootUrl, scene, function (imgs) {
  9228. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9229. var height = width;
  9230. _this._prepareWorkingCanvas();
  9231. _this._workingCanvas.width = width;
  9232. _this._workingCanvas.height = height;
  9233. var faces = [
  9234. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9235. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9236. ];
  9237. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9238. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9239. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9240. for (var index = 0; index < faces.length; index++) {
  9241. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9242. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9243. }
  9244. if (!noMipmap) {
  9245. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9246. }
  9247. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9248. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9249. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9250. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9251. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9252. _this.resetTextureCache();
  9253. texture._width = width;
  9254. texture._height = height;
  9255. texture.isReady = true;
  9256. texture.onLoadedCallbacks.forEach(function (callback) {
  9257. callback();
  9258. });
  9259. if (onLoad) {
  9260. onLoad();
  9261. }
  9262. }, files, onError);
  9263. }
  9264. this._loadedTexturesCache.push(texture);
  9265. return texture;
  9266. };
  9267. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9268. texture._width = width;
  9269. texture._height = height;
  9270. texture._size = width * height;
  9271. texture._baseWidth = width;
  9272. texture._baseHeight = height;
  9273. };
  9274. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  9275. var _this = this;
  9276. if (onLoad === void 0) { onLoad = null; }
  9277. if (onError === void 0) { onError = null; }
  9278. var gl = this._gl;
  9279. var texture = gl.createTexture();
  9280. scene._addPendingData(texture);
  9281. texture.isCube = true;
  9282. texture.references = 1;
  9283. texture.url = url;
  9284. var textureType = gl.UNSIGNED_BYTE;
  9285. if (type === Engine.TEXTURETYPE_FLOAT) {
  9286. textureType = gl.FLOAT;
  9287. }
  9288. var internalFormat = this._getInternalFormat(format);
  9289. var needConversion = false;
  9290. if (internalFormat === gl.RGB) {
  9291. internalFormat = gl.RGBA;
  9292. needConversion = true;
  9293. }
  9294. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9295. var width = size;
  9296. var height = width;
  9297. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9298. texture._width = width;
  9299. texture._height = height;
  9300. var onerror = function () {
  9301. scene._removePendingData(texture);
  9302. if (onError) {
  9303. onError();
  9304. }
  9305. };
  9306. var internalCallback = function (data) {
  9307. var rgbeDataArrays = callback(data);
  9308. var facesIndex = [
  9309. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9310. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9311. ];
  9312. width = texture._width;
  9313. height = texture._height;
  9314. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9315. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9316. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9317. if (mipmmapGenerator) {
  9318. var arrayTemp = [];
  9319. // Data are known to be in +X +Y +Z -X -Y -Z
  9320. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9321. arrayTemp.push(rgbeDataArrays[0]); // +X
  9322. arrayTemp.push(rgbeDataArrays[3]); // -X
  9323. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9324. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9325. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9326. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9327. var mipData = mipmmapGenerator(arrayTemp);
  9328. // mipData is order in +X -X +Y -Y +Z -Z
  9329. var mipFaces = [0, 2, 4, 1, 3, 5];
  9330. for (var level = 0; level < mipData.length; level++) {
  9331. var mipSize = width >> level;
  9332. for (var mipIndex in mipFaces) {
  9333. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9334. if (needConversion) {
  9335. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9336. }
  9337. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9338. }
  9339. }
  9340. }
  9341. else {
  9342. // Data are known to be in +X +Y +Z -X -Y -Z
  9343. for (var index = 0; index < facesIndex.length; index++) {
  9344. var faceData = rgbeDataArrays[index];
  9345. if (needConversion) {
  9346. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  9347. }
  9348. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  9349. }
  9350. if (!noMipmap && isPot) {
  9351. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9352. }
  9353. else {
  9354. noMipmap = true;
  9355. }
  9356. }
  9357. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  9358. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9360. }
  9361. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  9362. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9363. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9364. }
  9365. else {
  9366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9367. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9368. }
  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. texture.isReady = true;
  9373. _this.resetTextureCache();
  9374. scene._removePendingData(texture);
  9375. if (onLoad) {
  9376. onLoad();
  9377. }
  9378. };
  9379. BABYLON.Tools.LoadFile(url, function (data) {
  9380. internalCallback(data);
  9381. }, onerror, scene.database, true);
  9382. return texture;
  9383. };
  9384. ;
  9385. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9386. // Create new RGBA data container.
  9387. var rgbaData;
  9388. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9389. rgbaData = new Float32Array(width * height * 4);
  9390. }
  9391. else {
  9392. rgbaData = new Uint32Array(width * height * 4);
  9393. }
  9394. // Convert each pixel.
  9395. for (var x = 0; x < width; x++) {
  9396. for (var y = 0; y < height; y++) {
  9397. var index = (y * width + x) * 3;
  9398. var newIndex = (y * width + x) * 4;
  9399. // Map Old Value to new value.
  9400. rgbaData[newIndex + 0] = rgbData[index + 0];
  9401. rgbaData[newIndex + 1] = rgbData[index + 1];
  9402. rgbaData[newIndex + 2] = rgbData[index + 2];
  9403. // Add fully opaque alpha channel.
  9404. rgbaData[newIndex + 3] = 1;
  9405. }
  9406. }
  9407. return rgbaData;
  9408. };
  9409. Engine.prototype._releaseTexture = function (texture) {
  9410. var gl = this._gl;
  9411. if (texture._framebuffer) {
  9412. gl.deleteFramebuffer(texture._framebuffer);
  9413. }
  9414. if (texture._depthStencilBuffer) {
  9415. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9416. }
  9417. if (texture._MSAAFramebuffer) {
  9418. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9419. }
  9420. if (texture._MSAARenderBuffer) {
  9421. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9422. }
  9423. gl.deleteTexture(texture);
  9424. // Unbind channels
  9425. this.unbindAllTextures();
  9426. var index = this._loadedTexturesCache.indexOf(texture);
  9427. if (index !== -1) {
  9428. this._loadedTexturesCache.splice(index, 1);
  9429. }
  9430. };
  9431. Engine.prototype.setProgram = function (program) {
  9432. if (this._currentProgram !== program) {
  9433. this._gl.useProgram(program);
  9434. this._currentProgram = program;
  9435. }
  9436. };
  9437. Engine.prototype.bindSamplers = function (effect) {
  9438. this.setProgram(effect.getProgram());
  9439. var samplers = effect.getSamplers();
  9440. for (var index = 0; index < samplers.length; index++) {
  9441. var uniform = effect.getUniform(samplers[index]);
  9442. this._gl.uniform1i(uniform, index);
  9443. }
  9444. this._currentEffect = null;
  9445. };
  9446. Engine.prototype.activateTexture = function (texture) {
  9447. if (this._activeTexture !== texture) {
  9448. this._gl.activeTexture(texture);
  9449. this._activeTexture = texture;
  9450. }
  9451. };
  9452. Engine.prototype._bindTextureDirectly = function (target, texture) {
  9453. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  9454. this._gl.bindTexture(target, texture);
  9455. this._activeTexturesCache[this._activeTexture] = texture;
  9456. }
  9457. };
  9458. Engine.prototype._bindTexture = function (channel, texture) {
  9459. if (channel < 0) {
  9460. return;
  9461. }
  9462. this.activateTexture(this._gl.TEXTURE0 + channel);
  9463. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9464. };
  9465. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9466. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  9467. };
  9468. Engine.prototype.unbindAllTextures = function () {
  9469. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  9470. this.activateTexture(this._gl["TEXTURE" + channel]);
  9471. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9472. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9473. }
  9474. };
  9475. Engine.prototype.setTexture = function (channel, uniform, texture) {
  9476. if (channel < 0) {
  9477. return;
  9478. }
  9479. this._gl.uniform1i(uniform, channel);
  9480. this._setTexture(channel, texture);
  9481. };
  9482. Engine.prototype._setTexture = function (channel, texture) {
  9483. // Not ready?
  9484. if (!texture || !texture.isReady()) {
  9485. if (this._activeTexturesCache[channel] != null) {
  9486. this.activateTexture(this._gl["TEXTURE" + channel]);
  9487. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9488. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9489. }
  9490. return;
  9491. }
  9492. // Video
  9493. var alreadyActivated = false;
  9494. if (texture.video) {
  9495. this.activateTexture(this._gl["TEXTURE" + channel]);
  9496. alreadyActivated = true;
  9497. texture.update();
  9498. }
  9499. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  9500. texture.delayLoad();
  9501. return;
  9502. }
  9503. var internalTexture = texture.getInternalTexture();
  9504. if (this._activeTexturesCache[channel] === internalTexture) {
  9505. return;
  9506. }
  9507. if (!alreadyActivated) {
  9508. this.activateTexture(this._gl["TEXTURE" + channel]);
  9509. }
  9510. if (internalTexture.isCube) {
  9511. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  9512. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  9513. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  9514. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  9515. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  9516. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  9517. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  9518. }
  9519. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  9520. }
  9521. else {
  9522. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  9523. if (internalTexture._cachedWrapU !== texture.wrapU) {
  9524. internalTexture._cachedWrapU = texture.wrapU;
  9525. switch (texture.wrapU) {
  9526. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9527. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  9528. break;
  9529. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9530. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  9531. break;
  9532. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9533. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  9534. break;
  9535. }
  9536. }
  9537. if (internalTexture._cachedWrapV !== texture.wrapV) {
  9538. internalTexture._cachedWrapV = texture.wrapV;
  9539. switch (texture.wrapV) {
  9540. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9541. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  9542. break;
  9543. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9544. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  9545. break;
  9546. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9547. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  9548. break;
  9549. }
  9550. }
  9551. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  9552. }
  9553. };
  9554. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  9555. if (channel < 0) {
  9556. return;
  9557. }
  9558. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  9559. this._textureUnits = new Int32Array(textures.length);
  9560. }
  9561. for (var i = 0; i < textures.length; i++) {
  9562. this._textureUnits[i] = channel + i;
  9563. }
  9564. this._gl.uniform1iv(uniform, this._textureUnits);
  9565. for (var index = 0; index < textures.length; index++) {
  9566. this._setTexture(channel + index, textures[index]);
  9567. }
  9568. };
  9569. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  9570. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  9571. var value = texture.anisotropicFilteringLevel;
  9572. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9573. value = 1;
  9574. }
  9575. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  9576. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  9577. texture._cachedAnisotropicFilteringLevel = value;
  9578. }
  9579. };
  9580. Engine.prototype.readPixels = function (x, y, width, height) {
  9581. var data = new Uint8Array(height * width * 4);
  9582. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  9583. return data;
  9584. };
  9585. /**
  9586. * Add an externaly attached data from its key.
  9587. * This method call will fail and return false, if such key already exists.
  9588. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  9589. * @param key the unique key that identifies the data
  9590. * @param data the data object to associate to the key for this Engine instance
  9591. * @return true if no such key were already present and the data was added successfully, false otherwise
  9592. */
  9593. Engine.prototype.addExternalData = function (key, data) {
  9594. if (!this._externalData) {
  9595. this._externalData = new BABYLON.StringDictionary();
  9596. }
  9597. return this._externalData.add(key, data);
  9598. };
  9599. /**
  9600. * Get an externaly attached data from its key
  9601. * @param key the unique key that identifies the data
  9602. * @return the associated data, if present (can be null), or undefined if not present
  9603. */
  9604. Engine.prototype.getExternalData = function (key) {
  9605. if (!this._externalData) {
  9606. this._externalData = new BABYLON.StringDictionary();
  9607. }
  9608. return this._externalData.get(key);
  9609. };
  9610. /**
  9611. * Get an externaly attached data from its key, create it using a factory if it's not already present
  9612. * @param key the unique key that identifies the data
  9613. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  9614. * @return the associated data, can be null if the factory returned null.
  9615. */
  9616. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  9617. if (!this._externalData) {
  9618. this._externalData = new BABYLON.StringDictionary();
  9619. }
  9620. return this._externalData.getOrAddWithFactory(key, factory);
  9621. };
  9622. /**
  9623. * Remove an externaly attached data from the Engine instance
  9624. * @param key the unique key that identifies the data
  9625. * @return true if the data was successfully removed, false if it doesn't exist
  9626. */
  9627. Engine.prototype.removeExternalData = function (key) {
  9628. if (!this._externalData) {
  9629. this._externalData = new BABYLON.StringDictionary();
  9630. }
  9631. return this._externalData.remove(key);
  9632. };
  9633. Engine.prototype.releaseInternalTexture = function (texture) {
  9634. if (!texture) {
  9635. return;
  9636. }
  9637. texture.references--;
  9638. // Final reference ?
  9639. if (texture.references === 0) {
  9640. var texturesCache = this.getLoadedTexturesCache();
  9641. var index = texturesCache.indexOf(texture);
  9642. if (index > -1) {
  9643. texturesCache.splice(index, 1);
  9644. }
  9645. this._releaseTexture(texture);
  9646. }
  9647. };
  9648. Engine.prototype.unbindAllAttributes = function () {
  9649. if (this._mustWipeVertexAttributes) {
  9650. this._mustWipeVertexAttributes = false;
  9651. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9652. this._gl.disableVertexAttribArray(i);
  9653. this._vertexAttribArraysEnabled[i] = false;
  9654. this._currentBufferPointers[i] = null;
  9655. }
  9656. return;
  9657. }
  9658. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  9659. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  9660. continue;
  9661. }
  9662. this._gl.disableVertexAttribArray(i);
  9663. this._vertexAttribArraysEnabled[i] = false;
  9664. this._currentBufferPointers[i] = null;
  9665. }
  9666. };
  9667. Engine.prototype.releaseEffects = function () {
  9668. for (var name in this._compiledEffects) {
  9669. this._gl.deleteProgram(this._compiledEffects[name]._program);
  9670. }
  9671. this._compiledEffects = {};
  9672. };
  9673. // Dispose
  9674. Engine.prototype.dispose = function () {
  9675. this.hideLoadingUI();
  9676. this.stopRenderLoop();
  9677. // Release scenes
  9678. while (this.scenes.length) {
  9679. this.scenes[0].dispose();
  9680. }
  9681. // Release audio engine
  9682. Engine.audioEngine.dispose();
  9683. // Release effects
  9684. this.releaseEffects();
  9685. // Unbind
  9686. this.unbindAllAttributes();
  9687. this._gl = null;
  9688. //WebVR
  9689. this.disableVR();
  9690. // Events
  9691. window.removeEventListener("blur", this._onBlur);
  9692. window.removeEventListener("focus", this._onFocus);
  9693. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  9694. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  9695. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  9696. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  9697. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  9698. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  9699. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  9700. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  9701. // Remove from Instances
  9702. var index = Engine.Instances.indexOf(this);
  9703. if (index >= 0) {
  9704. Engine.Instances.splice(index, 1);
  9705. }
  9706. };
  9707. // Loading screen
  9708. Engine.prototype.displayLoadingUI = function () {
  9709. this.loadingScreen.displayLoadingUI();
  9710. };
  9711. Engine.prototype.hideLoadingUI = function () {
  9712. this.loadingScreen.hideLoadingUI();
  9713. };
  9714. Object.defineProperty(Engine.prototype, "loadingScreen", {
  9715. get: function () {
  9716. if (!this._loadingScreen)
  9717. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  9718. return this._loadingScreen;
  9719. },
  9720. set: function (loadingScreen) {
  9721. this._loadingScreen = loadingScreen;
  9722. },
  9723. enumerable: true,
  9724. configurable: true
  9725. });
  9726. Object.defineProperty(Engine.prototype, "loadingUIText", {
  9727. set: function (text) {
  9728. this.loadingScreen.loadingUIText = text;
  9729. },
  9730. enumerable: true,
  9731. configurable: true
  9732. });
  9733. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  9734. set: function (color) {
  9735. this.loadingScreen.loadingUIBackgroundColor = color;
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Engine.prototype.attachContextLostEvent = function (callback) {
  9741. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  9742. };
  9743. Engine.prototype.attachContextRestoredEvent = function (callback) {
  9744. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  9745. };
  9746. Engine.prototype.getVertexShaderSource = function (program) {
  9747. var shaders = this._gl.getAttachedShaders(program);
  9748. return this._gl.getShaderSource(shaders[0]);
  9749. };
  9750. Engine.prototype.getFragmentShaderSource = function (program) {
  9751. var shaders = this._gl.getAttachedShaders(program);
  9752. return this._gl.getShaderSource(shaders[1]);
  9753. };
  9754. // FPS
  9755. Engine.prototype.getFps = function () {
  9756. return this.fps;
  9757. };
  9758. Engine.prototype.getDeltaTime = function () {
  9759. return this.deltaTime;
  9760. };
  9761. Engine.prototype._measureFps = function () {
  9762. this.previousFramesDuration.push(BABYLON.Tools.Now);
  9763. var length = this.previousFramesDuration.length;
  9764. if (length >= 2) {
  9765. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  9766. }
  9767. if (length >= this.fpsRange) {
  9768. if (length > this.fpsRange) {
  9769. this.previousFramesDuration.splice(0, 1);
  9770. length = this.previousFramesDuration.length;
  9771. }
  9772. var sum = 0;
  9773. for (var id = 0; id < length - 1; id++) {
  9774. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9775. }
  9776. this.fps = 1000.0 / (sum / (length - 1));
  9777. }
  9778. };
  9779. Engine.prototype._canRenderToFloatFramebuffer = function () {
  9780. if (this._webGLVersion > 1) {
  9781. return this._caps.colorBufferFloat;
  9782. }
  9783. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  9784. };
  9785. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  9786. if (this._webGLVersion > 1) {
  9787. return this._caps.colorBufferFloat;
  9788. }
  9789. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  9790. };
  9791. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9792. Engine.prototype._canRenderToFramebuffer = function (type) {
  9793. var gl = this._gl;
  9794. //clear existing errors
  9795. while (gl.getError() !== gl.NO_ERROR) { }
  9796. var successful = true;
  9797. var texture = gl.createTexture();
  9798. gl.bindTexture(gl.TEXTURE_2D, texture);
  9799. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9801. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9802. var fb = gl.createFramebuffer();
  9803. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9804. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9805. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9806. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  9807. successful = successful && (gl.getError() === gl.NO_ERROR);
  9808. //try render by clearing frame buffer's color buffer
  9809. if (successful) {
  9810. gl.clear(gl.COLOR_BUFFER_BIT);
  9811. successful = successful && (gl.getError() === gl.NO_ERROR);
  9812. }
  9813. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  9814. if (successful) {
  9815. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  9816. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9817. var readFormat = gl.RGBA;
  9818. var readType = gl.UNSIGNED_BYTE;
  9819. var buffer = new Uint8Array(4);
  9820. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  9821. successful = successful && (gl.getError() === gl.NO_ERROR);
  9822. }
  9823. //clean up
  9824. gl.deleteTexture(texture);
  9825. gl.deleteFramebuffer(fb);
  9826. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9827. //clear accumulated errors
  9828. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  9829. return successful;
  9830. };
  9831. Engine.prototype._getWebGLTextureType = function (type) {
  9832. if (type === Engine.TEXTURETYPE_FLOAT) {
  9833. return this._gl.FLOAT;
  9834. }
  9835. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9836. // Add Half Float Constant.
  9837. return Engine.HALF_FLOAT_OES;
  9838. }
  9839. return this._gl.UNSIGNED_BYTE;
  9840. };
  9841. ;
  9842. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  9843. if (this._webGLVersion === 1) {
  9844. return this._gl.RGBA;
  9845. }
  9846. if (type === Engine.TEXTURETYPE_FLOAT) {
  9847. return Engine.RGBA32F;
  9848. }
  9849. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9850. return Engine.RGBA16F;
  9851. }
  9852. return this._gl.RGBA;
  9853. };
  9854. ;
  9855. // Statics
  9856. Engine.isSupported = function () {
  9857. try {
  9858. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9859. if (navigator.isCocoonJS) {
  9860. return true;
  9861. }
  9862. var tempcanvas = document.createElement("canvas");
  9863. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9864. return gl != null && !!window.WebGLRenderingContext;
  9865. }
  9866. catch (e) {
  9867. return false;
  9868. }
  9869. };
  9870. return Engine;
  9871. }());
  9872. Engine.Instances = new Array();
  9873. // Const statics
  9874. Engine._ALPHA_DISABLE = 0;
  9875. Engine._ALPHA_ADD = 1;
  9876. Engine._ALPHA_COMBINE = 2;
  9877. Engine._ALPHA_SUBTRACT = 3;
  9878. Engine._ALPHA_MULTIPLY = 4;
  9879. Engine._ALPHA_MAXIMIZED = 5;
  9880. Engine._ALPHA_ONEONE = 6;
  9881. Engine._ALPHA_PREMULTIPLIED = 7;
  9882. Engine._DELAYLOADSTATE_NONE = 0;
  9883. Engine._DELAYLOADSTATE_LOADED = 1;
  9884. Engine._DELAYLOADSTATE_LOADING = 2;
  9885. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9886. Engine._TEXTUREFORMAT_ALPHA = 0;
  9887. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9888. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9889. Engine._TEXTUREFORMAT_RGB = 4;
  9890. Engine._TEXTUREFORMAT_RGBA = 5;
  9891. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9892. Engine._TEXTURETYPE_FLOAT = 1;
  9893. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9894. // Depht or Stencil test Constants.
  9895. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9896. 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.
  9897. 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.
  9898. 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.
  9899. 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.
  9900. 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.
  9901. 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.
  9902. 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.
  9903. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9904. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9905. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9906. // Stencil Actions Constants.
  9907. Engine._KEEP = 0x1E00;
  9908. Engine._REPLACE = 0x1E01;
  9909. Engine._INCR = 0x1E02;
  9910. Engine._DECR = 0x1E03;
  9911. Engine._INVERT = 0x150A;
  9912. Engine._INCR_WRAP = 0x8507;
  9913. Engine._DECR_WRAP = 0x8508;
  9914. // Updatable statics so stick with vars here
  9915. Engine.CollisionsEpsilon = 0.001;
  9916. Engine.CodeRepository = "src/";
  9917. Engine.ShadersRepository = "src/Shaders/";
  9918. BABYLON.Engine = Engine;
  9919. })(BABYLON || (BABYLON = {}));
  9920. //# sourceMappingURL=babylon.engine.js.map
  9921. /// <reference path="Tools\babylon.decorators.ts" />
  9922. var BABYLON;
  9923. (function (BABYLON) {
  9924. /**
  9925. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9926. */
  9927. var Node = (function () {
  9928. /**
  9929. * @constructor
  9930. * @param {string} name - the name and id to be given to this node
  9931. * @param {BABYLON.Scene} the scene this node will be added to
  9932. */
  9933. function Node(name, scene) {
  9934. this.state = "";
  9935. this.metadata = null;
  9936. this.doNotSerialize = false;
  9937. this.animations = new Array();
  9938. this._ranges = {};
  9939. this._childrenFlag = -1;
  9940. this._isEnabled = true;
  9941. this._isReady = true;
  9942. this._currentRenderId = -1;
  9943. this._parentRenderId = -1;
  9944. /**
  9945. * An event triggered when the mesh is disposed.
  9946. * @type {BABYLON.Observable}
  9947. */
  9948. this.onDisposeObservable = new BABYLON.Observable();
  9949. this.name = name;
  9950. this.id = name;
  9951. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  9952. this._initCache();
  9953. }
  9954. Object.defineProperty(Node.prototype, "parent", {
  9955. get: function () {
  9956. return this._parentNode;
  9957. },
  9958. set: function (parent) {
  9959. if (this._parentNode === parent) {
  9960. return;
  9961. }
  9962. if (this._parentNode) {
  9963. var index = this._parentNode._children.indexOf(this);
  9964. if (index !== -1) {
  9965. this._parentNode._children.splice(index, 1);
  9966. }
  9967. }
  9968. this._parentNode = parent;
  9969. if (this._parentNode) {
  9970. if (!this._parentNode._children) {
  9971. this._parentNode._children = new Array();
  9972. }
  9973. this._parentNode._children.push(this);
  9974. }
  9975. },
  9976. enumerable: true,
  9977. configurable: true
  9978. });
  9979. Node.prototype.getClassName = function () {
  9980. return "Node";
  9981. };
  9982. Object.defineProperty(Node.prototype, "onDispose", {
  9983. set: function (callback) {
  9984. if (this._onDisposeObserver) {
  9985. this.onDisposeObservable.remove(this._onDisposeObserver);
  9986. }
  9987. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9988. },
  9989. enumerable: true,
  9990. configurable: true
  9991. });
  9992. Node.prototype.getScene = function () {
  9993. return this._scene;
  9994. };
  9995. Node.prototype.getEngine = function () {
  9996. return this._scene.getEngine();
  9997. };
  9998. // override it in derived class
  9999. Node.prototype.getWorldMatrix = function () {
  10000. return BABYLON.Matrix.Identity();
  10001. };
  10002. // override it in derived class if you add new variables to the cache
  10003. // and call the parent class method
  10004. Node.prototype._initCache = function () {
  10005. this._cache = {};
  10006. this._cache.parent = undefined;
  10007. };
  10008. Node.prototype.updateCache = function (force) {
  10009. if (!force && this.isSynchronized())
  10010. return;
  10011. this._cache.parent = this.parent;
  10012. this._updateCache();
  10013. };
  10014. // override it in derived class if you add new variables to the cache
  10015. // and call the parent class method if !ignoreParentClass
  10016. Node.prototype._updateCache = function (ignoreParentClass) {
  10017. };
  10018. // override it in derived class if you add new variables to the cache
  10019. Node.prototype._isSynchronized = function () {
  10020. return true;
  10021. };
  10022. Node.prototype._markSyncedWithParent = function () {
  10023. this._parentRenderId = this.parent._currentRenderId;
  10024. };
  10025. Node.prototype.isSynchronizedWithParent = function () {
  10026. if (!this.parent) {
  10027. return true;
  10028. }
  10029. if (this._parentRenderId !== this.parent._currentRenderId) {
  10030. return false;
  10031. }
  10032. return this.parent.isSynchronized();
  10033. };
  10034. Node.prototype.isSynchronized = function (updateCache) {
  10035. var check = this.hasNewParent();
  10036. check = check || !this.isSynchronizedWithParent();
  10037. check = check || !this._isSynchronized();
  10038. if (updateCache)
  10039. this.updateCache(true);
  10040. return !check;
  10041. };
  10042. Node.prototype.hasNewParent = function (update) {
  10043. if (this._cache.parent === this.parent)
  10044. return false;
  10045. if (update)
  10046. this._cache.parent = this.parent;
  10047. return true;
  10048. };
  10049. /**
  10050. * Is this node ready to be used/rendered
  10051. * @return {boolean} is it ready
  10052. */
  10053. Node.prototype.isReady = function () {
  10054. return this._isReady;
  10055. };
  10056. /**
  10057. * Is this node enabled.
  10058. * If the node has a parent and is enabled, the parent will be inspected as well.
  10059. * @return {boolean} whether this node (and its parent) is enabled.
  10060. * @see setEnabled
  10061. */
  10062. Node.prototype.isEnabled = function () {
  10063. if (!this._isEnabled) {
  10064. return false;
  10065. }
  10066. if (this.parent) {
  10067. return this.parent.isEnabled();
  10068. }
  10069. return true;
  10070. };
  10071. /**
  10072. * Set the enabled state of this node.
  10073. * @param {boolean} value - the new enabled state
  10074. * @see isEnabled
  10075. */
  10076. Node.prototype.setEnabled = function (value) {
  10077. this._isEnabled = value;
  10078. };
  10079. /**
  10080. * Is this node a descendant of the given node.
  10081. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10082. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10083. * @see parent
  10084. */
  10085. Node.prototype.isDescendantOf = function (ancestor) {
  10086. if (this.parent) {
  10087. if (this.parent === ancestor) {
  10088. return true;
  10089. }
  10090. return this.parent.isDescendantOf(ancestor);
  10091. }
  10092. return false;
  10093. };
  10094. /**
  10095. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10096. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10097. * @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.
  10098. * @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.
  10099. */
  10100. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10101. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10102. if (!this._children) {
  10103. return;
  10104. }
  10105. for (var index = 0; index < this._children.length; index++) {
  10106. var item = this._children[index];
  10107. if (!predicate || predicate(item)) {
  10108. results.push(item);
  10109. }
  10110. if (!directDescendantsOnly) {
  10111. item._getDescendants(results, false, predicate);
  10112. }
  10113. }
  10114. };
  10115. /**
  10116. * Will return all nodes that have this node as ascendant.
  10117. * @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.
  10118. * @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.
  10119. * @return {BABYLON.Node[]} all children nodes of all types.
  10120. */
  10121. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10122. var results = [];
  10123. this._getDescendants(results, directDescendantsOnly, predicate);
  10124. return results;
  10125. };
  10126. /**
  10127. * Get all child-meshes of this node.
  10128. */
  10129. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10130. var results = [];
  10131. this._getDescendants(results, directDecendantsOnly, function (node) {
  10132. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10133. });
  10134. return results;
  10135. };
  10136. /**
  10137. * Get all direct children of this node.
  10138. */
  10139. Node.prototype.getChildren = function (predicate) {
  10140. return this.getDescendants(true, predicate);
  10141. };
  10142. Node.prototype._setReady = function (state) {
  10143. if (state === this._isReady) {
  10144. return;
  10145. }
  10146. if (!state) {
  10147. this._isReady = false;
  10148. return;
  10149. }
  10150. this._isReady = true;
  10151. if (this.onReady) {
  10152. this.onReady(this);
  10153. }
  10154. };
  10155. Node.prototype.getAnimationByName = function (name) {
  10156. for (var i = 0; i < this.animations.length; i++) {
  10157. var animation = this.animations[i];
  10158. if (animation.name === name) {
  10159. return animation;
  10160. }
  10161. }
  10162. return null;
  10163. };
  10164. Node.prototype.createAnimationRange = function (name, from, to) {
  10165. // check name not already in use
  10166. if (!this._ranges[name]) {
  10167. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10168. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10169. if (this.animations[i]) {
  10170. this.animations[i].createRange(name, from, to);
  10171. }
  10172. }
  10173. }
  10174. };
  10175. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10176. if (deleteFrames === void 0) { deleteFrames = true; }
  10177. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10178. if (this.animations[i]) {
  10179. this.animations[i].deleteRange(name, deleteFrames);
  10180. }
  10181. }
  10182. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10183. };
  10184. Node.prototype.getAnimationRange = function (name) {
  10185. return this._ranges[name];
  10186. };
  10187. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10188. var range = this.getAnimationRange(name);
  10189. if (!range) {
  10190. return null;
  10191. }
  10192. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10193. };
  10194. Node.prototype.serializeAnimationRanges = function () {
  10195. var serializationRanges = [];
  10196. for (var name in this._ranges) {
  10197. var range = {};
  10198. range.name = name;
  10199. range.from = this._ranges[name].from;
  10200. range.to = this._ranges[name].to;
  10201. serializationRanges.push(range);
  10202. }
  10203. return serializationRanges;
  10204. };
  10205. Node.prototype.dispose = function () {
  10206. this.parent = null;
  10207. // Callback
  10208. this.onDisposeObservable.notifyObservers(this);
  10209. this.onDisposeObservable.clear();
  10210. };
  10211. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10212. if (parsedNode.ranges) {
  10213. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10214. var data = parsedNode.ranges[index];
  10215. node.createAnimationRange(data.name, data.from, data.to);
  10216. }
  10217. }
  10218. };
  10219. return Node;
  10220. }());
  10221. __decorate([
  10222. BABYLON.serialize()
  10223. ], Node.prototype, "name", void 0);
  10224. __decorate([
  10225. BABYLON.serialize()
  10226. ], Node.prototype, "id", void 0);
  10227. __decorate([
  10228. BABYLON.serialize()
  10229. ], Node.prototype, "uniqueId", void 0);
  10230. __decorate([
  10231. BABYLON.serialize()
  10232. ], Node.prototype, "state", void 0);
  10233. __decorate([
  10234. BABYLON.serialize()
  10235. ], Node.prototype, "metadata", void 0);
  10236. BABYLON.Node = Node;
  10237. })(BABYLON || (BABYLON = {}));
  10238. //# sourceMappingURL=babylon.node.js.map
  10239. var BABYLON;
  10240. (function (BABYLON) {
  10241. var BoundingSphere = (function () {
  10242. function BoundingSphere(minimum, maximum) {
  10243. this.minimum = minimum;
  10244. this.maximum = maximum;
  10245. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10246. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10247. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10248. this.radius = distance * 0.5;
  10249. this.centerWorld = BABYLON.Vector3.Zero();
  10250. this._update(BABYLON.Matrix.Identity());
  10251. }
  10252. // Methods
  10253. BoundingSphere.prototype._update = function (world) {
  10254. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10255. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10256. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10257. };
  10258. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10259. for (var i = 0; i < 6; i++) {
  10260. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10261. return false;
  10262. }
  10263. return true;
  10264. };
  10265. BoundingSphere.prototype.intersectsPoint = function (point) {
  10266. var x = this.centerWorld.x - point.x;
  10267. var y = this.centerWorld.y - point.y;
  10268. var z = this.centerWorld.z - point.z;
  10269. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10270. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10271. return false;
  10272. return true;
  10273. };
  10274. // Statics
  10275. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10276. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10277. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10278. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10279. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10280. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10281. return false;
  10282. return true;
  10283. };
  10284. return BoundingSphere;
  10285. }());
  10286. BABYLON.BoundingSphere = BoundingSphere;
  10287. })(BABYLON || (BABYLON = {}));
  10288. //# sourceMappingURL=babylon.boundingSphere.js.map
  10289. var BABYLON;
  10290. (function (BABYLON) {
  10291. var BoundingBox = (function () {
  10292. function BoundingBox(minimum, maximum) {
  10293. this.minimum = minimum;
  10294. this.maximum = maximum;
  10295. this.vectors = new Array();
  10296. this.vectorsWorld = new Array();
  10297. // Bounding vectors
  10298. this.vectors.push(this.minimum.clone());
  10299. this.vectors.push(this.maximum.clone());
  10300. this.vectors.push(this.minimum.clone());
  10301. this.vectors[2].x = this.maximum.x;
  10302. this.vectors.push(this.minimum.clone());
  10303. this.vectors[3].y = this.maximum.y;
  10304. this.vectors.push(this.minimum.clone());
  10305. this.vectors[4].z = this.maximum.z;
  10306. this.vectors.push(this.maximum.clone());
  10307. this.vectors[5].z = this.minimum.z;
  10308. this.vectors.push(this.maximum.clone());
  10309. this.vectors[6].x = this.minimum.x;
  10310. this.vectors.push(this.maximum.clone());
  10311. this.vectors[7].y = this.minimum.y;
  10312. // OBB
  10313. this.center = this.maximum.add(this.minimum).scale(0.5);
  10314. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10315. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10316. // World
  10317. for (var index = 0; index < this.vectors.length; index++) {
  10318. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10319. }
  10320. this.minimumWorld = BABYLON.Vector3.Zero();
  10321. this.maximumWorld = BABYLON.Vector3.Zero();
  10322. this.centerWorld = BABYLON.Vector3.Zero();
  10323. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10324. this._update(BABYLON.Matrix.Identity());
  10325. }
  10326. // Methods
  10327. BoundingBox.prototype.getWorldMatrix = function () {
  10328. return this._worldMatrix;
  10329. };
  10330. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10331. this._worldMatrix.copyFrom(matrix);
  10332. return this;
  10333. };
  10334. BoundingBox.prototype._update = function (world) {
  10335. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10336. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10337. for (var index = 0; index < this.vectors.length; index++) {
  10338. var v = this.vectorsWorld[index];
  10339. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10340. if (v.x < this.minimumWorld.x)
  10341. this.minimumWorld.x = v.x;
  10342. if (v.y < this.minimumWorld.y)
  10343. this.minimumWorld.y = v.y;
  10344. if (v.z < this.minimumWorld.z)
  10345. this.minimumWorld.z = v.z;
  10346. if (v.x > this.maximumWorld.x)
  10347. this.maximumWorld.x = v.x;
  10348. if (v.y > this.maximumWorld.y)
  10349. this.maximumWorld.y = v.y;
  10350. if (v.z > this.maximumWorld.z)
  10351. this.maximumWorld.z = v.z;
  10352. }
  10353. // Extend
  10354. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10355. this.extendSizeWorld.scaleInPlace(0.5);
  10356. // OBB
  10357. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10358. this.centerWorld.scaleInPlace(0.5);
  10359. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10360. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10361. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10362. this._worldMatrix = world;
  10363. };
  10364. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10365. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10366. };
  10367. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10368. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10369. };
  10370. BoundingBox.prototype.intersectsPoint = function (point) {
  10371. var delta = -BABYLON.Epsilon;
  10372. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10373. return false;
  10374. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10375. return false;
  10376. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10377. return false;
  10378. return true;
  10379. };
  10380. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10381. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10382. };
  10383. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10384. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10385. return false;
  10386. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10387. return false;
  10388. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10389. return false;
  10390. return true;
  10391. };
  10392. // Statics
  10393. BoundingBox.Intersects = function (box0, box1) {
  10394. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10395. return false;
  10396. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10397. return false;
  10398. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10399. return false;
  10400. return true;
  10401. };
  10402. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10403. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10404. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10405. return (num <= (sphereRadius * sphereRadius));
  10406. };
  10407. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10408. for (var p = 0; p < 6; p++) {
  10409. for (var i = 0; i < 8; i++) {
  10410. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10411. return false;
  10412. }
  10413. }
  10414. }
  10415. return true;
  10416. };
  10417. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10418. for (var p = 0; p < 6; p++) {
  10419. var inCount = 8;
  10420. for (var i = 0; i < 8; i++) {
  10421. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10422. --inCount;
  10423. }
  10424. else {
  10425. break;
  10426. }
  10427. }
  10428. if (inCount === 0)
  10429. return false;
  10430. }
  10431. return true;
  10432. };
  10433. return BoundingBox;
  10434. }());
  10435. BABYLON.BoundingBox = BoundingBox;
  10436. })(BABYLON || (BABYLON = {}));
  10437. //# sourceMappingURL=babylon.boundingBox.js.map
  10438. var BABYLON;
  10439. (function (BABYLON) {
  10440. var computeBoxExtents = function (axis, box) {
  10441. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  10442. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  10443. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  10444. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  10445. var r = r0 + r1 + r2;
  10446. return {
  10447. min: p - r,
  10448. max: p + r
  10449. };
  10450. };
  10451. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  10452. var axisOverlap = function (axis, box0, box1) {
  10453. var result0 = computeBoxExtents(axis, box0);
  10454. var result1 = computeBoxExtents(axis, box1);
  10455. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  10456. };
  10457. var BoundingInfo = (function () {
  10458. function BoundingInfo(minimum, maximum) {
  10459. this.minimum = minimum;
  10460. this.maximum = maximum;
  10461. this._isLocked = false;
  10462. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10463. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10464. }
  10465. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10466. get: function () {
  10467. return this._isLocked;
  10468. },
  10469. set: function (value) {
  10470. this._isLocked = value;
  10471. },
  10472. enumerable: true,
  10473. configurable: true
  10474. });
  10475. // Methods
  10476. BoundingInfo.prototype.update = function (world) {
  10477. if (this._isLocked) {
  10478. return;
  10479. }
  10480. this.boundingBox._update(world);
  10481. this.boundingSphere._update(world);
  10482. };
  10483. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10484. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10485. return false;
  10486. return this.boundingBox.isInFrustum(frustumPlanes);
  10487. };
  10488. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10489. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10490. };
  10491. BoundingInfo.prototype._checkCollision = function (collider) {
  10492. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10493. };
  10494. BoundingInfo.prototype.intersectsPoint = function (point) {
  10495. if (!this.boundingSphere.centerWorld) {
  10496. return false;
  10497. }
  10498. if (!this.boundingSphere.intersectsPoint(point)) {
  10499. return false;
  10500. }
  10501. if (!this.boundingBox.intersectsPoint(point)) {
  10502. return false;
  10503. }
  10504. return true;
  10505. };
  10506. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10507. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10508. return false;
  10509. }
  10510. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10511. return false;
  10512. }
  10513. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10514. return false;
  10515. }
  10516. if (!precise) {
  10517. return true;
  10518. }
  10519. var box0 = this.boundingBox;
  10520. var box1 = boundingInfo.boundingBox;
  10521. if (!axisOverlap(box0.directions[0], box0, box1))
  10522. return false;
  10523. if (!axisOverlap(box0.directions[1], box0, box1))
  10524. return false;
  10525. if (!axisOverlap(box0.directions[2], box0, box1))
  10526. return false;
  10527. if (!axisOverlap(box1.directions[0], box0, box1))
  10528. return false;
  10529. if (!axisOverlap(box1.directions[1], box0, box1))
  10530. return false;
  10531. if (!axisOverlap(box1.directions[2], box0, box1))
  10532. return false;
  10533. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  10534. return false;
  10535. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  10536. return false;
  10537. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  10538. return false;
  10539. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  10540. return false;
  10541. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  10542. return false;
  10543. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  10544. return false;
  10545. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  10546. return false;
  10547. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  10548. return false;
  10549. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  10550. return false;
  10551. return true;
  10552. };
  10553. return BoundingInfo;
  10554. }());
  10555. BABYLON.BoundingInfo = BoundingInfo;
  10556. })(BABYLON || (BABYLON = {}));
  10557. //# sourceMappingURL=babylon.boundingInfo.js.map
  10558. var BABYLON;
  10559. (function (BABYLON) {
  10560. var AbstractMesh = (function (_super) {
  10561. __extends(AbstractMesh, _super);
  10562. // Constructor
  10563. function AbstractMesh(name, scene) {
  10564. var _this = _super.call(this, name, scene) || this;
  10565. _this._facetNb = 0; // facet number
  10566. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  10567. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  10568. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  10569. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  10570. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  10571. _this._subDiv = {
  10572. max: 1,
  10573. X: 1,
  10574. Y: 1,
  10575. Z: 1
  10576. };
  10577. // Events
  10578. /**
  10579. * An event triggered when this mesh collides with another one
  10580. * @type {BABYLON.Observable}
  10581. */
  10582. _this.onCollideObservable = new BABYLON.Observable();
  10583. /**
  10584. * An event triggered when the collision's position changes
  10585. * @type {BABYLON.Observable}
  10586. */
  10587. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10588. /**
  10589. * An event triggered after the world matrix is updated
  10590. * @type {BABYLON.Observable}
  10591. */
  10592. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10593. // Properties
  10594. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10595. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10596. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10597. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  10598. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10599. _this.visibility = 1.0;
  10600. _this.alphaIndex = Number.MAX_VALUE;
  10601. _this.infiniteDistance = false;
  10602. _this.isVisible = true;
  10603. _this.isPickable = true;
  10604. _this.showBoundingBox = false;
  10605. _this.showSubMeshesBoundingBox = false;
  10606. _this.isBlocker = false;
  10607. _this.renderingGroupId = 0;
  10608. _this._receiveShadows = false;
  10609. _this.renderOutline = false;
  10610. _this.outlineColor = BABYLON.Color3.Red();
  10611. _this.outlineWidth = 0.02;
  10612. _this.renderOverlay = false;
  10613. _this.overlayColor = BABYLON.Color3.Red();
  10614. _this.overlayAlpha = 0.5;
  10615. _this._hasVertexAlpha = false;
  10616. _this._useVertexColors = true;
  10617. _this._computeBonesUsingShaders = true;
  10618. _this._numBoneInfluencers = 4;
  10619. _this._applyFog = true;
  10620. _this.scalingDeterminant = 1;
  10621. _this.useOctreeForRenderingSelection = true;
  10622. _this.useOctreeForPicking = true;
  10623. _this.useOctreeForCollisions = true;
  10624. _this.layerMask = 0x0FFFFFFF;
  10625. /**
  10626. * True if the mesh must be rendered in any case.
  10627. */
  10628. _this.alwaysSelectAsActiveMesh = false;
  10629. // Collisions
  10630. _this._checkCollisions = false;
  10631. _this._collisionMask = -1;
  10632. _this._collisionGroup = -1;
  10633. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10634. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10635. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10636. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10637. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10638. // Edges
  10639. _this.edgesWidth = 1;
  10640. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10641. // Cache
  10642. _this._localWorld = BABYLON.Matrix.Zero();
  10643. _this._worldMatrix = BABYLON.Matrix.Zero();
  10644. _this._absolutePosition = BABYLON.Vector3.Zero();
  10645. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10646. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10647. _this._isDirty = false;
  10648. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10649. _this._isDisposed = false;
  10650. _this._renderId = 0;
  10651. _this._intersectionsInProgress = new Array();
  10652. _this._isWorldMatrixFrozen = false;
  10653. _this._unIndexed = false;
  10654. _this._lightSources = new Array();
  10655. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10656. if (collidedMesh === void 0) { collidedMesh = null; }
  10657. //TODO move this to the collision coordinator!
  10658. if (_this.getScene().workerCollisions)
  10659. newPosition.multiplyInPlace(_this._collider.radius);
  10660. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10661. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10662. _this.position.addInPlace(_this._diffPositionForCollisions);
  10663. }
  10664. if (collidedMesh) {
  10665. _this.onCollideObservable.notifyObservers(collidedMesh);
  10666. }
  10667. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10668. };
  10669. _this.getScene().addMesh(_this);
  10670. _this._resyncLightSources();
  10671. return _this;
  10672. }
  10673. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10674. get: function () {
  10675. return AbstractMesh._BILLBOARDMODE_NONE;
  10676. },
  10677. enumerable: true,
  10678. configurable: true
  10679. });
  10680. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10681. get: function () {
  10682. return AbstractMesh._BILLBOARDMODE_X;
  10683. },
  10684. enumerable: true,
  10685. configurable: true
  10686. });
  10687. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10688. get: function () {
  10689. return AbstractMesh._BILLBOARDMODE_Y;
  10690. },
  10691. enumerable: true,
  10692. configurable: true
  10693. });
  10694. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10695. get: function () {
  10696. return AbstractMesh._BILLBOARDMODE_Z;
  10697. },
  10698. enumerable: true,
  10699. configurable: true
  10700. });
  10701. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10702. get: function () {
  10703. return AbstractMesh._BILLBOARDMODE_ALL;
  10704. },
  10705. enumerable: true,
  10706. configurable: true
  10707. });
  10708. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  10709. /**
  10710. * Read-only : the number of facets in the mesh
  10711. */
  10712. get: function () {
  10713. return this._facetNb;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  10719. /**
  10720. * The number (integer) of subdivisions per axis in the partioning space
  10721. */
  10722. get: function () {
  10723. return this._partitioningSubdivisions;
  10724. },
  10725. set: function (nb) {
  10726. this._partitioningSubdivisions = nb;
  10727. },
  10728. enumerable: true,
  10729. configurable: true
  10730. });
  10731. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  10732. /**
  10733. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  10734. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  10735. */
  10736. get: function () {
  10737. return this._partitioningBBoxRatio;
  10738. },
  10739. set: function (ratio) {
  10740. this._partitioningBBoxRatio = ratio;
  10741. },
  10742. enumerable: true,
  10743. configurable: true
  10744. });
  10745. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  10746. /**
  10747. * Read-only boolean : is the feature facetData enabled ?
  10748. */
  10749. get: function () {
  10750. return this._facetDataEnabled;
  10751. },
  10752. enumerable: true,
  10753. configurable: true
  10754. });
  10755. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10756. set: function (callback) {
  10757. if (this._onCollideObserver) {
  10758. this.onCollideObservable.remove(this._onCollideObserver);
  10759. }
  10760. this._onCollideObserver = this.onCollideObservable.add(callback);
  10761. },
  10762. enumerable: true,
  10763. configurable: true
  10764. });
  10765. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10766. set: function (callback) {
  10767. if (this._onCollisionPositionChangeObserver) {
  10768. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10769. }
  10770. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10771. },
  10772. enumerable: true,
  10773. configurable: true
  10774. });
  10775. Object.defineProperty(AbstractMesh.prototype, "material", {
  10776. get: function () {
  10777. return this._material;
  10778. },
  10779. set: function (value) {
  10780. if (this._material === value) {
  10781. return;
  10782. }
  10783. this._material = value;
  10784. if (!this.subMeshes) {
  10785. return;
  10786. }
  10787. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  10788. var subMesh = _a[_i];
  10789. subMesh.setEffect(null);
  10790. }
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  10796. get: function () {
  10797. return this._receiveShadows;
  10798. },
  10799. set: function (value) {
  10800. if (this._receiveShadows === value) {
  10801. return;
  10802. }
  10803. this._receiveShadows = value;
  10804. this._markSubMeshesAsLightDirty();
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  10810. get: function () {
  10811. return this._hasVertexAlpha;
  10812. },
  10813. set: function (value) {
  10814. if (this._hasVertexAlpha === value) {
  10815. return;
  10816. }
  10817. this._hasVertexAlpha = value;
  10818. this._markSubMeshesAsAttributesDirty();
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  10824. get: function () {
  10825. return this._useVertexColors;
  10826. },
  10827. set: function (value) {
  10828. if (this._useVertexColors === value) {
  10829. return;
  10830. }
  10831. this._useVertexColors = value;
  10832. this._markSubMeshesAsAttributesDirty();
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  10838. get: function () {
  10839. return this._computeBonesUsingShaders;
  10840. },
  10841. set: function (value) {
  10842. if (this._computeBonesUsingShaders === value) {
  10843. return;
  10844. }
  10845. this._computeBonesUsingShaders = value;
  10846. this._markSubMeshesAsAttributesDirty();
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  10852. get: function () {
  10853. return this._numBoneInfluencers;
  10854. },
  10855. set: function (value) {
  10856. if (this._numBoneInfluencers === value) {
  10857. return;
  10858. }
  10859. this._numBoneInfluencers = value;
  10860. this._markSubMeshesAsAttributesDirty();
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  10866. get: function () {
  10867. return this._applyFog;
  10868. },
  10869. set: function (value) {
  10870. if (this._applyFog === value) {
  10871. return;
  10872. }
  10873. this._applyFog = value;
  10874. this._markSubMeshesAsMiscDirty();
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  10880. get: function () {
  10881. return this._collisionMask;
  10882. },
  10883. set: function (mask) {
  10884. this._collisionMask = !isNaN(mask) ? mask : -1;
  10885. },
  10886. enumerable: true,
  10887. configurable: true
  10888. });
  10889. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  10890. get: function () {
  10891. return this._collisionGroup;
  10892. },
  10893. set: function (mask) {
  10894. this._collisionGroup = !isNaN(mask) ? mask : -1;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10900. get: function () {
  10901. return this._skeleton;
  10902. },
  10903. set: function (value) {
  10904. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10905. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10906. }
  10907. if (value && value.needInitialSkinMatrix) {
  10908. value._registerMeshWithPoseMatrix(this);
  10909. }
  10910. this._skeleton = value;
  10911. if (!this._skeleton) {
  10912. this._bonesTransformMatrices = null;
  10913. }
  10914. this._markSubMeshesAsAttributesDirty();
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. /**
  10920. * Returns the string "AbstractMesh"
  10921. */
  10922. AbstractMesh.prototype.getClassName = function () {
  10923. return "AbstractMesh";
  10924. };
  10925. /**
  10926. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10927. */
  10928. AbstractMesh.prototype.toString = function (fullDetails) {
  10929. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10930. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10931. if (this._skeleton) {
  10932. ret += ", skeleton: " + this._skeleton.name;
  10933. }
  10934. if (fullDetails) {
  10935. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10936. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10937. }
  10938. return ret;
  10939. };
  10940. AbstractMesh.prototype._resyncLightSources = function () {
  10941. this._lightSources.length = 0;
  10942. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  10943. var light = _a[_i];
  10944. if (!light.isEnabled()) {
  10945. continue;
  10946. }
  10947. if (light.canAffectMesh(this)) {
  10948. this._lightSources.push(light);
  10949. }
  10950. }
  10951. this._markSubMeshesAsLightDirty();
  10952. };
  10953. AbstractMesh.prototype._resyncLighSource = function (light) {
  10954. var isIn = light.isEnabled() && light.canAffectMesh(this);
  10955. var index = this._lightSources.indexOf(light);
  10956. if (index === -1) {
  10957. if (!isIn) {
  10958. return;
  10959. }
  10960. this._lightSources.push(light);
  10961. }
  10962. else {
  10963. if (isIn) {
  10964. return;
  10965. }
  10966. this._lightSources.splice(index, 1);
  10967. }
  10968. this._markSubMeshesAsLightDirty();
  10969. };
  10970. AbstractMesh.prototype._removeLightSource = function (light) {
  10971. var index = this._lightSources.indexOf(light);
  10972. if (index === -1) {
  10973. return;
  10974. }
  10975. this._lightSources.splice(index, 1);
  10976. };
  10977. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  10978. if (!this.subMeshes) {
  10979. return;
  10980. }
  10981. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  10982. var subMesh = _a[_i];
  10983. if (subMesh._materialDefines) {
  10984. func(subMesh._materialDefines);
  10985. }
  10986. }
  10987. };
  10988. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  10989. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  10990. };
  10991. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  10992. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  10993. };
  10994. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  10995. if (!this.subMeshes) {
  10996. return;
  10997. }
  10998. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  10999. var subMesh = _a[_i];
  11000. var material = subMesh.getMaterial();
  11001. if (material) {
  11002. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11003. }
  11004. }
  11005. };
  11006. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11007. /**
  11008. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11009. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11010. * Default : (0.0, 0.0, 0.0)
  11011. */
  11012. get: function () {
  11013. return this._rotation;
  11014. },
  11015. set: function (newRotation) {
  11016. this._rotation = newRotation;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11022. /**
  11023. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11024. * Default : (1.0, 1.0, 1.0)
  11025. */
  11026. get: function () {
  11027. return this._scaling;
  11028. },
  11029. set: function (newScaling) {
  11030. this._scaling = newScaling;
  11031. if (this.physicsImpostor) {
  11032. this.physicsImpostor.forceUpdate();
  11033. }
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11039. /**
  11040. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11041. * It's null by default.
  11042. * 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)
  11043. */
  11044. get: function () {
  11045. return this._rotationQuaternion;
  11046. },
  11047. set: function (quaternion) {
  11048. this._rotationQuaternion = quaternion;
  11049. //reset the rotation vector.
  11050. if (quaternion && this.rotation.length()) {
  11051. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11052. }
  11053. },
  11054. enumerable: true,
  11055. configurable: true
  11056. });
  11057. // Methods
  11058. /**
  11059. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11060. * Returns the AbstractMesh.
  11061. */
  11062. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11063. this._poseMatrix.copyFrom(matrix);
  11064. return this;
  11065. };
  11066. /**
  11067. * Returns the mesh Pose matrix.
  11068. * Returned object : Matrix
  11069. */
  11070. AbstractMesh.prototype.getPoseMatrix = function () {
  11071. return this._poseMatrix;
  11072. };
  11073. /**
  11074. * Disables the mesh edger rendering mode.
  11075. * Returns the AbstractMesh.
  11076. */
  11077. AbstractMesh.prototype.disableEdgesRendering = function () {
  11078. if (this._edgesRenderer !== undefined) {
  11079. this._edgesRenderer.dispose();
  11080. this._edgesRenderer = undefined;
  11081. }
  11082. return this;
  11083. };
  11084. /**
  11085. * Enables the edge rendering mode on the mesh.
  11086. * This mode makes the mesh edges visible.
  11087. * Returns the AbstractMesh.
  11088. */
  11089. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11090. if (epsilon === void 0) { epsilon = 0.95; }
  11091. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11092. this.disableEdgesRendering();
  11093. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11094. return this;
  11095. };
  11096. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11097. /**
  11098. * Returns true if the mesh is blocked. Used by the class Mesh.
  11099. * Returns the boolean `false` by default.
  11100. */
  11101. get: function () {
  11102. return false;
  11103. },
  11104. enumerable: true,
  11105. configurable: true
  11106. });
  11107. /**
  11108. * Returns the mesh itself by default, used by the class Mesh.
  11109. * Returned type : AbstractMesh
  11110. */
  11111. AbstractMesh.prototype.getLOD = function (camera) {
  11112. return this;
  11113. };
  11114. /**
  11115. * Returns 0 by default, used by the class Mesh.
  11116. * Returns an integer.
  11117. */
  11118. AbstractMesh.prototype.getTotalVertices = function () {
  11119. return 0;
  11120. };
  11121. /**
  11122. * Returns null by default, used by the class Mesh.
  11123. * Returned type : integer array
  11124. */
  11125. AbstractMesh.prototype.getIndices = function () {
  11126. return null;
  11127. };
  11128. /**
  11129. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11130. * Returned type : float array or Float32Array
  11131. */
  11132. AbstractMesh.prototype.getVerticesData = function (kind) {
  11133. return null;
  11134. };
  11135. /**
  11136. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11137. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11138. * The `data` are either a numeric array either a Float32Array.
  11139. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11140. * 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).
  11141. * Note that a new underlying VertexBuffer object is created each call.
  11142. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11143. *
  11144. * Possible `kind` values :
  11145. * - BABYLON.VertexBuffer.PositionKind
  11146. * - BABYLON.VertexBuffer.UVKind
  11147. * - BABYLON.VertexBuffer.UV2Kind
  11148. * - BABYLON.VertexBuffer.UV3Kind
  11149. * - BABYLON.VertexBuffer.UV4Kind
  11150. * - BABYLON.VertexBuffer.UV5Kind
  11151. * - BABYLON.VertexBuffer.UV6Kind
  11152. * - BABYLON.VertexBuffer.ColorKind
  11153. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11154. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11155. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11156. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11157. *
  11158. * Returns the Mesh.
  11159. */
  11160. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11161. return null;
  11162. };
  11163. /**
  11164. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11165. * If the mesh has no geometry, it is simply returned as it is.
  11166. * The `data` are either a numeric array either a Float32Array.
  11167. * No new underlying VertexBuffer object is created.
  11168. * 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.
  11169. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11170. *
  11171. * Possible `kind` values :
  11172. * - BABYLON.VertexBuffer.PositionKind
  11173. * - BABYLON.VertexBuffer.UVKind
  11174. * - BABYLON.VertexBuffer.UV2Kind
  11175. * - BABYLON.VertexBuffer.UV3Kind
  11176. * - BABYLON.VertexBuffer.UV4Kind
  11177. * - BABYLON.VertexBuffer.UV5Kind
  11178. * - BABYLON.VertexBuffer.UV6Kind
  11179. * - BABYLON.VertexBuffer.ColorKind
  11180. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11181. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11182. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11183. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11184. *
  11185. * Returns the Mesh.
  11186. */
  11187. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11188. return null;
  11189. };
  11190. /**
  11191. * Sets the mesh indices.
  11192. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11193. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11194. * This method creates a new index buffer each call.
  11195. * Returns the Mesh.
  11196. */
  11197. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11198. return null;
  11199. };
  11200. /** Returns false by default, used by the class Mesh.
  11201. * Returns a boolean
  11202. */
  11203. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11204. return false;
  11205. };
  11206. /**
  11207. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11208. * Returns a BoundingInfo
  11209. */
  11210. AbstractMesh.prototype.getBoundingInfo = function () {
  11211. if (this._masterMesh) {
  11212. return this._masterMesh.getBoundingInfo();
  11213. }
  11214. if (!this._boundingInfo) {
  11215. this._updateBoundingInfo();
  11216. }
  11217. return this._boundingInfo;
  11218. };
  11219. /**
  11220. * Sets a mesh new object BoundingInfo.
  11221. * Returns the AbstractMesh.
  11222. */
  11223. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11224. this._boundingInfo = boundingInfo;
  11225. return this;
  11226. };
  11227. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11228. get: function () {
  11229. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11230. },
  11231. enumerable: true,
  11232. configurable: true
  11233. });
  11234. AbstractMesh.prototype._preActivate = function () {
  11235. };
  11236. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11237. };
  11238. AbstractMesh.prototype._activate = function (renderId) {
  11239. this._renderId = renderId;
  11240. };
  11241. /**
  11242. * Returns the last update of the World matrix
  11243. * Returns a Matrix.
  11244. */
  11245. AbstractMesh.prototype.getWorldMatrix = function () {
  11246. if (this._masterMesh) {
  11247. return this._masterMesh.getWorldMatrix();
  11248. }
  11249. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11250. this.computeWorldMatrix();
  11251. }
  11252. return this._worldMatrix;
  11253. };
  11254. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11255. /**
  11256. * Returns directly the last state of the mesh World matrix.
  11257. * A Matrix is returned.
  11258. */
  11259. get: function () {
  11260. return this._worldMatrix;
  11261. },
  11262. enumerable: true,
  11263. configurable: true
  11264. });
  11265. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11266. /**
  11267. * Returns the current mesh absolute position.
  11268. * Retuns a Vector3.
  11269. */
  11270. get: function () {
  11271. return this._absolutePosition;
  11272. },
  11273. enumerable: true,
  11274. configurable: true
  11275. });
  11276. /**
  11277. * Prevents the World matrix to be computed any longer.
  11278. * Returns the AbstractMesh.
  11279. */
  11280. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11281. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11282. this.computeWorldMatrix(true);
  11283. this._isWorldMatrixFrozen = true;
  11284. return this;
  11285. };
  11286. /**
  11287. * Allows back the World matrix computation.
  11288. * Returns the AbstractMesh.
  11289. */
  11290. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11291. this._isWorldMatrixFrozen = false;
  11292. this.computeWorldMatrix(true);
  11293. return this;
  11294. };
  11295. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11296. /**
  11297. * True if the World matrix has been frozen.
  11298. * Returns a boolean.
  11299. */
  11300. get: function () {
  11301. return this._isWorldMatrixFrozen;
  11302. },
  11303. enumerable: true,
  11304. configurable: true
  11305. });
  11306. /**
  11307. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11308. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11309. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11310. * The passed axis is also normalized.
  11311. * Returns the AbstractMesh.
  11312. */
  11313. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11314. axis.normalize();
  11315. if (!this.rotationQuaternion) {
  11316. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11317. this.rotation = BABYLON.Vector3.Zero();
  11318. }
  11319. var rotationQuaternion;
  11320. if (!space || space === BABYLON.Space.LOCAL) {
  11321. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11322. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11323. }
  11324. else {
  11325. if (this.parent) {
  11326. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11327. invertParentWorldMatrix.invert();
  11328. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11329. }
  11330. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11331. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11332. }
  11333. return this;
  11334. };
  11335. /**
  11336. * Translates the mesh along the axis vector for the passed distance in the given space.
  11337. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11338. * Returns the AbstractMesh.
  11339. */
  11340. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11341. var displacementVector = axis.scale(distance);
  11342. if (!space || space === BABYLON.Space.LOCAL) {
  11343. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11344. this.setPositionWithLocalVector(tempV3);
  11345. }
  11346. else {
  11347. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11348. }
  11349. return this;
  11350. };
  11351. /**
  11352. * Adds a rotation step to the mesh current rotation.
  11353. * x, y, z are Euler angles expressed in radians.
  11354. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11355. * This means this rotation is made in the mesh local space only.
  11356. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11357. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11358. * ```javascript
  11359. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11360. * ```
  11361. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11362. * 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.
  11363. * Returns the AbstractMesh.
  11364. */
  11365. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11366. var rotationQuaternion;
  11367. if (this.rotationQuaternion) {
  11368. rotationQuaternion = this.rotationQuaternion;
  11369. }
  11370. else {
  11371. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11372. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11373. }
  11374. var accumulation = BABYLON.Tmp.Quaternion[0];
  11375. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11376. rotationQuaternion.multiplyInPlace(accumulation);
  11377. if (!this.rotationQuaternion) {
  11378. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11379. }
  11380. return this;
  11381. };
  11382. /**
  11383. * Retuns the mesh absolute position in the World.
  11384. * Returns a Vector3.
  11385. */
  11386. AbstractMesh.prototype.getAbsolutePosition = function () {
  11387. this.computeWorldMatrix();
  11388. return this._absolutePosition;
  11389. };
  11390. /**
  11391. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11392. * Returns the AbstractMesh.
  11393. */
  11394. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11395. if (!absolutePosition) {
  11396. return;
  11397. }
  11398. var absolutePositionX;
  11399. var absolutePositionY;
  11400. var absolutePositionZ;
  11401. if (absolutePosition.x === undefined) {
  11402. if (arguments.length < 3) {
  11403. return;
  11404. }
  11405. absolutePositionX = arguments[0];
  11406. absolutePositionY = arguments[1];
  11407. absolutePositionZ = arguments[2];
  11408. }
  11409. else {
  11410. absolutePositionX = absolutePosition.x;
  11411. absolutePositionY = absolutePosition.y;
  11412. absolutePositionZ = absolutePosition.z;
  11413. }
  11414. if (this.parent) {
  11415. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11416. invertParentWorldMatrix.invert();
  11417. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11418. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11419. }
  11420. else {
  11421. this.position.x = absolutePositionX;
  11422. this.position.y = absolutePositionY;
  11423. this.position.z = absolutePositionZ;
  11424. }
  11425. return this;
  11426. };
  11427. // ================================== Point of View Movement =================================
  11428. /**
  11429. * Perform relative position change from the point of view of behind the front of the mesh.
  11430. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11431. * Supports definition of mesh facing forward or backward.
  11432. * @param {number} amountRight
  11433. * @param {number} amountUp
  11434. * @param {number} amountForward
  11435. *
  11436. * Returns the AbstractMesh.
  11437. */
  11438. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  11439. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  11440. return this;
  11441. };
  11442. /**
  11443. * Calculate relative position change from the point of view of behind the front of the mesh.
  11444. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11445. * Supports definition of mesh facing forward or backward.
  11446. * @param {number} amountRight
  11447. * @param {number} amountUp
  11448. * @param {number} amountForward
  11449. *
  11450. * Returns a new Vector3.
  11451. */
  11452. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  11453. var rotMatrix = new BABYLON.Matrix();
  11454. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11455. rotQuaternion.toRotationMatrix(rotMatrix);
  11456. var translationDelta = BABYLON.Vector3.Zero();
  11457. var defForwardMult = this.definedFacingForward ? -1 : 1;
  11458. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  11459. return translationDelta;
  11460. };
  11461. // ================================== Point of View Rotation =================================
  11462. /**
  11463. * Perform relative rotation change from the point of view of behind the front of the mesh.
  11464. * Supports definition of mesh facing forward or backward.
  11465. * @param {number} flipBack
  11466. * @param {number} twirlClockwise
  11467. * @param {number} tiltRight
  11468. *
  11469. * Returns the AbstractMesh.
  11470. */
  11471. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11472. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  11473. return this;
  11474. };
  11475. /**
  11476. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  11477. * Supports definition of mesh facing forward or backward.
  11478. * @param {number} flipBack
  11479. * @param {number} twirlClockwise
  11480. * @param {number} tiltRight
  11481. *
  11482. * Returns a new Vector3.
  11483. */
  11484. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11485. var defForwardMult = this.definedFacingForward ? 1 : -1;
  11486. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  11487. };
  11488. /**
  11489. * Sets a new pivot matrix to the mesh.
  11490. * Returns the AbstractMesh.
  11491. */
  11492. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  11493. this._pivotMatrix = matrix;
  11494. this._cache.pivotMatrixUpdated = true;
  11495. return this;
  11496. };
  11497. /**
  11498. * Returns the mesh pivot matrix.
  11499. * Default : Identity.
  11500. * A Matrix is returned.
  11501. */
  11502. AbstractMesh.prototype.getPivotMatrix = function () {
  11503. return this._pivotMatrix;
  11504. };
  11505. AbstractMesh.prototype._isSynchronized = function () {
  11506. if (this._isDirty) {
  11507. return false;
  11508. }
  11509. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  11510. return false;
  11511. if (this._cache.pivotMatrixUpdated) {
  11512. return false;
  11513. }
  11514. if (this.infiniteDistance) {
  11515. return false;
  11516. }
  11517. if (!this._cache.position.equals(this.position))
  11518. return false;
  11519. if (this.rotationQuaternion) {
  11520. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  11521. return false;
  11522. }
  11523. if (!this._cache.rotation.equals(this.rotation))
  11524. return false;
  11525. if (!this._cache.scaling.equals(this.scaling))
  11526. return false;
  11527. return true;
  11528. };
  11529. AbstractMesh.prototype._initCache = function () {
  11530. _super.prototype._initCache.call(this);
  11531. this._cache.localMatrixUpdated = false;
  11532. this._cache.position = BABYLON.Vector3.Zero();
  11533. this._cache.scaling = BABYLON.Vector3.Zero();
  11534. this._cache.rotation = BABYLON.Vector3.Zero();
  11535. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  11536. this._cache.billboardMode = -1;
  11537. };
  11538. AbstractMesh.prototype.markAsDirty = function (property) {
  11539. if (property === "rotation") {
  11540. this.rotationQuaternion = null;
  11541. }
  11542. this._currentRenderId = Number.MAX_VALUE;
  11543. this._isDirty = true;
  11544. return this;
  11545. };
  11546. /**
  11547. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  11548. * Returns the AbstractMesh.
  11549. */
  11550. AbstractMesh.prototype._updateBoundingInfo = function () {
  11551. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  11552. this._boundingInfo.update(this.worldMatrixFromCache);
  11553. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11554. return this;
  11555. };
  11556. /**
  11557. * Update a mesh's children BoundingInfo objects only.
  11558. * Returns the AbstractMesh.
  11559. */
  11560. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  11561. if (!this.subMeshes) {
  11562. return;
  11563. }
  11564. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  11565. var subMesh = this.subMeshes[subIndex];
  11566. if (!subMesh.IsGlobal) {
  11567. subMesh.updateBoundingInfo(matrix);
  11568. }
  11569. }
  11570. return this;
  11571. };
  11572. /**
  11573. * Computes the mesh World matrix and returns it.
  11574. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  11575. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  11576. * If the parameter `force`is set to `true`, the actual computation is done.
  11577. * Returns the mesh World Matrix.
  11578. */
  11579. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  11580. if (this._isWorldMatrixFrozen) {
  11581. return this._worldMatrix;
  11582. }
  11583. if (!force && this.isSynchronized(true)) {
  11584. this._currentRenderId = this.getScene().getRenderId();
  11585. return this._worldMatrix;
  11586. }
  11587. this._cache.position.copyFrom(this.position);
  11588. this._cache.scaling.copyFrom(this.scaling);
  11589. this._cache.pivotMatrixUpdated = false;
  11590. this._cache.billboardMode = this.billboardMode;
  11591. this._currentRenderId = this.getScene().getRenderId();
  11592. this._isDirty = false;
  11593. // Scaling
  11594. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  11595. // Rotation
  11596. //rotate, if quaternion is set and rotation was used
  11597. if (this.rotationQuaternion) {
  11598. var len = this.rotation.length();
  11599. if (len) {
  11600. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  11601. this.rotation.copyFromFloats(0, 0, 0);
  11602. }
  11603. }
  11604. if (this.rotationQuaternion) {
  11605. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  11606. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  11607. }
  11608. else {
  11609. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  11610. this._cache.rotation.copyFrom(this.rotation);
  11611. }
  11612. // Translation
  11613. if (this.infiniteDistance && !this.parent) {
  11614. var camera = this.getScene().activeCamera;
  11615. if (camera) {
  11616. var cameraWorldMatrix = camera.getWorldMatrix();
  11617. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  11618. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  11619. }
  11620. }
  11621. else {
  11622. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  11623. }
  11624. // Composing transformations
  11625. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  11626. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11627. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  11628. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  11629. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  11630. // Need to decompose each rotation here
  11631. var currentPosition = BABYLON.Tmp.Vector3[3];
  11632. if (this.parent && this.parent.getWorldMatrix) {
  11633. if (this._meshToBoneReferal) {
  11634. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11635. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  11636. }
  11637. else {
  11638. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  11639. }
  11640. }
  11641. else {
  11642. currentPosition.copyFrom(this.position);
  11643. }
  11644. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  11645. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  11646. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  11647. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  11648. }
  11649. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  11650. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  11651. }
  11652. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  11653. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  11654. }
  11655. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  11656. }
  11657. else {
  11658. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  11659. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  11660. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  11661. }
  11662. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  11663. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11664. }
  11665. // Local world
  11666. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  11667. // Parent
  11668. if (this.parent && this.parent.getWorldMatrix) {
  11669. this._markSyncedWithParent();
  11670. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  11671. if (this._meshToBoneReferal) {
  11672. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11673. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  11674. }
  11675. else {
  11676. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  11677. }
  11678. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  11679. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  11680. this._worldMatrix.copyFrom(this._localWorld);
  11681. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  11682. }
  11683. else {
  11684. if (this._meshToBoneReferal) {
  11685. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11686. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  11687. }
  11688. else {
  11689. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  11690. }
  11691. }
  11692. }
  11693. else {
  11694. this._worldMatrix.copyFrom(this._localWorld);
  11695. }
  11696. // Bounding info
  11697. this._updateBoundingInfo();
  11698. // Absolute position
  11699. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  11700. // Callbacks
  11701. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  11702. if (!this._poseMatrix) {
  11703. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  11704. }
  11705. return this._worldMatrix;
  11706. };
  11707. /**
  11708. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  11709. * @param func: callback function to add
  11710. *
  11711. * Returns the AbstractMesh.
  11712. */
  11713. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  11714. this.onAfterWorldMatrixUpdateObservable.add(func);
  11715. return this;
  11716. };
  11717. /**
  11718. * Removes a registered callback function.
  11719. * Returns the AbstractMesh.
  11720. */
  11721. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  11722. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  11723. return this;
  11724. };
  11725. /**
  11726. * Sets the mesh position in its local space.
  11727. * Returns the AbstractMesh.
  11728. */
  11729. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  11730. this.computeWorldMatrix();
  11731. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  11732. return this;
  11733. };
  11734. /**
  11735. * Returns the mesh position in the local space from the current World matrix values.
  11736. * Returns a new Vector3.
  11737. */
  11738. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  11739. this.computeWorldMatrix();
  11740. var invLocalWorldMatrix = this._localWorld.clone();
  11741. invLocalWorldMatrix.invert();
  11742. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  11743. };
  11744. /**
  11745. * Translates the mesh along the passed Vector3 in its local space.
  11746. * Returns the AbstractMesh.
  11747. */
  11748. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  11749. this.computeWorldMatrix(true);
  11750. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  11751. return this;
  11752. };
  11753. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  11754. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  11755. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  11756. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  11757. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  11758. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  11759. /// <returns>Mesh oriented towards targetMesh</returns>
  11760. if (yawCor === void 0) { yawCor = 0; }
  11761. if (pitchCor === void 0) { pitchCor = 0; }
  11762. if (rollCor === void 0) { rollCor = 0; }
  11763. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11764. var dv = AbstractMesh._lookAtVectorCache;
  11765. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  11766. targetPoint.subtractToRef(pos, dv);
  11767. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  11768. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  11769. var pitch = Math.atan2(dv.y, len);
  11770. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  11771. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  11772. return this;
  11773. };
  11774. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11775. this._meshToBoneReferal = affectedMesh;
  11776. this.parent = bone;
  11777. if (bone.getWorldMatrix().determinant() < 0) {
  11778. this.scalingDeterminant *= -1;
  11779. }
  11780. return this;
  11781. };
  11782. AbstractMesh.prototype.detachFromBone = function () {
  11783. if (this.parent.getWorldMatrix().determinant() < 0) {
  11784. this.scalingDeterminant *= -1;
  11785. }
  11786. this._meshToBoneReferal = null;
  11787. this.parent = null;
  11788. return this;
  11789. };
  11790. /**
  11791. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  11792. * A mesh is in the frustum if its bounding box intersects the frustum.
  11793. * Boolean returned.
  11794. */
  11795. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11796. return this._boundingInfo.isInFrustum(frustumPlanes);
  11797. };
  11798. /**
  11799. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  11800. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  11801. * Boolean returned.
  11802. */
  11803. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11804. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11805. ;
  11806. };
  11807. /**
  11808. * True if the mesh intersects another mesh or a SolidParticle object.
  11809. * 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)
  11810. * Returns a boolean.
  11811. */
  11812. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11813. if (!this._boundingInfo || !mesh._boundingInfo) {
  11814. return false;
  11815. }
  11816. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11817. };
  11818. /**
  11819. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  11820. * Returns a boolean.
  11821. */
  11822. AbstractMesh.prototype.intersectsPoint = function (point) {
  11823. if (!this._boundingInfo) {
  11824. return false;
  11825. }
  11826. return this._boundingInfo.intersectsPoint(point);
  11827. };
  11828. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11829. return this.physicsImpostor;
  11830. };
  11831. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11832. if (!camera) {
  11833. camera = this.getScene().activeCamera;
  11834. }
  11835. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11836. };
  11837. /**
  11838. * Returns the distance from the mesh to the active camera.
  11839. * Returns a float.
  11840. */
  11841. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11842. if (!camera) {
  11843. camera = this.getScene().activeCamera;
  11844. }
  11845. return this.absolutePosition.subtract(camera.position).length();
  11846. };
  11847. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11848. if (!this.physicsImpostor) {
  11849. return;
  11850. }
  11851. this.physicsImpostor.applyImpulse(force, contactPoint);
  11852. return this;
  11853. };
  11854. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11855. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11856. return;
  11857. }
  11858. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11859. mainPivot: pivot1,
  11860. connectedPivot: pivot2,
  11861. nativeParams: options
  11862. });
  11863. return this;
  11864. };
  11865. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11866. // Collisions
  11867. /**
  11868. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  11869. * Default `false`.
  11870. */
  11871. get: function () {
  11872. return this._checkCollisions;
  11873. },
  11874. set: function (collisionEnabled) {
  11875. this._checkCollisions = collisionEnabled;
  11876. if (this.getScene().workerCollisions) {
  11877. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11878. }
  11879. },
  11880. enumerable: true,
  11881. configurable: true
  11882. });
  11883. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11884. var globalPosition = this.getAbsolutePosition();
  11885. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11886. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11887. if (!this._collider) {
  11888. this._collider = new BABYLON.Collider();
  11889. }
  11890. this._collider.radius = this.ellipsoid;
  11891. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11892. return this;
  11893. };
  11894. // Submeshes octree
  11895. /**
  11896. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  11897. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  11898. * Returns an Octree of submeshes.
  11899. */
  11900. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11901. if (maxCapacity === void 0) { maxCapacity = 64; }
  11902. if (maxDepth === void 0) { maxDepth = 2; }
  11903. if (!this._submeshesOctree) {
  11904. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11905. }
  11906. this.computeWorldMatrix(true);
  11907. // Update octree
  11908. var bbox = this.getBoundingInfo().boundingBox;
  11909. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11910. return this._submeshesOctree;
  11911. };
  11912. // Collisions
  11913. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11914. this._generatePointsArray();
  11915. // Transformation
  11916. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11917. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11918. subMesh._lastColliderWorldVertices = [];
  11919. subMesh._trianglePlanes = [];
  11920. var start = subMesh.verticesStart;
  11921. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11922. for (var i = start; i < end; i++) {
  11923. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11924. }
  11925. }
  11926. // Collide
  11927. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11928. if (collider.collisionFound) {
  11929. collider.collidedMesh = this;
  11930. }
  11931. return this;
  11932. };
  11933. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11934. var subMeshes;
  11935. var len;
  11936. // Octrees
  11937. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11938. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11939. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11940. len = intersections.length;
  11941. subMeshes = intersections.data;
  11942. }
  11943. else {
  11944. subMeshes = this.subMeshes;
  11945. len = subMeshes.length;
  11946. }
  11947. for (var index = 0; index < len; index++) {
  11948. var subMesh = subMeshes[index];
  11949. // Bounding test
  11950. if (len > 1 && !subMesh._checkCollision(collider))
  11951. continue;
  11952. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11953. }
  11954. return this;
  11955. };
  11956. AbstractMesh.prototype._checkCollision = function (collider) {
  11957. // Bounding box test
  11958. if (!this._boundingInfo._checkCollision(collider))
  11959. return this;
  11960. // Transformation matrix
  11961. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11962. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11963. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11964. return this;
  11965. };
  11966. // Picking
  11967. AbstractMesh.prototype._generatePointsArray = function () {
  11968. return false;
  11969. };
  11970. /**
  11971. * Checks if the passed Ray intersects with the mesh.
  11972. * Returns an object PickingInfo.
  11973. */
  11974. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11975. var pickingInfo = new BABYLON.PickingInfo();
  11976. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11977. return pickingInfo;
  11978. }
  11979. if (!this._generatePointsArray()) {
  11980. return pickingInfo;
  11981. }
  11982. var intersectInfo = null;
  11983. // Octrees
  11984. var subMeshes;
  11985. var len;
  11986. if (this._submeshesOctree && this.useOctreeForPicking) {
  11987. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11988. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11989. len = intersections.length;
  11990. subMeshes = intersections.data;
  11991. }
  11992. else {
  11993. subMeshes = this.subMeshes;
  11994. len = subMeshes.length;
  11995. }
  11996. for (var index = 0; index < len; index++) {
  11997. var subMesh = subMeshes[index];
  11998. // Bounding test
  11999. if (len > 1 && !subMesh.canIntersects(ray))
  12000. continue;
  12001. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12002. if (currentIntersectInfo) {
  12003. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12004. intersectInfo = currentIntersectInfo;
  12005. intersectInfo.subMeshId = index;
  12006. if (fastCheck) {
  12007. break;
  12008. }
  12009. }
  12010. }
  12011. }
  12012. if (intersectInfo) {
  12013. // Get picked point
  12014. var world = this.getWorldMatrix();
  12015. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12016. var direction = ray.direction.clone();
  12017. direction = direction.scale(intersectInfo.distance);
  12018. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12019. var pickedPoint = worldOrigin.add(worldDirection);
  12020. // Return result
  12021. pickingInfo.hit = true;
  12022. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12023. pickingInfo.pickedPoint = pickedPoint;
  12024. pickingInfo.pickedMesh = this;
  12025. pickingInfo.bu = intersectInfo.bu;
  12026. pickingInfo.bv = intersectInfo.bv;
  12027. pickingInfo.faceId = intersectInfo.faceId;
  12028. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12029. return pickingInfo;
  12030. }
  12031. return pickingInfo;
  12032. };
  12033. /**
  12034. * Clones the mesh, used by the class Mesh.
  12035. * Just returns `null` for an AbstractMesh.
  12036. */
  12037. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12038. return null;
  12039. };
  12040. /**
  12041. * Disposes all the mesh submeshes.
  12042. * Returns the AbstractMesh.
  12043. */
  12044. AbstractMesh.prototype.releaseSubMeshes = function () {
  12045. if (this.subMeshes) {
  12046. while (this.subMeshes.length) {
  12047. this.subMeshes[0].dispose();
  12048. }
  12049. }
  12050. else {
  12051. this.subMeshes = new Array();
  12052. }
  12053. return this;
  12054. };
  12055. /**
  12056. * Disposes the AbstractMesh.
  12057. * Some internal references are kept for further use.
  12058. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12059. * Returns nothing.
  12060. */
  12061. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12062. var _this = this;
  12063. var index;
  12064. // Action manager
  12065. if (this.actionManager) {
  12066. this.actionManager.dispose();
  12067. this.actionManager = null;
  12068. }
  12069. // Skeleton
  12070. this.skeleton = null;
  12071. // Animations
  12072. this.getScene().stopAnimation(this);
  12073. // Physics
  12074. if (this.physicsImpostor) {
  12075. this.physicsImpostor.dispose();
  12076. }
  12077. // Intersections in progress
  12078. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12079. var other = this._intersectionsInProgress[index];
  12080. var pos = other._intersectionsInProgress.indexOf(this);
  12081. other._intersectionsInProgress.splice(pos, 1);
  12082. }
  12083. this._intersectionsInProgress = [];
  12084. // Lights
  12085. var lights = this.getScene().lights;
  12086. lights.forEach(function (light) {
  12087. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12088. if (meshIndex !== -1) {
  12089. light.includedOnlyMeshes.splice(meshIndex, 1);
  12090. }
  12091. meshIndex = light.excludedMeshes.indexOf(_this);
  12092. if (meshIndex !== -1) {
  12093. light.excludedMeshes.splice(meshIndex, 1);
  12094. }
  12095. // Shadow generators
  12096. var generator = light.getShadowGenerator();
  12097. if (generator) {
  12098. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  12099. if (meshIndex !== -1) {
  12100. generator.getShadowMap().renderList.splice(meshIndex, 1);
  12101. }
  12102. }
  12103. });
  12104. // Edges
  12105. if (this._edgesRenderer) {
  12106. this._edgesRenderer.dispose();
  12107. this._edgesRenderer = null;
  12108. }
  12109. // SubMeshes
  12110. if (this.getClassName() !== "InstancedMesh") {
  12111. this.releaseSubMeshes();
  12112. }
  12113. // Octree
  12114. var sceneOctree = this.getScene().selectionOctree;
  12115. if (sceneOctree) {
  12116. var index = sceneOctree.dynamicContent.indexOf(this);
  12117. if (index !== -1) {
  12118. sceneOctree.dynamicContent.splice(index, 1);
  12119. }
  12120. }
  12121. // Engine
  12122. this.getScene().getEngine().wipeCaches();
  12123. // Remove from scene
  12124. this.getScene().removeMesh(this);
  12125. if (!doNotRecurse) {
  12126. // Particles
  12127. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12128. if (this.getScene().particleSystems[index].emitter === this) {
  12129. this.getScene().particleSystems[index].dispose();
  12130. index--;
  12131. }
  12132. }
  12133. // Children
  12134. var objects = this.getDescendants(true);
  12135. for (index = 0; index < objects.length; index++) {
  12136. objects[index].dispose();
  12137. }
  12138. }
  12139. else {
  12140. var childMeshes = this.getChildMeshes(true);
  12141. for (index = 0; index < childMeshes.length; index++) {
  12142. var child = childMeshes[index];
  12143. child.parent = null;
  12144. child.computeWorldMatrix(true);
  12145. }
  12146. }
  12147. // facet data
  12148. if (this._facetDataEnabled) {
  12149. this.disableFacetData();
  12150. }
  12151. this.onAfterWorldMatrixUpdateObservable.clear();
  12152. this.onCollideObservable.clear();
  12153. this.onCollisionPositionChangeObservable.clear();
  12154. this._isDisposed = true;
  12155. _super.prototype.dispose.call(this);
  12156. };
  12157. /**
  12158. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12159. * This Vector3 is expressed in the World space.
  12160. */
  12161. AbstractMesh.prototype.getDirection = function (localAxis) {
  12162. var result = BABYLON.Vector3.Zero();
  12163. this.getDirectionToRef(localAxis, result);
  12164. return result;
  12165. };
  12166. /**
  12167. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12168. * localAxis is expressed in the mesh local space.
  12169. * result is computed in the Wordl space from the mesh World matrix.
  12170. * Returns the AbstractMesh.
  12171. */
  12172. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12173. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12174. return this;
  12175. };
  12176. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12177. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12178. if (this.getScene().getRenderId() == 0) {
  12179. this.computeWorldMatrix(true);
  12180. }
  12181. var wm = this.getWorldMatrix();
  12182. if (space == BABYLON.Space.WORLD) {
  12183. var tmat = BABYLON.Tmp.Matrix[0];
  12184. wm.invertToRef(tmat);
  12185. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12186. }
  12187. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12188. this._pivotMatrix.m[12] = -point.x;
  12189. this._pivotMatrix.m[13] = -point.y;
  12190. this._pivotMatrix.m[14] = -point.z;
  12191. this._cache.pivotMatrixUpdated = true;
  12192. return this;
  12193. };
  12194. /**
  12195. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12196. */
  12197. AbstractMesh.prototype.getPivotPoint = function () {
  12198. var point = BABYLON.Vector3.Zero();
  12199. this.getPivotPointToRef(point);
  12200. return point;
  12201. };
  12202. /**
  12203. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12204. * Returns the AbstractMesh.
  12205. */
  12206. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12207. result.x = -this._pivotMatrix.m[12];
  12208. result.y = -this._pivotMatrix.m[13];
  12209. result.z = -this._pivotMatrix.m[14];
  12210. return this;
  12211. };
  12212. /**
  12213. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12214. */
  12215. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12216. var point = BABYLON.Vector3.Zero();
  12217. this.getAbsolutePivotPointToRef(point);
  12218. return point;
  12219. };
  12220. /**
  12221. * Defines the passed mesh as the parent of the current mesh.
  12222. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  12223. * Returns the AbstractMesh.
  12224. */
  12225. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  12226. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  12227. var child = this;
  12228. var parent = mesh;
  12229. if (mesh == null) {
  12230. if (child.parent && keepWorldPositionRotation) {
  12231. var rotation = BABYLON.Tmp.Quaternion[0];
  12232. var position = BABYLON.Tmp.Vector3[0];
  12233. var scale = BABYLON.Tmp.Vector3[1];
  12234. child.getWorldMatrix().decompose(scale, rotation, position);
  12235. if (child.rotationQuaternion) {
  12236. child.rotationQuaternion.copyFrom(rotation);
  12237. }
  12238. else {
  12239. rotation.toEulerAnglesToRef(child.rotation);
  12240. }
  12241. child.position.x = position.x;
  12242. child.position.y = position.y;
  12243. child.position.z = position.z;
  12244. }
  12245. }
  12246. else {
  12247. if (keepWorldPositionRotation) {
  12248. var rotation = BABYLON.Tmp.Quaternion[0];
  12249. var position = BABYLON.Tmp.Vector3[0];
  12250. var scale = BABYLON.Tmp.Vector3[1];
  12251. var m1 = BABYLON.Tmp.Matrix[0];
  12252. var m2 = BABYLON.Tmp.Matrix[1];
  12253. parent.getWorldMatrix().decompose(scale, rotation, position);
  12254. rotation.toRotationMatrix(m1);
  12255. m2.setTranslation(position);
  12256. m2.multiplyToRef(m1, m1);
  12257. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12258. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12259. m.decompose(scale, rotation, position);
  12260. if (child.rotationQuaternion) {
  12261. child.rotationQuaternion.copyFrom(rotation);
  12262. }
  12263. else {
  12264. rotation.toEulerAnglesToRef(child.rotation);
  12265. }
  12266. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12267. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12268. m.decompose(scale, rotation, position);
  12269. child.position.x = position.x;
  12270. child.position.y = position.y;
  12271. child.position.z = position.z;
  12272. }
  12273. }
  12274. child.parent = parent;
  12275. return this;
  12276. };
  12277. /**
  12278. * Adds the passed mesh as a child to the current mesh.
  12279. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  12280. * Returns the AbstractMesh.
  12281. */
  12282. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  12283. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  12284. mesh.setParent(this, keepWorldPositionRotation);
  12285. return this;
  12286. };
  12287. /**
  12288. * Removes the passed mesh from the current mesh children list.
  12289. * Returns the AbstractMesh.
  12290. */
  12291. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  12292. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  12293. mesh.setParent(null, keepWorldPositionRotation);
  12294. return this;
  12295. };
  12296. /**
  12297. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12298. * Returns the AbstractMesh.
  12299. */
  12300. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12301. result.x = this._pivotMatrix.m[12];
  12302. result.y = this._pivotMatrix.m[13];
  12303. result.z = this._pivotMatrix.m[14];
  12304. this.getPivotPointToRef(result);
  12305. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12306. return this;
  12307. };
  12308. // Facet data
  12309. /**
  12310. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12311. * Returns the AbstractMesh.
  12312. */
  12313. AbstractMesh.prototype._initFacetData = function () {
  12314. if (!this._facetNormals) {
  12315. this._facetNormals = new Array();
  12316. }
  12317. if (!this._facetPositions) {
  12318. this._facetPositions = new Array();
  12319. }
  12320. if (!this._facetPartitioning) {
  12321. this._facetPartitioning = new Array();
  12322. }
  12323. this._facetNb = this.getIndices().length / 3;
  12324. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12325. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12326. for (var f = 0; f < this._facetNb; f++) {
  12327. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12328. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12329. }
  12330. this._facetDataEnabled = true;
  12331. return this;
  12332. };
  12333. /**
  12334. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12335. * This method can be called within the render loop.
  12336. * 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.
  12337. * Returns the AbstractMesh.
  12338. */
  12339. AbstractMesh.prototype.updateFacetData = function () {
  12340. if (!this._facetDataEnabled) {
  12341. this._initFacetData();
  12342. }
  12343. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12344. var indices = this.getIndices();
  12345. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12346. var bInfo = this.getBoundingInfo();
  12347. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12348. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12349. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12350. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12351. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12352. this._subDiv.max = this._partitioningSubdivisions;
  12353. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12354. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12355. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12356. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12357. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12358. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12359. // set the parameters for ComputeNormals()
  12360. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12361. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12362. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12363. this._facetParameters.bInfo = bInfo;
  12364. this._facetParameters.bbSize = this._bbSize;
  12365. this._facetParameters.subDiv = this._subDiv;
  12366. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12367. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12368. return this;
  12369. };
  12370. /**
  12371. * Returns the facetLocalNormals array.
  12372. * The normals are expressed in the mesh local space.
  12373. */
  12374. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12375. if (!this._facetNormals) {
  12376. this.updateFacetData();
  12377. }
  12378. return this._facetNormals;
  12379. };
  12380. /**
  12381. * Returns the facetLocalPositions array.
  12382. * The facet positions are expressed in the mesh local space.
  12383. */
  12384. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12385. if (!this._facetPositions) {
  12386. this.updateFacetData();
  12387. }
  12388. return this._facetPositions;
  12389. };
  12390. /**
  12391. * Returns the facetLocalPartioning array.
  12392. */
  12393. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12394. if (!this._facetPartitioning) {
  12395. this.updateFacetData();
  12396. }
  12397. return this._facetPartitioning;
  12398. };
  12399. /**
  12400. * Returns the i-th facet position in the world system.
  12401. * This method allocates a new Vector3 per call.
  12402. */
  12403. AbstractMesh.prototype.getFacetPosition = function (i) {
  12404. var pos = BABYLON.Vector3.Zero();
  12405. this.getFacetPositionToRef(i, pos);
  12406. return pos;
  12407. };
  12408. /**
  12409. * Sets the reference Vector3 with the i-th facet position in the world system.
  12410. * Returns the AbstractMesh.
  12411. */
  12412. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12413. var localPos = (this.getFacetLocalPositions())[i];
  12414. var world = this.getWorldMatrix();
  12415. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12416. return this;
  12417. };
  12418. /**
  12419. * Returns the i-th facet normal in the world system.
  12420. * This method allocates a new Vector3 per call.
  12421. */
  12422. AbstractMesh.prototype.getFacetNormal = function (i) {
  12423. var norm = BABYLON.Vector3.Zero();
  12424. this.getFacetNormalToRef(i, norm);
  12425. return norm;
  12426. };
  12427. /**
  12428. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12429. * Returns the AbstractMesh.
  12430. */
  12431. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12432. var localNorm = (this.getFacetLocalNormals())[i];
  12433. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12434. return this;
  12435. };
  12436. /**
  12437. * 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).
  12438. */
  12439. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12440. var bInfo = this.getBoundingInfo();
  12441. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12442. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  12443. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  12444. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  12445. return null;
  12446. }
  12447. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  12448. };
  12449. /**
  12450. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  12451. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  12452. * 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.
  12453. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12454. * 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.
  12455. */
  12456. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  12457. if (checkFace === void 0) { checkFace = false; }
  12458. if (facing === void 0) { facing = true; }
  12459. var world = this.getWorldMatrix();
  12460. var invMat = BABYLON.Tmp.Matrix[5];
  12461. world.invertToRef(invMat);
  12462. var invVect = BABYLON.Tmp.Vector3[8];
  12463. var closest = null;
  12464. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  12465. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  12466. if (projected) {
  12467. // tranform the local computed projected vector to world coordinates
  12468. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  12469. }
  12470. return closest;
  12471. };
  12472. /**
  12473. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  12474. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  12475. * 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.
  12476. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12477. * 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.
  12478. */
  12479. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  12480. if (checkFace === void 0) { checkFace = false; }
  12481. if (facing === void 0) { facing = true; }
  12482. var closest = null;
  12483. var tmpx = 0.0;
  12484. var tmpy = 0.0;
  12485. var tmpz = 0.0;
  12486. var d = 0.0; // tmp dot facet normal * facet position
  12487. var t0 = 0.0;
  12488. var projx = 0.0;
  12489. var projy = 0.0;
  12490. var projz = 0.0;
  12491. // Get all the facets in the same partitioning block than (x, y, z)
  12492. var facetPositions = this.getFacetLocalPositions();
  12493. var facetNormals = this.getFacetLocalNormals();
  12494. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  12495. if (!facetsInBlock) {
  12496. return null;
  12497. }
  12498. // Get the closest facet to (x, y, z)
  12499. var shortest = Number.MAX_VALUE; // init distance vars
  12500. var tmpDistance = shortest;
  12501. var fib; // current facet in the block
  12502. var norm; // current facet normal
  12503. var p0; // current facet barycenter position
  12504. // loop on all the facets in the current partitioning block
  12505. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  12506. fib = facetsInBlock[idx];
  12507. norm = facetNormals[fib];
  12508. p0 = facetPositions[fib];
  12509. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  12510. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  12511. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  12512. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  12513. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  12514. projx = x + norm.x * t0;
  12515. projy = y + norm.y * t0;
  12516. projz = z + norm.z * t0;
  12517. tmpx = projx - x;
  12518. tmpy = projy - y;
  12519. tmpz = projz - z;
  12520. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  12521. if (tmpDistance < shortest) {
  12522. shortest = tmpDistance;
  12523. closest = fib;
  12524. if (projected) {
  12525. projected.x = projx;
  12526. projected.y = projy;
  12527. projected.z = projz;
  12528. }
  12529. }
  12530. }
  12531. }
  12532. return closest;
  12533. };
  12534. /**
  12535. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  12536. */
  12537. AbstractMesh.prototype.getFacetDataParameters = function () {
  12538. return this._facetParameters;
  12539. };
  12540. /**
  12541. * Disables the feature FacetData and frees the related memory.
  12542. * Returns the AbstractMesh.
  12543. */
  12544. AbstractMesh.prototype.disableFacetData = function () {
  12545. if (this._facetDataEnabled) {
  12546. this._facetDataEnabled = false;
  12547. this._facetPositions = null;
  12548. this._facetNormals = null;
  12549. this._facetPartitioning = null;
  12550. this._facetParameters = null;
  12551. }
  12552. return this;
  12553. };
  12554. /**
  12555. * Creates new normals data for the mesh.
  12556. * @param updatable.
  12557. */
  12558. AbstractMesh.prototype.createNormals = function (updatable) {
  12559. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12560. var indices = this.getIndices();
  12561. var normals;
  12562. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12563. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12564. }
  12565. else {
  12566. normals = [];
  12567. }
  12568. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  12569. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  12570. };
  12571. return AbstractMesh;
  12572. }(BABYLON.Node));
  12573. // Statics
  12574. AbstractMesh._BILLBOARDMODE_NONE = 0;
  12575. AbstractMesh._BILLBOARDMODE_X = 1;
  12576. AbstractMesh._BILLBOARDMODE_Y = 2;
  12577. AbstractMesh._BILLBOARDMODE_Z = 4;
  12578. AbstractMesh._BILLBOARDMODE_ALL = 7;
  12579. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  12580. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  12581. BABYLON.AbstractMesh = AbstractMesh;
  12582. })(BABYLON || (BABYLON = {}));
  12583. //# sourceMappingURL=babylon.abstractMesh.js.map
  12584. var BABYLON;
  12585. (function (BABYLON) {
  12586. var Light = (function (_super) {
  12587. __extends(Light, _super);
  12588. /**
  12589. * Creates a Light object in the scene.
  12590. * Documentation : http://doc.babylonjs.com/tutorials/lights
  12591. */
  12592. function Light(name, scene) {
  12593. var _this = _super.call(this, name, scene) || this;
  12594. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  12595. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  12596. _this.intensity = 1.0;
  12597. _this.range = Number.MAX_VALUE;
  12598. _this._excludeWithLayerMask = 0;
  12599. _this._includeOnlyWithLayerMask = 0;
  12600. _this._lightmapMode = 0;
  12601. // PBR Properties.
  12602. _this.radius = 0.00001;
  12603. _this._excludedMeshesIds = new Array();
  12604. _this._includedOnlyMeshesIds = new Array();
  12605. _this.getScene().addLight(_this);
  12606. _this.includedOnlyMeshes = new Array();
  12607. _this.excludedMeshes = new Array();
  12608. _this._resyncMeshes();
  12609. return _this;
  12610. }
  12611. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  12612. /**
  12613. * If every light affecting the material is in this lightmapMode,
  12614. * material.lightmapTexture adds or multiplies
  12615. * (depends on material.useLightmapAsShadowmap)
  12616. * after every other light calculations.
  12617. */
  12618. get: function () {
  12619. return Light._LIGHTMAP_DEFAULT;
  12620. },
  12621. enumerable: true,
  12622. configurable: true
  12623. });
  12624. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  12625. /**
  12626. * material.lightmapTexture as only diffuse lighting from this light
  12627. * adds pnly specular lighting from this light
  12628. * adds dynamic shadows
  12629. */
  12630. get: function () {
  12631. return Light._LIGHTMAP_SPECULAR;
  12632. },
  12633. enumerable: true,
  12634. configurable: true
  12635. });
  12636. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  12637. /**
  12638. * material.lightmapTexture as only lighting
  12639. * no light calculation from this light
  12640. * only adds dynamic shadows from this light
  12641. */
  12642. get: function () {
  12643. return Light._LIGHTMAP_SHADOWSONLY;
  12644. },
  12645. enumerable: true,
  12646. configurable: true
  12647. });
  12648. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  12649. get: function () {
  12650. return this._includedOnlyMeshes;
  12651. },
  12652. set: function (value) {
  12653. this._includedOnlyMeshes = value;
  12654. this._hookArrayForIncludedOnly(value);
  12655. },
  12656. enumerable: true,
  12657. configurable: true
  12658. });
  12659. Object.defineProperty(Light.prototype, "excludedMeshes", {
  12660. get: function () {
  12661. return this._excludedMeshes;
  12662. },
  12663. set: function (value) {
  12664. this._excludedMeshes = value;
  12665. this._hookArrayForExcluded(value);
  12666. },
  12667. enumerable: true,
  12668. configurable: true
  12669. });
  12670. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  12671. get: function () {
  12672. return this._excludeWithLayerMask;
  12673. },
  12674. set: function (value) {
  12675. this._excludeWithLayerMask = value;
  12676. this._resyncMeshes();
  12677. },
  12678. enumerable: true,
  12679. configurable: true
  12680. });
  12681. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  12682. get: function () {
  12683. return this._includeOnlyWithLayerMask;
  12684. },
  12685. set: function (value) {
  12686. this._includeOnlyWithLayerMask = value;
  12687. this._resyncMeshes();
  12688. },
  12689. enumerable: true,
  12690. configurable: true
  12691. });
  12692. Object.defineProperty(Light.prototype, "lightmapMode", {
  12693. get: function () {
  12694. return this._lightmapMode;
  12695. },
  12696. set: function (value) {
  12697. if (this._lightmapMode === value) {
  12698. return;
  12699. }
  12700. this._lightmapMode = value;
  12701. this._markMeshesAsLightDirty();
  12702. },
  12703. enumerable: true,
  12704. configurable: true
  12705. });
  12706. /**
  12707. * Returns the string "Light".
  12708. */
  12709. Light.prototype.getClassName = function () {
  12710. return "Light";
  12711. };
  12712. /**
  12713. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12714. */
  12715. Light.prototype.toString = function (fullDetails) {
  12716. var ret = "Name: " + this.name;
  12717. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  12718. if (this.animations) {
  12719. for (var i = 0; i < this.animations.length; i++) {
  12720. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12721. }
  12722. }
  12723. if (fullDetails) {
  12724. }
  12725. return ret;
  12726. };
  12727. /**
  12728. * Set the enabled state of this node.
  12729. * @param {boolean} value - the new enabled state
  12730. * @see isEnabled
  12731. */
  12732. Light.prototype.setEnabled = function (value) {
  12733. _super.prototype.setEnabled.call(this, value);
  12734. this._resyncMeshes();
  12735. };
  12736. /**
  12737. * Returns the Light associated shadow generator.
  12738. */
  12739. Light.prototype.getShadowGenerator = function () {
  12740. return this._shadowGenerator;
  12741. };
  12742. /**
  12743. * Returns a Vector3, the absolute light position in the World.
  12744. */
  12745. Light.prototype.getAbsolutePosition = function () {
  12746. return BABYLON.Vector3.Zero();
  12747. };
  12748. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  12749. };
  12750. Light.prototype._getWorldMatrix = function () {
  12751. return BABYLON.Matrix.Identity();
  12752. };
  12753. /**
  12754. * Boolean : True if the light will affect the passed mesh.
  12755. */
  12756. Light.prototype.canAffectMesh = function (mesh) {
  12757. if (!mesh) {
  12758. return true;
  12759. }
  12760. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  12761. return false;
  12762. }
  12763. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  12764. return false;
  12765. }
  12766. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  12767. return false;
  12768. }
  12769. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  12770. return false;
  12771. }
  12772. return true;
  12773. };
  12774. /**
  12775. * Returns the light World matrix.
  12776. */
  12777. Light.prototype.getWorldMatrix = function () {
  12778. this._currentRenderId = this.getScene().getRenderId();
  12779. var worldMatrix = this._getWorldMatrix();
  12780. if (this.parent && this.parent.getWorldMatrix) {
  12781. if (!this._parentedWorldMatrix) {
  12782. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  12783. }
  12784. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  12785. this._markSyncedWithParent();
  12786. return this._parentedWorldMatrix;
  12787. }
  12788. return worldMatrix;
  12789. };
  12790. /**
  12791. * Disposes the light.
  12792. */
  12793. Light.prototype.dispose = function () {
  12794. if (this._shadowGenerator) {
  12795. this._shadowGenerator.dispose();
  12796. this._shadowGenerator = null;
  12797. }
  12798. // Animations
  12799. this.getScene().stopAnimation(this);
  12800. // Remove from meshes
  12801. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  12802. var mesh = _a[_i];
  12803. mesh._removeLightSource(this);
  12804. }
  12805. // Remove from scene
  12806. this.getScene().removeLight(this);
  12807. _super.prototype.dispose.call(this);
  12808. };
  12809. /**
  12810. * Returns the light type ID (integer).
  12811. */
  12812. Light.prototype.getTypeID = function () {
  12813. return 0;
  12814. };
  12815. /**
  12816. * Returns a new Light object, named "name", from the current one.
  12817. */
  12818. Light.prototype.clone = function (name) {
  12819. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  12820. };
  12821. /**
  12822. * Serializes the current light into a Serialization object.
  12823. * Returns the serialized object.
  12824. */
  12825. Light.prototype.serialize = function () {
  12826. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12827. // Type
  12828. serializationObject.type = this.getTypeID();
  12829. // Parent
  12830. if (this.parent) {
  12831. serializationObject.parentId = this.parent.id;
  12832. }
  12833. // Inclusion / exclusions
  12834. if (this.excludedMeshes.length > 0) {
  12835. serializationObject.excludedMeshesIds = [];
  12836. this.excludedMeshes.forEach(function (mesh) {
  12837. serializationObject.excludedMeshesIds.push(mesh.id);
  12838. });
  12839. }
  12840. if (this.includedOnlyMeshes.length > 0) {
  12841. serializationObject.includedOnlyMeshesIds = [];
  12842. this.includedOnlyMeshes.forEach(function (mesh) {
  12843. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  12844. });
  12845. }
  12846. // Animations
  12847. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12848. serializationObject.ranges = this.serializeAnimationRanges();
  12849. return serializationObject;
  12850. };
  12851. /**
  12852. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  12853. * This new light is named "name" and added to the passed scene.
  12854. */
  12855. Light.GetConstructorFromName = function (type, name, scene) {
  12856. switch (type) {
  12857. case 0:
  12858. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  12859. case 1:
  12860. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  12861. case 2:
  12862. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  12863. case 3:
  12864. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  12865. }
  12866. };
  12867. /**
  12868. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  12869. */
  12870. Light.Parse = function (parsedLight, scene) {
  12871. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  12872. // Inclusion / exclusions
  12873. if (parsedLight.excludedMeshesIds) {
  12874. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  12875. }
  12876. if (parsedLight.includedOnlyMeshesIds) {
  12877. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  12878. }
  12879. // Parent
  12880. if (parsedLight.parentId) {
  12881. light._waitingParentId = parsedLight.parentId;
  12882. }
  12883. // Animations
  12884. if (parsedLight.animations) {
  12885. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  12886. var parsedAnimation = parsedLight.animations[animationIndex];
  12887. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12888. }
  12889. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  12890. }
  12891. if (parsedLight.autoAnimate) {
  12892. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  12893. }
  12894. return light;
  12895. };
  12896. Light.prototype._hookArrayForExcluded = function (array) {
  12897. var _this = this;
  12898. var oldPush = array.push;
  12899. array.push = function () {
  12900. var items = [];
  12901. for (var _i = 0; _i < arguments.length; _i++) {
  12902. items[_i] = arguments[_i];
  12903. }
  12904. var result = oldPush.apply(array, items);
  12905. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  12906. var item = items_1[_a];
  12907. item._resyncLighSource(_this);
  12908. }
  12909. return result;
  12910. };
  12911. var oldSplice = array.splice;
  12912. array.splice = function (index, deleteCount) {
  12913. var deleted = oldSplice.apply(array, [index, deleteCount]);
  12914. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  12915. var item = deleted_1[_i];
  12916. item._resyncLighSource(_this);
  12917. }
  12918. return deleted;
  12919. };
  12920. };
  12921. Light.prototype._hookArrayForIncludedOnly = function (array) {
  12922. var _this = this;
  12923. var oldPush = array.push;
  12924. array.push = function () {
  12925. var items = [];
  12926. for (var _i = 0; _i < arguments.length; _i++) {
  12927. items[_i] = arguments[_i];
  12928. }
  12929. var result = oldPush.apply(array, items);
  12930. _this._resyncMeshes();
  12931. return result;
  12932. };
  12933. var oldSplice = array.splice;
  12934. array.splice = function (index, deleteCount) {
  12935. var deleted = oldSplice.apply(array, [index, deleteCount]);
  12936. _this._resyncMeshes();
  12937. return deleted;
  12938. };
  12939. };
  12940. Light.prototype._resyncMeshes = function () {
  12941. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  12942. var mesh = _a[_i];
  12943. mesh._resyncLighSource(this);
  12944. }
  12945. };
  12946. Light.prototype._markMeshesAsLightDirty = function () {
  12947. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  12948. var mesh = _a[_i];
  12949. if (mesh._lightSources.indexOf(this) !== -1) {
  12950. mesh._markSubMeshesAsLightDirty();
  12951. }
  12952. }
  12953. };
  12954. return Light;
  12955. }(BABYLON.Node));
  12956. //lightmapMode Consts
  12957. Light._LIGHTMAP_DEFAULT = 0;
  12958. Light._LIGHTMAP_SPECULAR = 1;
  12959. Light._LIGHTMAP_SHADOWSONLY = 2;
  12960. __decorate([
  12961. BABYLON.serializeAsColor3()
  12962. ], Light.prototype, "diffuse", void 0);
  12963. __decorate([
  12964. BABYLON.serializeAsColor3()
  12965. ], Light.prototype, "specular", void 0);
  12966. __decorate([
  12967. BABYLON.serialize()
  12968. ], Light.prototype, "intensity", void 0);
  12969. __decorate([
  12970. BABYLON.serialize()
  12971. ], Light.prototype, "range", void 0);
  12972. __decorate([
  12973. BABYLON.serialize("excludeWithLayerMask")
  12974. ], Light.prototype, "_excludeWithLayerMask", void 0);
  12975. __decorate([
  12976. BABYLON.serialize("includeOnlyWithLayerMask")
  12977. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  12978. __decorate([
  12979. BABYLON.serialize("lightmapMode")
  12980. ], Light.prototype, "_lightmapMode", void 0);
  12981. __decorate([
  12982. BABYLON.serialize()
  12983. ], Light.prototype, "radius", void 0);
  12984. BABYLON.Light = Light;
  12985. })(BABYLON || (BABYLON = {}));
  12986. //# sourceMappingURL=babylon.light.js.map
  12987. var BABYLON;
  12988. (function (BABYLON) {
  12989. var Camera = (function (_super) {
  12990. __extends(Camera, _super);
  12991. function Camera(name, position, scene) {
  12992. var _this = _super.call(this, name, scene) || this;
  12993. _this.upVector = BABYLON.Vector3.Up();
  12994. _this.orthoLeft = null;
  12995. _this.orthoRight = null;
  12996. _this.orthoBottom = null;
  12997. _this.orthoTop = null;
  12998. _this.fov = 0.8;
  12999. _this.minZ = 1.0;
  13000. _this.maxZ = 10000.0;
  13001. _this.inertia = 0.9;
  13002. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13003. _this.isIntermediate = false;
  13004. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13005. _this.layerMask = 0x0FFFFFFF;
  13006. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13007. // Camera rig members
  13008. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13009. _this._rigCameras = new Array();
  13010. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13011. // Cache
  13012. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13013. _this._projectionMatrix = new BABYLON.Matrix();
  13014. _this._doNotComputeProjectionMatrix = false;
  13015. _this._postProcesses = new Array();
  13016. _this._transformMatrix = BABYLON.Matrix.Zero();
  13017. _this._activeMeshes = new BABYLON.SmartArray(256);
  13018. _this._globalPosition = BABYLON.Vector3.Zero();
  13019. _this._refreshFrustumPlanes = true;
  13020. _this.getScene().addCamera(_this);
  13021. if (!_this.getScene().activeCamera) {
  13022. _this.getScene().activeCamera = _this;
  13023. }
  13024. _this.position = position;
  13025. return _this;
  13026. }
  13027. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13028. get: function () {
  13029. return Camera._PERSPECTIVE_CAMERA;
  13030. },
  13031. enumerable: true,
  13032. configurable: true
  13033. });
  13034. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13035. get: function () {
  13036. return Camera._ORTHOGRAPHIC_CAMERA;
  13037. },
  13038. enumerable: true,
  13039. configurable: true
  13040. });
  13041. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13042. get: function () {
  13043. return Camera._FOVMODE_VERTICAL_FIXED;
  13044. },
  13045. enumerable: true,
  13046. configurable: true
  13047. });
  13048. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13049. get: function () {
  13050. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13051. },
  13052. enumerable: true,
  13053. configurable: true
  13054. });
  13055. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13056. get: function () {
  13057. return Camera._RIG_MODE_NONE;
  13058. },
  13059. enumerable: true,
  13060. configurable: true
  13061. });
  13062. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13063. get: function () {
  13064. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13065. },
  13066. enumerable: true,
  13067. configurable: true
  13068. });
  13069. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13070. get: function () {
  13071. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13072. },
  13073. enumerable: true,
  13074. configurable: true
  13075. });
  13076. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13077. get: function () {
  13078. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13079. },
  13080. enumerable: true,
  13081. configurable: true
  13082. });
  13083. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13084. get: function () {
  13085. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13086. },
  13087. enumerable: true,
  13088. configurable: true
  13089. });
  13090. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13091. get: function () {
  13092. return Camera._RIG_MODE_VR;
  13093. },
  13094. enumerable: true,
  13095. configurable: true
  13096. });
  13097. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13098. get: function () {
  13099. return Camera._RIG_MODE_WEBVR;
  13100. },
  13101. enumerable: true,
  13102. configurable: true
  13103. });
  13104. Camera.prototype.getClassName = function () {
  13105. return "Camera";
  13106. };
  13107. /**
  13108. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13109. */
  13110. Camera.prototype.toString = function (fullDetails) {
  13111. var ret = "Name: " + this.name;
  13112. ret += ", type: " + this.getClassName();
  13113. if (this.animations) {
  13114. for (var i = 0; i < this.animations.length; i++) {
  13115. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13116. }
  13117. }
  13118. if (fullDetails) {
  13119. }
  13120. return ret;
  13121. };
  13122. Object.defineProperty(Camera.prototype, "globalPosition", {
  13123. get: function () {
  13124. return this._globalPosition;
  13125. },
  13126. enumerable: true,
  13127. configurable: true
  13128. });
  13129. Camera.prototype.getActiveMeshes = function () {
  13130. return this._activeMeshes;
  13131. };
  13132. Camera.prototype.isActiveMesh = function (mesh) {
  13133. return (this._activeMeshes.indexOf(mesh) !== -1);
  13134. };
  13135. //Cache
  13136. Camera.prototype._initCache = function () {
  13137. _super.prototype._initCache.call(this);
  13138. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13139. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13140. this._cache.mode = undefined;
  13141. this._cache.minZ = undefined;
  13142. this._cache.maxZ = undefined;
  13143. this._cache.fov = undefined;
  13144. this._cache.fovMode = undefined;
  13145. this._cache.aspectRatio = undefined;
  13146. this._cache.orthoLeft = undefined;
  13147. this._cache.orthoRight = undefined;
  13148. this._cache.orthoBottom = undefined;
  13149. this._cache.orthoTop = undefined;
  13150. this._cache.renderWidth = undefined;
  13151. this._cache.renderHeight = undefined;
  13152. };
  13153. Camera.prototype._updateCache = function (ignoreParentClass) {
  13154. if (!ignoreParentClass) {
  13155. _super.prototype._updateCache.call(this);
  13156. }
  13157. var engine = this.getEngine();
  13158. this._cache.position.copyFrom(this.position);
  13159. this._cache.upVector.copyFrom(this.upVector);
  13160. this._cache.mode = this.mode;
  13161. this._cache.minZ = this.minZ;
  13162. this._cache.maxZ = this.maxZ;
  13163. this._cache.fov = this.fov;
  13164. this._cache.fovMode = this.fovMode;
  13165. this._cache.aspectRatio = engine.getAspectRatio(this);
  13166. this._cache.orthoLeft = this.orthoLeft;
  13167. this._cache.orthoRight = this.orthoRight;
  13168. this._cache.orthoBottom = this.orthoBottom;
  13169. this._cache.orthoTop = this.orthoTop;
  13170. this._cache.renderWidth = engine.getRenderWidth();
  13171. this._cache.renderHeight = engine.getRenderHeight();
  13172. };
  13173. Camera.prototype._updateFromScene = function () {
  13174. this.updateCache();
  13175. this.update();
  13176. };
  13177. // Synchronized
  13178. Camera.prototype._isSynchronized = function () {
  13179. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13180. };
  13181. Camera.prototype._isSynchronizedViewMatrix = function () {
  13182. if (!_super.prototype._isSynchronized.call(this))
  13183. return false;
  13184. return this._cache.position.equals(this.position)
  13185. && this._cache.upVector.equals(this.upVector)
  13186. && this.isSynchronizedWithParent();
  13187. };
  13188. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13189. var check = this._cache.mode === this.mode
  13190. && this._cache.minZ === this.minZ
  13191. && this._cache.maxZ === this.maxZ;
  13192. if (!check) {
  13193. return false;
  13194. }
  13195. var engine = this.getEngine();
  13196. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13197. check = this._cache.fov === this.fov
  13198. && this._cache.fovMode === this.fovMode
  13199. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13200. }
  13201. else {
  13202. check = this._cache.orthoLeft === this.orthoLeft
  13203. && this._cache.orthoRight === this.orthoRight
  13204. && this._cache.orthoBottom === this.orthoBottom
  13205. && this._cache.orthoTop === this.orthoTop
  13206. && this._cache.renderWidth === engine.getRenderWidth()
  13207. && this._cache.renderHeight === engine.getRenderHeight();
  13208. }
  13209. return check;
  13210. };
  13211. // Controls
  13212. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13213. };
  13214. Camera.prototype.detachControl = function (element) {
  13215. };
  13216. Camera.prototype.update = function () {
  13217. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13218. this._updateRigCameras();
  13219. }
  13220. this._checkInputs();
  13221. };
  13222. Camera.prototype._checkInputs = function () {
  13223. };
  13224. Object.defineProperty(Camera.prototype, "rigCameras", {
  13225. get: function () {
  13226. return this._rigCameras;
  13227. },
  13228. enumerable: true,
  13229. configurable: true
  13230. });
  13231. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  13232. get: function () {
  13233. return this._rigPostProcess;
  13234. },
  13235. enumerable: true,
  13236. configurable: true
  13237. });
  13238. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13239. // invalidate framebuffer
  13240. if (this._postProcesses.length > 0) {
  13241. this._postProcesses[0].markTextureDirty();
  13242. }
  13243. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13244. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13245. var cam = this._rigCameras[i];
  13246. var rigPostProcess = cam._rigPostProcess;
  13247. // for VR rig, there does not have to be a post process
  13248. if (rigPostProcess) {
  13249. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13250. if (isPass) {
  13251. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13252. cam.isIntermediate = this._postProcesses.length === 0;
  13253. }
  13254. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13255. rigPostProcess.markTextureDirty();
  13256. }
  13257. else {
  13258. cam._postProcesses = this._postProcesses.slice(0);
  13259. }
  13260. }
  13261. };
  13262. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13263. if (insertAt === void 0) { insertAt = null; }
  13264. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13265. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13266. return 0;
  13267. }
  13268. if (insertAt == null || insertAt < 0) {
  13269. this._postProcesses.push(postProcess);
  13270. }
  13271. else {
  13272. this._postProcesses.splice(insertAt, 0, postProcess);
  13273. }
  13274. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13275. return this._postProcesses.indexOf(postProcess);
  13276. };
  13277. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13278. if (atIndices === void 0) { atIndices = null; }
  13279. var result = [];
  13280. var i;
  13281. var index;
  13282. if (!atIndices) {
  13283. var idx = this._postProcesses.indexOf(postProcess);
  13284. if (idx !== -1) {
  13285. this._postProcesses.splice(idx, 1);
  13286. }
  13287. }
  13288. else {
  13289. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13290. // iterate descending, so can just splice as we go
  13291. for (i = atIndices.length - 1; i >= 0; i--) {
  13292. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13293. result.push(i);
  13294. continue;
  13295. }
  13296. index = atIndices[i];
  13297. this._postProcesses.splice(index, 1);
  13298. }
  13299. }
  13300. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13301. return result;
  13302. };
  13303. Camera.prototype.getWorldMatrix = function () {
  13304. if (!this._worldMatrix) {
  13305. this._worldMatrix = BABYLON.Matrix.Identity();
  13306. }
  13307. var viewMatrix = this.getViewMatrix();
  13308. viewMatrix.invertToRef(this._worldMatrix);
  13309. return this._worldMatrix;
  13310. };
  13311. Camera.prototype._getViewMatrix = function () {
  13312. return BABYLON.Matrix.Identity();
  13313. };
  13314. Camera.prototype.getViewMatrix = function (force) {
  13315. this._computedViewMatrix = this._computeViewMatrix(force);
  13316. if (!force && this._isSynchronizedViewMatrix()) {
  13317. return this._computedViewMatrix;
  13318. }
  13319. this._refreshFrustumPlanes = true;
  13320. if (!this.parent || !this.parent.getWorldMatrix) {
  13321. this._globalPosition.copyFrom(this.position);
  13322. }
  13323. else {
  13324. if (!this._worldMatrix) {
  13325. this._worldMatrix = BABYLON.Matrix.Identity();
  13326. }
  13327. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13328. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13329. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13330. this._computedViewMatrix.invert();
  13331. this._markSyncedWithParent();
  13332. }
  13333. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  13334. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  13335. }
  13336. this._currentRenderId = this.getScene().getRenderId();
  13337. return this._computedViewMatrix;
  13338. };
  13339. Camera.prototype._computeViewMatrix = function (force) {
  13340. if (!force && this._isSynchronizedViewMatrix()) {
  13341. return this._computedViewMatrix;
  13342. }
  13343. this._computedViewMatrix = this._getViewMatrix();
  13344. this._currentRenderId = this.getScene().getRenderId();
  13345. return this._computedViewMatrix;
  13346. };
  13347. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13348. this._doNotComputeProjectionMatrix = true;
  13349. if (projection !== undefined) {
  13350. this._projectionMatrix = projection;
  13351. }
  13352. };
  13353. ;
  13354. Camera.prototype.unfreezeProjectionMatrix = function () {
  13355. this._doNotComputeProjectionMatrix = false;
  13356. };
  13357. ;
  13358. Camera.prototype.getProjectionMatrix = function (force) {
  13359. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13360. return this._projectionMatrix;
  13361. }
  13362. this._refreshFrustumPlanes = true;
  13363. var engine = this.getEngine();
  13364. var scene = this.getScene();
  13365. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13366. if (this.minZ <= 0) {
  13367. this.minZ = 0.1;
  13368. }
  13369. if (scene.useRightHandedSystem) {
  13370. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13371. }
  13372. else {
  13373. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13374. }
  13375. return this._projectionMatrix;
  13376. }
  13377. var halfWidth = engine.getRenderWidth() / 2.0;
  13378. var halfHeight = engine.getRenderHeight() / 2.0;
  13379. if (scene.useRightHandedSystem) {
  13380. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13381. }
  13382. else {
  13383. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13384. }
  13385. return this._projectionMatrix;
  13386. };
  13387. Camera.prototype.getTranformationMatrix = function () {
  13388. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13389. return this._transformMatrix;
  13390. };
  13391. Camera.prototype.updateFrustumPlanes = function () {
  13392. if (!this._refreshFrustumPlanes) {
  13393. return;
  13394. }
  13395. this.getTranformationMatrix();
  13396. if (!this._frustumPlanes) {
  13397. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13398. }
  13399. else {
  13400. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13401. }
  13402. this._refreshFrustumPlanes = false;
  13403. };
  13404. Camera.prototype.isInFrustum = function (target) {
  13405. this.updateFrustumPlanes();
  13406. return target.isInFrustum(this._frustumPlanes);
  13407. };
  13408. Camera.prototype.isCompletelyInFrustum = function (target) {
  13409. this.updateFrustumPlanes();
  13410. return target.isCompletelyInFrustum(this._frustumPlanes);
  13411. };
  13412. Camera.prototype.dispose = function () {
  13413. // Animations
  13414. this.getScene().stopAnimation(this);
  13415. // Remove from scene
  13416. this.getScene().removeCamera(this);
  13417. while (this._rigCameras.length > 0) {
  13418. this._rigCameras.pop().dispose();
  13419. }
  13420. // Postprocesses
  13421. var i = this._postProcesses.length;
  13422. while (--i >= 0) {
  13423. this._postProcesses[i].dispose(this);
  13424. }
  13425. _super.prototype.dispose.call(this);
  13426. };
  13427. // ---- Camera rigs section ----
  13428. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13429. while (this._rigCameras.length > 0) {
  13430. this._rigCameras.pop().dispose();
  13431. }
  13432. this.cameraRigMode = mode;
  13433. this._cameraRigParams = {};
  13434. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13435. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13436. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13437. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13438. // create the rig cameras, unless none
  13439. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13440. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13441. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13442. }
  13443. switch (this.cameraRigMode) {
  13444. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13445. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13446. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13447. break;
  13448. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13449. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13450. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13451. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13452. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13453. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13454. break;
  13455. case Camera.RIG_MODE_VR:
  13456. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13457. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13458. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13459. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13460. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13461. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13462. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13463. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13464. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13465. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13466. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13467. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13468. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13469. if (metrics.compensateDistortion) {
  13470. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13471. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13472. }
  13473. break;
  13474. case Camera.RIG_MODE_WEBVR:
  13475. if (rigParams.vrDisplay) {
  13476. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13477. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13478. //Left eye
  13479. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13480. this._rigCameras[0].setCameraRigParameter("left", true);
  13481. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  13482. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  13483. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13484. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13485. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13486. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13487. this._rigCameras[0].parent = this;
  13488. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13489. //Right eye
  13490. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13491. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  13492. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  13493. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13494. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13495. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13496. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13497. this._rigCameras[1].parent = this;
  13498. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  13499. }
  13500. break;
  13501. }
  13502. this._cascadePostProcessesToRigCams();
  13503. this.
  13504. update();
  13505. };
  13506. Camera.prototype._getVRProjectionMatrix = function () {
  13507. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13508. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13509. return this._projectionMatrix;
  13510. };
  13511. Camera.prototype._updateCameraRotationMatrix = function () {
  13512. //Here for WebVR
  13513. };
  13514. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  13515. //Here for WebVR
  13516. };
  13517. /**
  13518. * This function MUST be overwritten by the different WebVR cameras available.
  13519. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13520. */
  13521. Camera.prototype._getWebVRProjectionMatrix = function () {
  13522. return BABYLON.Matrix.Identity();
  13523. };
  13524. /**
  13525. * This function MUST be overwritten by the different WebVR cameras available.
  13526. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13527. */
  13528. Camera.prototype._getWebVRViewMatrix = function () {
  13529. return BABYLON.Matrix.Identity();
  13530. };
  13531. Camera.prototype.setCameraRigParameter = function (name, value) {
  13532. if (!this._cameraRigParams) {
  13533. this._cameraRigParams = {};
  13534. }
  13535. this._cameraRigParams[name] = value;
  13536. //provisionnally:
  13537. if (name === "interaxialDistance") {
  13538. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13539. }
  13540. };
  13541. /**
  13542. * needs to be overridden by children so sub has required properties to be copied
  13543. */
  13544. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13545. return null;
  13546. };
  13547. /**
  13548. * May need to be overridden by children
  13549. */
  13550. Camera.prototype._updateRigCameras = function () {
  13551. for (var i = 0; i < this._rigCameras.length; i++) {
  13552. this._rigCameras[i].minZ = this.minZ;
  13553. this._rigCameras[i].maxZ = this.maxZ;
  13554. this._rigCameras[i].fov = this.fov;
  13555. }
  13556. // only update viewport when ANAGLYPH
  13557. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13558. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13559. }
  13560. };
  13561. Camera.prototype._setupInputs = function () {
  13562. };
  13563. Camera.prototype.serialize = function () {
  13564. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13565. // Type
  13566. serializationObject.type = this.getClassName();
  13567. // Parent
  13568. if (this.parent) {
  13569. serializationObject.parentId = this.parent.id;
  13570. }
  13571. if (this.inputs) {
  13572. this.inputs.serialize(serializationObject);
  13573. }
  13574. // Animations
  13575. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13576. serializationObject.ranges = this.serializeAnimationRanges();
  13577. return serializationObject;
  13578. };
  13579. Camera.prototype.clone = function (name) {
  13580. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13581. };
  13582. Camera.prototype.getDirection = function (localAxis) {
  13583. var result = BABYLON.Vector3.Zero();
  13584. this.getDirectionToRef(localAxis, result);
  13585. return result;
  13586. };
  13587. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13588. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13589. };
  13590. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13591. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13592. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13593. switch (type) {
  13594. case "ArcRotateCamera":
  13595. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13596. case "DeviceOrientationCamera":
  13597. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13598. case "FollowCamera":
  13599. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13600. case "ArcFollowCamera":
  13601. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13602. case "GamepadCamera":
  13603. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13604. case "TouchCamera":
  13605. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13606. case "VirtualJoysticksCamera":
  13607. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13608. case "WebVRFreeCamera":
  13609. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13610. case "WebVRGamepadCamera":
  13611. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13612. case "VRDeviceOrientationFreeCamera":
  13613. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13614. case "VRDeviceOrientationGamepadCamera":
  13615. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13616. case "AnaglyphArcRotateCamera":
  13617. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13618. case "AnaglyphFreeCamera":
  13619. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13620. case "AnaglyphGamepadCamera":
  13621. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13622. case "AnaglyphUniversalCamera":
  13623. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13624. case "StereoscopicArcRotateCamera":
  13625. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13626. case "StereoscopicFreeCamera":
  13627. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13628. case "StereoscopicGamepadCamera":
  13629. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13630. case "StereoscopicUniversalCamera":
  13631. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13632. case "FreeCamera":
  13633. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13634. default:
  13635. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13636. }
  13637. };
  13638. Camera.Parse = function (parsedCamera, scene) {
  13639. var type = parsedCamera.type;
  13640. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13641. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13642. // Parent
  13643. if (parsedCamera.parentId) {
  13644. camera._waitingParentId = parsedCamera.parentId;
  13645. }
  13646. //If camera has an input manager, let it parse inputs settings
  13647. if (camera.inputs) {
  13648. camera.inputs.parse(parsedCamera);
  13649. camera._setupInputs();
  13650. }
  13651. // Target
  13652. if (parsedCamera.target) {
  13653. if (camera.setTarget) {
  13654. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13655. }
  13656. }
  13657. // Apply 3d rig, when found
  13658. if (parsedCamera.cameraRigMode) {
  13659. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13660. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13661. }
  13662. // Animations
  13663. if (parsedCamera.animations) {
  13664. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13665. var parsedAnimation = parsedCamera.animations[animationIndex];
  13666. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13667. }
  13668. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13669. }
  13670. if (parsedCamera.autoAnimate) {
  13671. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13672. }
  13673. return camera;
  13674. };
  13675. return Camera;
  13676. }(BABYLON.Node));
  13677. // Statics
  13678. Camera._PERSPECTIVE_CAMERA = 0;
  13679. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13680. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13681. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13682. Camera._RIG_MODE_NONE = 0;
  13683. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13684. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13685. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13686. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13687. Camera._RIG_MODE_VR = 20;
  13688. Camera._RIG_MODE_WEBVR = 21;
  13689. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13690. __decorate([
  13691. BABYLON.serializeAsVector3()
  13692. ], Camera.prototype, "position", void 0);
  13693. __decorate([
  13694. BABYLON.serializeAsVector3()
  13695. ], Camera.prototype, "upVector", void 0);
  13696. __decorate([
  13697. BABYLON.serialize()
  13698. ], Camera.prototype, "orthoLeft", void 0);
  13699. __decorate([
  13700. BABYLON.serialize()
  13701. ], Camera.prototype, "orthoRight", void 0);
  13702. __decorate([
  13703. BABYLON.serialize()
  13704. ], Camera.prototype, "orthoBottom", void 0);
  13705. __decorate([
  13706. BABYLON.serialize()
  13707. ], Camera.prototype, "orthoTop", void 0);
  13708. __decorate([
  13709. BABYLON.serialize()
  13710. ], Camera.prototype, "fov", void 0);
  13711. __decorate([
  13712. BABYLON.serialize()
  13713. ], Camera.prototype, "minZ", void 0);
  13714. __decorate([
  13715. BABYLON.serialize()
  13716. ], Camera.prototype, "maxZ", void 0);
  13717. __decorate([
  13718. BABYLON.serialize()
  13719. ], Camera.prototype, "inertia", void 0);
  13720. __decorate([
  13721. BABYLON.serialize()
  13722. ], Camera.prototype, "mode", void 0);
  13723. __decorate([
  13724. BABYLON.serialize()
  13725. ], Camera.prototype, "layerMask", void 0);
  13726. __decorate([
  13727. BABYLON.serialize()
  13728. ], Camera.prototype, "fovMode", void 0);
  13729. __decorate([
  13730. BABYLON.serialize()
  13731. ], Camera.prototype, "cameraRigMode", void 0);
  13732. __decorate([
  13733. BABYLON.serialize()
  13734. ], Camera.prototype, "interaxialDistance", void 0);
  13735. __decorate([
  13736. BABYLON.serialize()
  13737. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13738. BABYLON.Camera = Camera;
  13739. })(BABYLON || (BABYLON = {}));
  13740. //# sourceMappingURL=babylon.camera.js.map
  13741. var BABYLON;
  13742. (function (BABYLON) {
  13743. var RenderingManager = (function () {
  13744. function RenderingManager(scene) {
  13745. this._renderingGroups = new Array();
  13746. this._autoClearDepthStencil = {};
  13747. this._customOpaqueSortCompareFn = {};
  13748. this._customAlphaTestSortCompareFn = {};
  13749. this._customTransparentSortCompareFn = {};
  13750. this._renderinGroupInfo = null;
  13751. this._scene = scene;
  13752. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  13753. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  13754. }
  13755. }
  13756. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  13757. if (depth === void 0) { depth = true; }
  13758. if (stencil === void 0) { stencil = true; }
  13759. if (this._depthStencilBufferAlreadyCleaned) {
  13760. return;
  13761. }
  13762. this._scene.getEngine().clear(null, false, depth, stencil);
  13763. this._depthStencilBufferAlreadyCleaned = true;
  13764. };
  13765. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13766. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  13767. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  13768. var info = null;
  13769. if (observable) {
  13770. if (!this._renderinGroupInfo) {
  13771. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  13772. }
  13773. info = this._renderinGroupInfo;
  13774. info.scene = this._scene;
  13775. info.camera = this._scene.activeCamera;
  13776. }
  13777. // Dispatch sprites
  13778. if (renderSprites) {
  13779. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  13780. var manager = this._scene.spriteManagers[index];
  13781. this.dispatchSprites(manager);
  13782. }
  13783. }
  13784. // Render
  13785. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13786. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  13787. var renderingGroup = this._renderingGroups[index];
  13788. if (!renderingGroup && !observable)
  13789. continue;
  13790. this._currentIndex = index;
  13791. var renderingGroupMask = 0;
  13792. // Fire PRECLEAR stage
  13793. if (observable) {
  13794. renderingGroupMask = Math.pow(2, index);
  13795. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  13796. info.renderingGroupId = index;
  13797. observable.notifyObservers(info, renderingGroupMask);
  13798. }
  13799. // Clear depth/stencil if needed
  13800. var autoClear = this._autoClearDepthStencil[index];
  13801. if (autoClear && autoClear.autoClear) {
  13802. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  13803. }
  13804. if (observable) {
  13805. // Fire PREOPAQUE stage
  13806. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  13807. observable.notifyObservers(info, renderingGroupMask);
  13808. // Fire PRETRANSPARENT stage
  13809. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  13810. observable.notifyObservers(info, renderingGroupMask);
  13811. }
  13812. if (renderingGroup)
  13813. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  13814. // Fire POSTTRANSPARENT stage
  13815. if (observable) {
  13816. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  13817. observable.notifyObservers(info, renderingGroupMask);
  13818. }
  13819. }
  13820. };
  13821. RenderingManager.prototype.reset = function () {
  13822. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13823. var renderingGroup = this._renderingGroups[index];
  13824. if (renderingGroup) {
  13825. renderingGroup.prepare();
  13826. }
  13827. }
  13828. };
  13829. RenderingManager.prototype.dispose = function () {
  13830. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13831. var renderingGroup = this._renderingGroups[index];
  13832. if (renderingGroup) {
  13833. renderingGroup.dispose();
  13834. }
  13835. }
  13836. this._renderingGroups.length = 0;
  13837. };
  13838. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  13839. if (!this._renderingGroups[renderingGroupId]) {
  13840. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  13841. }
  13842. };
  13843. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  13844. var renderingGroupId = spriteManager.renderingGroupId || 0;
  13845. this._prepareRenderingGroup(renderingGroupId);
  13846. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  13847. };
  13848. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  13849. var renderingGroupId = particleSystem.renderingGroupId || 0;
  13850. this._prepareRenderingGroup(renderingGroupId);
  13851. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  13852. };
  13853. RenderingManager.prototype.dispatch = function (subMesh) {
  13854. var mesh = subMesh.getMesh();
  13855. var renderingGroupId = mesh.renderingGroupId || 0;
  13856. this._prepareRenderingGroup(renderingGroupId);
  13857. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13858. };
  13859. /**
  13860. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  13861. * This allowed control for front to back rendering or reversly depending of the special needs.
  13862. *
  13863. * @param renderingGroupId The rendering group id corresponding to its index
  13864. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  13865. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  13866. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  13867. */
  13868. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  13869. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  13870. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  13871. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  13872. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  13873. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  13874. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  13875. if (this._renderingGroups[renderingGroupId]) {
  13876. var group = this._renderingGroups[renderingGroupId];
  13877. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  13878. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  13879. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  13880. }
  13881. };
  13882. /**
  13883. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  13884. *
  13885. * @param renderingGroupId The rendering group id corresponding to its index
  13886. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  13887. * @param depth Automatically clears depth between groups if true and autoClear is true.
  13888. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  13889. */
  13890. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  13891. if (depth === void 0) { depth = true; }
  13892. if (stencil === void 0) { stencil = true; }
  13893. this._autoClearDepthStencil[renderingGroupId] = {
  13894. autoClear: autoClearDepthStencil,
  13895. depth: depth,
  13896. stencil: stencil
  13897. };
  13898. };
  13899. return RenderingManager;
  13900. }());
  13901. /**
  13902. * The max id used for rendering groups (not included)
  13903. */
  13904. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13905. /**
  13906. * The min id used for rendering groups (included)
  13907. */
  13908. RenderingManager.MIN_RENDERINGGROUPS = 0;
  13909. BABYLON.RenderingManager = RenderingManager;
  13910. })(BABYLON || (BABYLON = {}));
  13911. //# sourceMappingURL=babylon.renderingManager.js.map
  13912. var BABYLON;
  13913. (function (BABYLON) {
  13914. var RenderingGroup = (function () {
  13915. /**
  13916. * Creates a new rendering group.
  13917. * @param index The rendering group index
  13918. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  13919. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  13920. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  13921. */
  13922. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  13923. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  13924. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  13925. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  13926. this.index = index;
  13927. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13928. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13929. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13930. this._particleSystems = new BABYLON.SmartArray(256);
  13931. this._spriteManagers = new BABYLON.SmartArray(256);
  13932. this._scene = scene;
  13933. this.opaqueSortCompareFn = opaqueSortCompareFn;
  13934. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  13935. this.transparentSortCompareFn = transparentSortCompareFn;
  13936. }
  13937. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  13938. /**
  13939. * Set the opaque sort comparison function.
  13940. * If null the sub meshes will be render in the order they were created
  13941. */
  13942. set: function (value) {
  13943. this._opaqueSortCompareFn = value;
  13944. if (value) {
  13945. this._renderOpaque = this.renderOpaqueSorted;
  13946. }
  13947. else {
  13948. this._renderOpaque = RenderingGroup.renderUnsorted;
  13949. }
  13950. },
  13951. enumerable: true,
  13952. configurable: true
  13953. });
  13954. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  13955. /**
  13956. * Set the alpha test sort comparison function.
  13957. * If null the sub meshes will be render in the order they were created
  13958. */
  13959. set: function (value) {
  13960. this._alphaTestSortCompareFn = value;
  13961. if (value) {
  13962. this._renderAlphaTest = this.renderAlphaTestSorted;
  13963. }
  13964. else {
  13965. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  13966. }
  13967. },
  13968. enumerable: true,
  13969. configurable: true
  13970. });
  13971. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  13972. /**
  13973. * Set the transparent sort comparison function.
  13974. * If null the sub meshes will be render in the order they were created
  13975. */
  13976. set: function (value) {
  13977. if (value) {
  13978. this._transparentSortCompareFn = value;
  13979. }
  13980. else {
  13981. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  13982. }
  13983. this._renderTransparent = this.renderTransparentSorted;
  13984. },
  13985. enumerable: true,
  13986. configurable: true
  13987. });
  13988. /**
  13989. * Render all the sub meshes contained in the group.
  13990. * @param customRenderFunction Used to override the default render behaviour of the group.
  13991. * @returns true if rendered some submeshes.
  13992. */
  13993. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  13994. if (customRenderFunction) {
  13995. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13996. return;
  13997. }
  13998. var engine = this._scene.getEngine();
  13999. // Opaque
  14000. if (this._opaqueSubMeshes.length !== 0) {
  14001. this._renderOpaque(this._opaqueSubMeshes);
  14002. }
  14003. // Alpha test
  14004. if (this._alphaTestSubMeshes.length !== 0) {
  14005. engine.setAlphaTesting(true);
  14006. this._renderAlphaTest(this._alphaTestSubMeshes);
  14007. engine.setAlphaTesting(false);
  14008. }
  14009. var stencilState = engine.getStencilBuffer();
  14010. engine.setStencilBuffer(false);
  14011. // Sprites
  14012. if (renderSprites) {
  14013. this._renderSprites();
  14014. }
  14015. // Particles
  14016. if (renderParticles) {
  14017. this._renderParticles(activeMeshes);
  14018. }
  14019. if (this.onBeforeTransparentRendering) {
  14020. this.onBeforeTransparentRendering();
  14021. }
  14022. // Transparent
  14023. if (this._transparentSubMeshes.length !== 0) {
  14024. this._renderTransparent(this._transparentSubMeshes);
  14025. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14026. }
  14027. engine.setStencilBuffer(stencilState);
  14028. };
  14029. /**
  14030. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14031. * @param subMeshes The submeshes to render
  14032. */
  14033. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14034. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14035. };
  14036. /**
  14037. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14038. * @param subMeshes The submeshes to render
  14039. */
  14040. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14041. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14042. };
  14043. /**
  14044. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14045. * @param subMeshes The submeshes to render
  14046. */
  14047. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14048. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14049. };
  14050. /**
  14051. * Renders the submeshes in a specified order.
  14052. * @param subMeshes The submeshes to sort before render
  14053. * @param sortCompareFn The comparison function use to sort
  14054. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14055. * @param transparent Specifies to activate blending if true
  14056. */
  14057. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14058. var subIndex = 0;
  14059. var subMesh;
  14060. for (; subIndex < subMeshes.length; subIndex++) {
  14061. subMesh = subMeshes.data[subIndex];
  14062. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14063. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14064. }
  14065. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14066. sortedArray.sort(sortCompareFn);
  14067. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14068. subMesh = sortedArray[subIndex];
  14069. subMesh.render(transparent);
  14070. }
  14071. };
  14072. /**
  14073. * Renders the submeshes in the order they were dispatched (no sort applied).
  14074. * @param subMeshes The submeshes to render
  14075. */
  14076. RenderingGroup.renderUnsorted = function (subMeshes) {
  14077. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14078. var submesh = subMeshes.data[subIndex];
  14079. submesh.render(false);
  14080. }
  14081. };
  14082. /**
  14083. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14084. * are rendered back to front if in the same alpha index.
  14085. *
  14086. * @param a The first submesh
  14087. * @param b The second submesh
  14088. * @returns The result of the comparison
  14089. */
  14090. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14091. // Alpha index first
  14092. if (a._alphaIndex > b._alphaIndex) {
  14093. return 1;
  14094. }
  14095. if (a._alphaIndex < b._alphaIndex) {
  14096. return -1;
  14097. }
  14098. // Then distance to camera
  14099. return RenderingGroup.backToFrontSortCompare(a, b);
  14100. };
  14101. /**
  14102. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14103. * are rendered back to front.
  14104. *
  14105. * @param a The first submesh
  14106. * @param b The second submesh
  14107. * @returns The result of the comparison
  14108. */
  14109. RenderingGroup.backToFrontSortCompare = function (a, b) {
  14110. // Then distance to camera
  14111. if (a._distanceToCamera < b._distanceToCamera) {
  14112. return 1;
  14113. }
  14114. if (a._distanceToCamera > b._distanceToCamera) {
  14115. return -1;
  14116. }
  14117. return 0;
  14118. };
  14119. /**
  14120. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14121. * are rendered front to back (prevent overdraw).
  14122. *
  14123. * @param a The first submesh
  14124. * @param b The second submesh
  14125. * @returns The result of the comparison
  14126. */
  14127. RenderingGroup.frontToBackSortCompare = function (a, b) {
  14128. // Then distance to camera
  14129. if (a._distanceToCamera < b._distanceToCamera) {
  14130. return -1;
  14131. }
  14132. if (a._distanceToCamera > b._distanceToCamera) {
  14133. return 1;
  14134. }
  14135. return 0;
  14136. };
  14137. /**
  14138. * Resets the different lists of submeshes to prepare a new frame.
  14139. */
  14140. RenderingGroup.prototype.prepare = function () {
  14141. this._opaqueSubMeshes.reset();
  14142. this._transparentSubMeshes.reset();
  14143. this._alphaTestSubMeshes.reset();
  14144. this._particleSystems.reset();
  14145. this._spriteManagers.reset();
  14146. };
  14147. RenderingGroup.prototype.dispose = function () {
  14148. this._opaqueSubMeshes.dispose();
  14149. this._transparentSubMeshes.dispose();
  14150. this._alphaTestSubMeshes.dispose();
  14151. this._particleSystems.dispose();
  14152. this._spriteManagers.dispose();
  14153. };
  14154. /**
  14155. * Inserts the submesh in its correct queue depending on its material.
  14156. * @param subMesh The submesh to dispatch
  14157. */
  14158. RenderingGroup.prototype.dispatch = function (subMesh) {
  14159. var material = subMesh.getMaterial();
  14160. var mesh = subMesh.getMesh();
  14161. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14162. this._transparentSubMeshes.push(subMesh);
  14163. }
  14164. else if (material.needAlphaTesting()) {
  14165. this._alphaTestSubMeshes.push(subMesh);
  14166. }
  14167. else {
  14168. this._opaqueSubMeshes.push(subMesh); // Opaque
  14169. }
  14170. };
  14171. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  14172. this._spriteManagers.push(spriteManager);
  14173. };
  14174. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  14175. this._particleSystems.push(particleSystem);
  14176. };
  14177. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  14178. if (this._particleSystems.length === 0) {
  14179. return;
  14180. }
  14181. // Particles
  14182. var activeCamera = this._scene.activeCamera;
  14183. this._scene._particlesDuration.beginMonitoring();
  14184. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14185. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14186. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14187. continue;
  14188. }
  14189. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14190. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14191. }
  14192. }
  14193. this._scene._particlesDuration.endMonitoring(false);
  14194. };
  14195. RenderingGroup.prototype._renderSprites = function () {
  14196. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  14197. return;
  14198. }
  14199. // Sprites
  14200. var activeCamera = this._scene.activeCamera;
  14201. this._scene._spritesDuration.beginMonitoring();
  14202. for (var id = 0; id < this._spriteManagers.length; id++) {
  14203. var spriteManager = this._spriteManagers.data[id];
  14204. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14205. spriteManager.render();
  14206. }
  14207. }
  14208. this._scene._spritesDuration.endMonitoring(false);
  14209. };
  14210. return RenderingGroup;
  14211. }());
  14212. BABYLON.RenderingGroup = RenderingGroup;
  14213. })(BABYLON || (BABYLON = {}));
  14214. //# sourceMappingURL=babylon.renderingGroup.js.map
  14215. var BABYLON;
  14216. (function (BABYLON) {
  14217. var ClickInfo = (function () {
  14218. function ClickInfo() {
  14219. this._singleClick = false;
  14220. this._doubleClick = false;
  14221. this._hasSwiped = false;
  14222. this._ignore = false;
  14223. }
  14224. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  14225. get: function () {
  14226. return this._singleClick;
  14227. },
  14228. set: function (b) {
  14229. this._singleClick = b;
  14230. },
  14231. enumerable: true,
  14232. configurable: true
  14233. });
  14234. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  14235. get: function () {
  14236. return this._doubleClick;
  14237. },
  14238. set: function (b) {
  14239. this._doubleClick = b;
  14240. },
  14241. enumerable: true,
  14242. configurable: true
  14243. });
  14244. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  14245. get: function () {
  14246. return this._hasSwiped;
  14247. },
  14248. set: function (b) {
  14249. this._hasSwiped = b;
  14250. },
  14251. enumerable: true,
  14252. configurable: true
  14253. });
  14254. Object.defineProperty(ClickInfo.prototype, "ignore", {
  14255. get: function () {
  14256. return this._ignore;
  14257. },
  14258. set: function (b) {
  14259. this._ignore = b;
  14260. },
  14261. enumerable: true,
  14262. configurable: true
  14263. });
  14264. return ClickInfo;
  14265. }());
  14266. var PointerEventTypes = (function () {
  14267. function PointerEventTypes() {
  14268. }
  14269. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14270. get: function () {
  14271. return PointerEventTypes._POINTERDOWN;
  14272. },
  14273. enumerable: true,
  14274. configurable: true
  14275. });
  14276. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14277. get: function () {
  14278. return PointerEventTypes._POINTERUP;
  14279. },
  14280. enumerable: true,
  14281. configurable: true
  14282. });
  14283. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14284. get: function () {
  14285. return PointerEventTypes._POINTERMOVE;
  14286. },
  14287. enumerable: true,
  14288. configurable: true
  14289. });
  14290. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14291. get: function () {
  14292. return PointerEventTypes._POINTERWHEEL;
  14293. },
  14294. enumerable: true,
  14295. configurable: true
  14296. });
  14297. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14298. get: function () {
  14299. return PointerEventTypes._POINTERPICK;
  14300. },
  14301. enumerable: true,
  14302. configurable: true
  14303. });
  14304. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  14305. get: function () {
  14306. return PointerEventTypes._POINTERTAP;
  14307. },
  14308. enumerable: true,
  14309. configurable: true
  14310. });
  14311. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  14312. get: function () {
  14313. return PointerEventTypes._POINTERDOUBLETAP;
  14314. },
  14315. enumerable: true,
  14316. configurable: true
  14317. });
  14318. return PointerEventTypes;
  14319. }());
  14320. PointerEventTypes._POINTERDOWN = 0x01;
  14321. PointerEventTypes._POINTERUP = 0x02;
  14322. PointerEventTypes._POINTERMOVE = 0x04;
  14323. PointerEventTypes._POINTERWHEEL = 0x08;
  14324. PointerEventTypes._POINTERPICK = 0x10;
  14325. PointerEventTypes._POINTERTAP = 0x20;
  14326. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  14327. BABYLON.PointerEventTypes = PointerEventTypes;
  14328. var PointerInfoBase = (function () {
  14329. function PointerInfoBase(type, event) {
  14330. this.type = type;
  14331. this.event = event;
  14332. }
  14333. return PointerInfoBase;
  14334. }());
  14335. BABYLON.PointerInfoBase = PointerInfoBase;
  14336. /**
  14337. * This class is used to store pointer related info for the onPrePointerObservable event.
  14338. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14339. */
  14340. var PointerInfoPre = (function (_super) {
  14341. __extends(PointerInfoPre, _super);
  14342. function PointerInfoPre(type, event, localX, localY) {
  14343. var _this = _super.call(this, type, event) || this;
  14344. _this.skipOnPointerObservable = false;
  14345. _this.localPosition = new BABYLON.Vector2(localX, localY);
  14346. return _this;
  14347. }
  14348. return PointerInfoPre;
  14349. }(PointerInfoBase));
  14350. BABYLON.PointerInfoPre = PointerInfoPre;
  14351. /**
  14352. * This type contains all the data related to a pointer event in Babylon.js.
  14353. * 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.
  14354. */
  14355. var PointerInfo = (function (_super) {
  14356. __extends(PointerInfo, _super);
  14357. function PointerInfo(type, event, pickInfo) {
  14358. var _this = _super.call(this, type, event) || this;
  14359. _this.pickInfo = pickInfo;
  14360. return _this;
  14361. }
  14362. return PointerInfo;
  14363. }(PointerInfoBase));
  14364. BABYLON.PointerInfo = PointerInfo;
  14365. /**
  14366. * This class is used by the onRenderingGroupObservable
  14367. */
  14368. var RenderingGroupInfo = (function () {
  14369. function RenderingGroupInfo() {
  14370. }
  14371. return RenderingGroupInfo;
  14372. }());
  14373. /**
  14374. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  14375. * This stage will be fired no matter what
  14376. */
  14377. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  14378. /**
  14379. * Called before opaque object are rendered.
  14380. * This stage will be fired only if there's 3D Opaque content to render
  14381. */
  14382. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  14383. /**
  14384. * Called after the opaque objects are rendered and before the transparent ones
  14385. * This stage will be fired only if there's 3D transparent content to render
  14386. */
  14387. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  14388. /**
  14389. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  14390. * This stage will be fired no matter what
  14391. */
  14392. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  14393. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  14394. /**
  14395. * Represents a scene to be rendered by the engine.
  14396. * @see http://doc.babylonjs.com/page.php?p=21911
  14397. */
  14398. var Scene = (function () {
  14399. /**
  14400. * @constructor
  14401. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14402. */
  14403. function Scene(engine) {
  14404. // Members
  14405. this.autoClear = true;
  14406. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  14407. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14408. this.forceWireframe = false;
  14409. this._forcePointsCloud = false;
  14410. this.forceShowBoundingBoxes = false;
  14411. this.animationsEnabled = true;
  14412. this.constantlyUpdateMeshUnderPointer = false;
  14413. this.useRightHandedSystem = false;
  14414. this.hoverCursor = "pointer";
  14415. // Metadata
  14416. this.metadata = null;
  14417. // Events
  14418. /**
  14419. * An event triggered when the scene is disposed.
  14420. * @type {BABYLON.Observable}
  14421. */
  14422. this.onDisposeObservable = new BABYLON.Observable();
  14423. /**
  14424. * An event triggered before rendering the scene
  14425. * @type {BABYLON.Observable}
  14426. */
  14427. this.onBeforeRenderObservable = new BABYLON.Observable();
  14428. /**
  14429. * An event triggered after rendering the scene
  14430. * @type {BABYLON.Observable}
  14431. */
  14432. this.onAfterRenderObservable = new BABYLON.Observable();
  14433. /**
  14434. * An event triggered when the scene is ready
  14435. * @type {BABYLON.Observable}
  14436. */
  14437. this.onReadyObservable = new BABYLON.Observable();
  14438. /**
  14439. * An event triggered before rendering a camera
  14440. * @type {BABYLON.Observable}
  14441. */
  14442. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14443. /**
  14444. * An event triggered after rendering a camera
  14445. * @type {BABYLON.Observable}
  14446. */
  14447. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14448. /**
  14449. * An event triggered when a camera is created
  14450. * @type {BABYLON.Observable}
  14451. */
  14452. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14453. /**
  14454. * An event triggered when a camera is removed
  14455. * @type {BABYLON.Observable}
  14456. */
  14457. this.onCameraRemovedObservable = new BABYLON.Observable();
  14458. /**
  14459. * An event triggered when a light is created
  14460. * @type {BABYLON.Observable}
  14461. */
  14462. this.onNewLightAddedObservable = new BABYLON.Observable();
  14463. /**
  14464. * An event triggered when a light is removed
  14465. * @type {BABYLON.Observable}
  14466. */
  14467. this.onLightRemovedObservable = new BABYLON.Observable();
  14468. /**
  14469. * An event triggered when a geometry is created
  14470. * @type {BABYLON.Observable}
  14471. */
  14472. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14473. /**
  14474. * An event triggered when a geometry is removed
  14475. * @type {BABYLON.Observable}
  14476. */
  14477. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14478. /**
  14479. * An event triggered when a mesh is created
  14480. * @type {BABYLON.Observable}
  14481. */
  14482. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14483. /**
  14484. * An event triggered when a mesh is removed
  14485. * @type {BABYLON.Observable}
  14486. */
  14487. this.onMeshRemovedObservable = new BABYLON.Observable();
  14488. /**
  14489. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  14490. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  14491. * 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)
  14492. */
  14493. this.onRenderingGroupObservable = new BABYLON.Observable();
  14494. // Animations
  14495. this.animations = [];
  14496. /**
  14497. * 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).
  14498. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  14499. */
  14500. this.onPrePointerObservable = new BABYLON.Observable();
  14501. /**
  14502. * Observable event triggered each time an input event is received from the rendering canvas
  14503. */
  14504. this.onPointerObservable = new BABYLON.Observable();
  14505. this._meshPickProceed = false;
  14506. this._previousHasSwiped = false;
  14507. this._currentPickResult = null;
  14508. this._previousPickResult = null;
  14509. this._isButtonPressed = false;
  14510. this._doubleClickOccured = false;
  14511. 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
  14512. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14513. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  14514. this._startingPointerTime = 0;
  14515. this._previousStartingPointerTime = 0;
  14516. // Fog
  14517. /**
  14518. * is fog enabled on this scene.
  14519. * @type {boolean}
  14520. */
  14521. this._fogEnabled = true;
  14522. this._fogMode = Scene.FOGMODE_NONE;
  14523. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14524. this.fogDensity = 0.1;
  14525. this.fogStart = 0;
  14526. this.fogEnd = 1000.0;
  14527. // Lights
  14528. /**
  14529. * is shadow enabled on this scene.
  14530. * @type {boolean}
  14531. */
  14532. this._shadowsEnabled = true;
  14533. /**
  14534. * is light enabled on this scene.
  14535. * @type {boolean}
  14536. */
  14537. this._lightsEnabled = true;
  14538. /**
  14539. * All of the lights added to this scene.
  14540. * @see BABYLON.Light
  14541. * @type {BABYLON.Light[]}
  14542. */
  14543. this.lights = new Array();
  14544. // Cameras
  14545. /**
  14546. * All of the cameras added to this scene.
  14547. * @see BABYLON.Camera
  14548. * @type {BABYLON.Camera[]}
  14549. */
  14550. this.cameras = new Array();
  14551. this.activeCameras = new Array();
  14552. // Meshes
  14553. /**
  14554. * All of the (abstract) meshes added to this scene.
  14555. * @see BABYLON.AbstractMesh
  14556. * @type {BABYLON.AbstractMesh[]}
  14557. */
  14558. this.meshes = new Array();
  14559. // Geometries
  14560. this._geometries = new Array();
  14561. this.materials = new Array();
  14562. this.multiMaterials = new Array();
  14563. // Textures
  14564. this._texturesEnabled = true;
  14565. this.textures = new Array();
  14566. // Particles
  14567. this.particlesEnabled = true;
  14568. this.particleSystems = new Array();
  14569. // Sprites
  14570. this.spritesEnabled = true;
  14571. this.spriteManagers = new Array();
  14572. // Layers
  14573. this.layers = new Array();
  14574. this.highlightLayers = new Array();
  14575. // Skeletons
  14576. this._skeletonsEnabled = true;
  14577. this.skeletons = new Array();
  14578. // Morph targets
  14579. this.morphTargetManagers = new Array();
  14580. // Lens flares
  14581. this.lensFlaresEnabled = true;
  14582. this.lensFlareSystems = new Array();
  14583. // Collisions
  14584. this.collisionsEnabled = true;
  14585. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14586. // Postprocesses
  14587. this.postProcessesEnabled = true;
  14588. // Customs render targets
  14589. this.renderTargetsEnabled = true;
  14590. this.dumpNextRenderTargets = false;
  14591. this.customRenderTargets = new Array();
  14592. // Imported meshes
  14593. this.importedMeshesFiles = new Array();
  14594. // Probes
  14595. this.probesEnabled = true;
  14596. this.reflectionProbes = new Array();
  14597. this._actionManagers = new Array();
  14598. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14599. // Procedural textures
  14600. this.proceduralTexturesEnabled = true;
  14601. this._proceduralTextures = new Array();
  14602. this.soundTracks = new Array();
  14603. this._audioEnabled = true;
  14604. this._headphone = false;
  14605. // Performance counters
  14606. this._totalMeshesCounter = new BABYLON.PerfCounter();
  14607. this._totalLightsCounter = new BABYLON.PerfCounter();
  14608. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  14609. this._totalTexturesCounter = new BABYLON.PerfCounter();
  14610. this._totalVertices = new BABYLON.PerfCounter();
  14611. this._activeIndices = new BABYLON.PerfCounter();
  14612. this._activeParticles = new BABYLON.PerfCounter();
  14613. this._lastFrameDuration = new BABYLON.PerfCounter();
  14614. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  14615. this._renderTargetsDuration = new BABYLON.PerfCounter();
  14616. this._particlesDuration = new BABYLON.PerfCounter();
  14617. this._renderDuration = new BABYLON.PerfCounter();
  14618. this._spritesDuration = new BABYLON.PerfCounter();
  14619. this._activeBones = new BABYLON.PerfCounter();
  14620. this._animationTime = 0;
  14621. this.animationTimeScale = 1;
  14622. this._renderId = 0;
  14623. this._executeWhenReadyTimeoutId = -1;
  14624. this._intermediateRendering = false;
  14625. this._viewUpdateFlag = -1;
  14626. this._projectionUpdateFlag = -1;
  14627. this._toBeDisposed = new BABYLON.SmartArray(256);
  14628. this._pendingData = []; //ANY
  14629. this._activeMeshes = new BABYLON.SmartArray(256);
  14630. this._processedMaterials = new BABYLON.SmartArray(256);
  14631. this._renderTargets = new BABYLON.SmartArray(256);
  14632. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14633. this._activeSkeletons = new BABYLON.SmartArray(32);
  14634. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14635. this._activeAnimatables = new Array();
  14636. this._transformMatrix = BABYLON.Matrix.Zero();
  14637. this._edgesRenderers = new BABYLON.SmartArray(16);
  14638. this._uniqueIdCounter = 0;
  14639. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  14640. this._engine.scenes.push(this);
  14641. this._uid = null;
  14642. this._renderingManager = new BABYLON.RenderingManager(this);
  14643. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14644. if (BABYLON.OutlineRenderer) {
  14645. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14646. }
  14647. this.attachControl();
  14648. if (BABYLON.SoundTrack) {
  14649. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14650. }
  14651. //simplification queue
  14652. if (BABYLON.SimplificationQueue) {
  14653. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14654. }
  14655. //collision coordinator initialization. For now legacy per default.
  14656. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14657. }
  14658. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14659. get: function () {
  14660. return Scene._FOGMODE_NONE;
  14661. },
  14662. enumerable: true,
  14663. configurable: true
  14664. });
  14665. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14666. get: function () {
  14667. return Scene._FOGMODE_EXP;
  14668. },
  14669. enumerable: true,
  14670. configurable: true
  14671. });
  14672. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14673. get: function () {
  14674. return Scene._FOGMODE_EXP2;
  14675. },
  14676. enumerable: true,
  14677. configurable: true
  14678. });
  14679. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14680. get: function () {
  14681. return Scene._FOGMODE_LINEAR;
  14682. },
  14683. enumerable: true,
  14684. configurable: true
  14685. });
  14686. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  14687. get: function () {
  14688. return this._forcePointsCloud;
  14689. },
  14690. set: function (value) {
  14691. if (this._forcePointsCloud === value) {
  14692. return;
  14693. }
  14694. this._forcePointsCloud = value;
  14695. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14696. },
  14697. enumerable: true,
  14698. configurable: true
  14699. });
  14700. Object.defineProperty(Scene.prototype, "onDispose", {
  14701. set: function (callback) {
  14702. if (this._onDisposeObserver) {
  14703. this.onDisposeObservable.remove(this._onDisposeObserver);
  14704. }
  14705. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14706. },
  14707. enumerable: true,
  14708. configurable: true
  14709. });
  14710. Object.defineProperty(Scene.prototype, "beforeRender", {
  14711. set: function (callback) {
  14712. if (this._onBeforeRenderObserver) {
  14713. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14714. }
  14715. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14716. },
  14717. enumerable: true,
  14718. configurable: true
  14719. });
  14720. Object.defineProperty(Scene.prototype, "afterRender", {
  14721. set: function (callback) {
  14722. if (this._onAfterRenderObserver) {
  14723. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14724. }
  14725. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14726. },
  14727. enumerable: true,
  14728. configurable: true
  14729. });
  14730. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14731. set: function (callback) {
  14732. if (this._onBeforeCameraRenderObserver) {
  14733. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14734. }
  14735. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14736. },
  14737. enumerable: true,
  14738. configurable: true
  14739. });
  14740. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14741. set: function (callback) {
  14742. if (this._onAfterCameraRenderObserver) {
  14743. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14744. }
  14745. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14746. },
  14747. enumerable: true,
  14748. configurable: true
  14749. });
  14750. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  14751. get: function () {
  14752. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  14753. },
  14754. enumerable: true,
  14755. configurable: true
  14756. });
  14757. Object.defineProperty(Scene.prototype, "fogEnabled", {
  14758. get: function () {
  14759. return this._fogEnabled;
  14760. },
  14761. set: function (value) {
  14762. if (this._fogEnabled === value) {
  14763. return;
  14764. }
  14765. this._fogEnabled = value;
  14766. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14767. },
  14768. enumerable: true,
  14769. configurable: true
  14770. });
  14771. Object.defineProperty(Scene.prototype, "fogMode", {
  14772. get: function () {
  14773. return this._fogMode;
  14774. },
  14775. set: function (value) {
  14776. if (this._fogMode === value) {
  14777. return;
  14778. }
  14779. this._fogMode = value;
  14780. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14781. },
  14782. enumerable: true,
  14783. configurable: true
  14784. });
  14785. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  14786. get: function () {
  14787. return this._shadowsEnabled;
  14788. },
  14789. set: function (value) {
  14790. if (this._shadowsEnabled === value) {
  14791. return;
  14792. }
  14793. this._shadowsEnabled = value;
  14794. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  14795. },
  14796. enumerable: true,
  14797. configurable: true
  14798. });
  14799. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  14800. get: function () {
  14801. return this._lightsEnabled;
  14802. },
  14803. set: function (value) {
  14804. if (this._lightsEnabled === value) {
  14805. return;
  14806. }
  14807. this._lightsEnabled = value;
  14808. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  14809. },
  14810. enumerable: true,
  14811. configurable: true
  14812. });
  14813. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  14814. get: function () {
  14815. if (!this._defaultMaterial) {
  14816. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14817. }
  14818. return this._defaultMaterial;
  14819. },
  14820. enumerable: true,
  14821. configurable: true
  14822. });
  14823. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  14824. get: function () {
  14825. return this._texturesEnabled;
  14826. },
  14827. set: function (value) {
  14828. if (this._texturesEnabled === value) {
  14829. return;
  14830. }
  14831. this._texturesEnabled = value;
  14832. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  14833. },
  14834. enumerable: true,
  14835. configurable: true
  14836. });
  14837. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  14838. get: function () {
  14839. return this._skeletonsEnabled;
  14840. },
  14841. set: function (value) {
  14842. if (this._skeletonsEnabled === value) {
  14843. return;
  14844. }
  14845. this._skeletonsEnabled = value;
  14846. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  14847. },
  14848. enumerable: true,
  14849. configurable: true
  14850. });
  14851. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  14852. get: function () {
  14853. if (!this._postProcessRenderPipelineManager) {
  14854. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14855. }
  14856. return this._postProcessRenderPipelineManager;
  14857. },
  14858. enumerable: true,
  14859. configurable: true
  14860. });
  14861. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  14862. get: function () {
  14863. return this._frustumPlanes;
  14864. },
  14865. enumerable: true,
  14866. configurable: true
  14867. });
  14868. Object.defineProperty(Scene.prototype, "debugLayer", {
  14869. // Properties
  14870. get: function () {
  14871. if (!this._debugLayer) {
  14872. this._debugLayer = new BABYLON.DebugLayer(this);
  14873. }
  14874. return this._debugLayer;
  14875. },
  14876. enumerable: true,
  14877. configurable: true
  14878. });
  14879. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14880. get: function () {
  14881. return this._workerCollisions;
  14882. },
  14883. set: function (enabled) {
  14884. if (!BABYLON.CollisionCoordinatorLegacy) {
  14885. return;
  14886. }
  14887. enabled = (enabled && !!Worker);
  14888. this._workerCollisions = enabled;
  14889. if (this.collisionCoordinator) {
  14890. this.collisionCoordinator.destroy();
  14891. }
  14892. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14893. this.collisionCoordinator.init(this);
  14894. },
  14895. enumerable: true,
  14896. configurable: true
  14897. });
  14898. Object.defineProperty(Scene.prototype, "selectionOctree", {
  14899. get: function () {
  14900. return this._selectionOctree;
  14901. },
  14902. enumerable: true,
  14903. configurable: true
  14904. });
  14905. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14906. /**
  14907. * The mesh that is currently under the pointer.
  14908. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14909. */
  14910. get: function () {
  14911. return this._pointerOverMesh;
  14912. },
  14913. enumerable: true,
  14914. configurable: true
  14915. });
  14916. Object.defineProperty(Scene.prototype, "pointerX", {
  14917. /**
  14918. * Current on-screen X position of the pointer
  14919. * @return {number} X position of the pointer
  14920. */
  14921. get: function () {
  14922. return this._pointerX;
  14923. },
  14924. enumerable: true,
  14925. configurable: true
  14926. });
  14927. Object.defineProperty(Scene.prototype, "pointerY", {
  14928. /**
  14929. * Current on-screen Y position of the pointer
  14930. * @return {number} Y position of the pointer
  14931. */
  14932. get: function () {
  14933. return this._pointerY;
  14934. },
  14935. enumerable: true,
  14936. configurable: true
  14937. });
  14938. Scene.prototype.getCachedMaterial = function () {
  14939. return this._cachedMaterial;
  14940. };
  14941. Scene.prototype.getCachedEffect = function () {
  14942. return this._cachedEffect;
  14943. };
  14944. Scene.prototype.getBoundingBoxRenderer = function () {
  14945. if (!this._boundingBoxRenderer) {
  14946. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14947. }
  14948. return this._boundingBoxRenderer;
  14949. };
  14950. Scene.prototype.getOutlineRenderer = function () {
  14951. return this._outlineRenderer;
  14952. };
  14953. Scene.prototype.getEngine = function () {
  14954. return this._engine;
  14955. };
  14956. Scene.prototype.getTotalVertices = function () {
  14957. return this._totalVertices.current;
  14958. };
  14959. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  14960. get: function () {
  14961. return this._totalVertices;
  14962. },
  14963. enumerable: true,
  14964. configurable: true
  14965. });
  14966. Scene.prototype.getActiveIndices = function () {
  14967. return this._activeIndices.current;
  14968. };
  14969. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  14970. get: function () {
  14971. return this._activeIndices;
  14972. },
  14973. enumerable: true,
  14974. configurable: true
  14975. });
  14976. Scene.prototype.getActiveParticles = function () {
  14977. return this._activeParticles.current;
  14978. };
  14979. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  14980. get: function () {
  14981. return this._activeParticles;
  14982. },
  14983. enumerable: true,
  14984. configurable: true
  14985. });
  14986. Scene.prototype.getActiveBones = function () {
  14987. return this._activeBones.current;
  14988. };
  14989. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  14990. get: function () {
  14991. return this._activeBones;
  14992. },
  14993. enumerable: true,
  14994. configurable: true
  14995. });
  14996. // Stats
  14997. Scene.prototype.getLastFrameDuration = function () {
  14998. return this._lastFrameDuration.current;
  14999. };
  15000. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15001. get: function () {
  15002. return this._lastFrameDuration;
  15003. },
  15004. enumerable: true,
  15005. configurable: true
  15006. });
  15007. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15008. return this._evaluateActiveMeshesDuration.current;
  15009. };
  15010. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15011. get: function () {
  15012. return this._evaluateActiveMeshesDuration;
  15013. },
  15014. enumerable: true,
  15015. configurable: true
  15016. });
  15017. Scene.prototype.getActiveMeshes = function () {
  15018. return this._activeMeshes;
  15019. };
  15020. Scene.prototype.getRenderTargetsDuration = function () {
  15021. return this._renderTargetsDuration.current;
  15022. };
  15023. Scene.prototype.getRenderDuration = function () {
  15024. return this._renderDuration.current;
  15025. };
  15026. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15027. get: function () {
  15028. return this._renderDuration;
  15029. },
  15030. enumerable: true,
  15031. configurable: true
  15032. });
  15033. Scene.prototype.getParticlesDuration = function () {
  15034. return this._particlesDuration.current;
  15035. };
  15036. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15037. get: function () {
  15038. return this._particlesDuration;
  15039. },
  15040. enumerable: true,
  15041. configurable: true
  15042. });
  15043. Scene.prototype.getSpritesDuration = function () {
  15044. return this._spritesDuration.current;
  15045. };
  15046. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15047. get: function () {
  15048. return this._spritesDuration;
  15049. },
  15050. enumerable: true,
  15051. configurable: true
  15052. });
  15053. Scene.prototype.getAnimationRatio = function () {
  15054. return this._animationRatio;
  15055. };
  15056. Scene.prototype.getRenderId = function () {
  15057. return this._renderId;
  15058. };
  15059. Scene.prototype.incrementRenderId = function () {
  15060. this._renderId++;
  15061. };
  15062. Scene.prototype._updatePointerPosition = function (evt) {
  15063. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15064. this._pointerX = evt.clientX - canvasRect.left;
  15065. this._pointerY = evt.clientY - canvasRect.top;
  15066. this._unTranslatedPointerX = this._pointerX;
  15067. this._unTranslatedPointerY = this._pointerY;
  15068. if (this.cameraToUseForPointers) {
  15069. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15070. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15071. }
  15072. };
  15073. // Pointers handling
  15074. /**
  15075. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15076. * @param attachUp defines if you want to attach events to pointerup
  15077. * @param attachDown defines if you want to attach events to pointerdown
  15078. * @param attachMove defines if you want to attach events to pointermove
  15079. */
  15080. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15081. var _this = this;
  15082. if (attachUp === void 0) { attachUp = true; }
  15083. if (attachDown === void 0) { attachDown = true; }
  15084. if (attachMove === void 0) { attachMove = true; }
  15085. this._initActionManager = function (act, clickInfo) {
  15086. if (!_this._meshPickProceed) {
  15087. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15088. _this._currentPickResult = pickResult;
  15089. if (pickResult) {
  15090. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  15091. }
  15092. _this._meshPickProceed = true;
  15093. }
  15094. return act;
  15095. };
  15096. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  15097. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  15098. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  15099. btn !== _this._previousButtonPressed) {
  15100. _this._doubleClickOccured = false;
  15101. clickInfo.singleClick = true;
  15102. clickInfo.ignore = false;
  15103. cb(clickInfo, _this._currentPickResult);
  15104. }
  15105. };
  15106. this._initClickEvent = function (obs1, obs2, evt, cb) {
  15107. var clickInfo = new ClickInfo();
  15108. _this._currentPickResult = null;
  15109. var act;
  15110. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  15111. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  15112. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15113. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  15114. act = _this._initActionManager(act, clickInfo);
  15115. if (act)
  15116. checkPicking = act.hasPickTriggers;
  15117. }
  15118. if (checkPicking) {
  15119. var btn = evt.button;
  15120. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  15121. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  15122. if (!clickInfo.hasSwiped) {
  15123. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  15124. if (!checkSingleClickImmediately) {
  15125. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  15126. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15127. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15128. act = _this._initActionManager(act, clickInfo);
  15129. if (act)
  15130. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15131. }
  15132. }
  15133. if (checkSingleClickImmediately) {
  15134. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  15135. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  15136. btn !== _this._previousButtonPressed) {
  15137. clickInfo.singleClick = true;
  15138. cb(clickInfo, _this._currentPickResult);
  15139. }
  15140. }
  15141. else {
  15142. // wait that no double click has been raised during the double click delay
  15143. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15144. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  15145. }
  15146. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  15147. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15148. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15149. act = _this._initActionManager(act, clickInfo);
  15150. if (act)
  15151. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15152. }
  15153. if (checkDoubleClick) {
  15154. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  15155. if (btn === _this._previousButtonPressed &&
  15156. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  15157. !_this._doubleClickOccured) {
  15158. // pointer has not moved for 2 clicks, it's a double click
  15159. if (!clickInfo.hasSwiped &&
  15160. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  15161. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  15162. _this._previousStartingPointerTime = 0;
  15163. _this._doubleClickOccured = true;
  15164. clickInfo.doubleClick = true;
  15165. clickInfo.ignore = false;
  15166. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  15167. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15168. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15169. cb(clickInfo, _this._currentPickResult);
  15170. }
  15171. else {
  15172. _this._doubleClickOccured = false;
  15173. _this._previousStartingPointerTime = _this._startingPointerTime;
  15174. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15175. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15176. _this._previousButtonPressed = btn;
  15177. _this._previousHasSwiped = clickInfo.hasSwiped;
  15178. if (Scene.ExclusiveDoubleClickMode) {
  15179. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  15180. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15181. }
  15182. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15183. cb(clickInfo, _this._previousPickResult);
  15184. }
  15185. else {
  15186. cb(clickInfo, _this._currentPickResult);
  15187. }
  15188. }
  15189. }
  15190. else {
  15191. _this._doubleClickOccured = false;
  15192. _this._previousStartingPointerTime = _this._startingPointerTime;
  15193. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15194. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15195. _this._previousButtonPressed = btn;
  15196. _this._previousHasSwiped = clickInfo.hasSwiped;
  15197. }
  15198. }
  15199. }
  15200. }
  15201. clickInfo.ignore = true;
  15202. cb(clickInfo, _this._currentPickResult);
  15203. };
  15204. var spritePredicate = function (sprite) {
  15205. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15206. };
  15207. this._onPointerMove = function (evt) {
  15208. _this._updatePointerPosition(evt);
  15209. // PreObservable support
  15210. if (_this.onPrePointerObservable.hasObservers()) {
  15211. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15212. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15213. _this.onPrePointerObservable.notifyObservers(pi, type);
  15214. if (pi.skipOnPointerObservable) {
  15215. return;
  15216. }
  15217. }
  15218. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15219. return;
  15220. }
  15221. var canvas = _this._engine.getRenderingCanvas();
  15222. if (!_this.pointerMovePredicate) {
  15223. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  15224. }
  15225. // Meshes
  15226. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15227. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15228. _this.setPointerOverSprite(null);
  15229. _this.setPointerOverMesh(pickResult.pickedMesh);
  15230. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15231. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  15232. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  15233. }
  15234. else {
  15235. canvas.style.cursor = _this.hoverCursor;
  15236. }
  15237. }
  15238. else {
  15239. canvas.style.cursor = "";
  15240. }
  15241. }
  15242. else {
  15243. _this.setPointerOverMesh(null);
  15244. // Sprites
  15245. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15246. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15247. _this.setPointerOverSprite(pickResult.pickedSprite);
  15248. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  15249. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  15250. }
  15251. else {
  15252. canvas.style.cursor = _this.hoverCursor;
  15253. }
  15254. }
  15255. else {
  15256. _this.setPointerOverSprite(null);
  15257. // Restore pointer
  15258. canvas.style.cursor = "";
  15259. }
  15260. }
  15261. if (_this.onPointerMove) {
  15262. _this.onPointerMove(evt, pickResult);
  15263. }
  15264. if (_this.onPointerObservable.hasObservers()) {
  15265. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15266. var pi = new PointerInfo(type, evt, pickResult);
  15267. _this.onPointerObservable.notifyObservers(pi, type);
  15268. }
  15269. };
  15270. this._onPointerDown = function (evt) {
  15271. _this._isButtonPressed = true;
  15272. _this._pickedDownMesh = null;
  15273. _this._meshPickProceed = false;
  15274. _this._updatePointerPosition(evt);
  15275. // PreObservable support
  15276. if (_this.onPrePointerObservable.hasObservers()) {
  15277. var type = PointerEventTypes.POINTERDOWN;
  15278. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15279. _this.onPrePointerObservable.notifyObservers(pi, type);
  15280. if (pi.skipOnPointerObservable) {
  15281. return;
  15282. }
  15283. }
  15284. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15285. return;
  15286. }
  15287. _this._startingPointerPosition.x = _this._pointerX;
  15288. _this._startingPointerPosition.y = _this._pointerY;
  15289. _this._startingPointerTime = new Date().getTime();
  15290. if (!_this.pointerDownPredicate) {
  15291. _this.pointerDownPredicate = function (mesh) {
  15292. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15293. };
  15294. }
  15295. // Meshes
  15296. _this._pickedDownMesh = null;
  15297. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15298. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15299. _this._pickedDownMesh = pickResult.pickedMesh;
  15300. var actionManager = pickResult.pickedMesh.actionManager;
  15301. if (actionManager) {
  15302. if (actionManager.hasPickTriggers) {
  15303. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15304. switch (evt.button) {
  15305. case 0:
  15306. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15307. break;
  15308. case 1:
  15309. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15310. break;
  15311. case 2:
  15312. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15313. break;
  15314. }
  15315. }
  15316. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15317. window.setTimeout((function () {
  15318. var _this = this;
  15319. 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);
  15320. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15321. if (this._isButtonPressed &&
  15322. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  15323. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  15324. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  15325. this._startingPointerTime = 0;
  15326. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15327. }
  15328. }
  15329. }).bind(_this), Scene.LongPressDelay);
  15330. }
  15331. }
  15332. }
  15333. if (_this.onPointerDown) {
  15334. _this.onPointerDown(evt, pickResult);
  15335. }
  15336. if (_this.onPointerObservable.hasObservers()) {
  15337. var type = PointerEventTypes.POINTERDOWN;
  15338. var pi = new PointerInfo(type, evt, pickResult);
  15339. _this.onPointerObservable.notifyObservers(pi, type);
  15340. }
  15341. // Sprites
  15342. _this._pickedDownSprite = null;
  15343. if (_this.spriteManagers.length > 0) {
  15344. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15345. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15346. if (pickResult.pickedSprite.actionManager) {
  15347. _this._pickedDownSprite = pickResult.pickedSprite;
  15348. switch (evt.button) {
  15349. case 0:
  15350. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15351. break;
  15352. case 1:
  15353. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15354. break;
  15355. case 2:
  15356. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15357. break;
  15358. }
  15359. if (pickResult.pickedSprite.actionManager) {
  15360. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15361. }
  15362. }
  15363. }
  15364. }
  15365. };
  15366. this._onPointerUp = function (evt) {
  15367. _this._isButtonPressed = false;
  15368. _this._pickedUpMesh = null;
  15369. _this._meshPickProceed = false;
  15370. _this._updatePointerPosition(evt);
  15371. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  15372. // PreObservable support
  15373. if (this.onPrePointerObservable.hasObservers()) {
  15374. if (!clickInfo.ignore) {
  15375. if (!clickInfo.hasSwiped) {
  15376. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15377. var type = PointerEventTypes.POINTERTAP;
  15378. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15379. this.onPrePointerObservable.notifyObservers(pi, type);
  15380. if (pi.skipOnPointerObservable) {
  15381. return;
  15382. }
  15383. }
  15384. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15385. var type = PointerEventTypes.POINTERDOUBLETAP;
  15386. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15387. this.onPrePointerObservable.notifyObservers(pi, type);
  15388. if (pi.skipOnPointerObservable) {
  15389. return;
  15390. }
  15391. }
  15392. }
  15393. }
  15394. else {
  15395. var type = PointerEventTypes.POINTERUP;
  15396. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15397. this.onPrePointerObservable.notifyObservers(pi, type);
  15398. if (pi.skipOnPointerObservable) {
  15399. return;
  15400. }
  15401. }
  15402. }
  15403. if (!this.cameraToUseForPointers && !this.activeCamera) {
  15404. return;
  15405. }
  15406. if (!this.pointerUpPredicate) {
  15407. this.pointerUpPredicate = function (mesh) {
  15408. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15409. };
  15410. }
  15411. // Meshes
  15412. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  15413. this._initActionManager(null, clickInfo);
  15414. }
  15415. if (!pickResult) {
  15416. pickResult = this._currentPickResult;
  15417. }
  15418. if (pickResult && pickResult && pickResult.pickedMesh) {
  15419. this._pickedUpMesh = pickResult.pickedMesh;
  15420. if (this._pickedDownMesh === this._pickedUpMesh) {
  15421. if (this.onPointerPick) {
  15422. this.onPointerPick(evt, pickResult);
  15423. }
  15424. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  15425. var type = PointerEventTypes.POINTERPICK;
  15426. var pi = new PointerInfo(type, evt, pickResult);
  15427. this.onPointerObservable.notifyObservers(pi, type);
  15428. }
  15429. }
  15430. if (pickResult.pickedMesh.actionManager) {
  15431. if (clickInfo.ignore) {
  15432. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15433. }
  15434. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  15435. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15436. }
  15437. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15438. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15439. }
  15440. }
  15441. }
  15442. if (this._pickedDownMesh &&
  15443. this._pickedDownMesh.actionManager &&
  15444. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  15445. this._pickedDownMesh !== this._pickedUpMesh) {
  15446. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  15447. }
  15448. if (this.onPointerUp) {
  15449. this.onPointerUp(evt, pickResult);
  15450. }
  15451. if (this.onPointerObservable.hasObservers()) {
  15452. if (!clickInfo.ignore) {
  15453. if (!clickInfo.hasSwiped) {
  15454. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15455. var type = PointerEventTypes.POINTERTAP;
  15456. var pi = new PointerInfo(type, evt, pickResult);
  15457. this.onPointerObservable.notifyObservers(pi, type);
  15458. }
  15459. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15460. var type = PointerEventTypes.POINTERDOUBLETAP;
  15461. var pi = new PointerInfo(type, evt, pickResult);
  15462. this.onPointerObservable.notifyObservers(pi, type);
  15463. }
  15464. }
  15465. }
  15466. else {
  15467. var type = PointerEventTypes.POINTERUP;
  15468. var pi = new PointerInfo(type, evt, pickResult);
  15469. this.onPointerObservable.notifyObservers(pi, type);
  15470. }
  15471. }
  15472. // Sprites
  15473. if (this.spriteManagers.length > 0) {
  15474. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  15475. if (pickResult.hit && pickResult.pickedSprite) {
  15476. if (pickResult.pickedSprite.actionManager) {
  15477. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15478. if (pickResult.pickedSprite.actionManager) {
  15479. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  15480. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15481. }
  15482. }
  15483. }
  15484. }
  15485. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  15486. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  15487. }
  15488. }
  15489. this._previousPickResult = this._currentPickResult;
  15490. }).bind(_this));
  15491. };
  15492. this._onKeyDown = function (evt) {
  15493. if (_this.actionManager) {
  15494. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15495. }
  15496. };
  15497. this._onKeyUp = function (evt) {
  15498. if (_this.actionManager) {
  15499. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15500. }
  15501. };
  15502. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15503. var canvas = this._engine.getRenderingCanvas();
  15504. if (attachMove) {
  15505. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15506. // Wheel
  15507. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  15508. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15509. }
  15510. if (attachDown) {
  15511. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15512. }
  15513. if (attachUp) {
  15514. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15515. }
  15516. canvas.tabIndex = 1;
  15517. canvas.addEventListener("keydown", this._onKeyDown, false);
  15518. canvas.addEventListener("keyup", this._onKeyUp, false);
  15519. };
  15520. Scene.prototype.detachControl = function () {
  15521. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15522. var canvas = this._engine.getRenderingCanvas();
  15523. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  15524. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  15525. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  15526. // Wheel
  15527. canvas.removeEventListener('mousewheel', this._onPointerMove);
  15528. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  15529. canvas.removeEventListener("keydown", this._onKeyDown);
  15530. canvas.removeEventListener("keyup", this._onKeyUp);
  15531. };
  15532. // Ready
  15533. Scene.prototype.isReady = function () {
  15534. if (this._pendingData.length > 0) {
  15535. return false;
  15536. }
  15537. var index;
  15538. // Geometries
  15539. for (index = 0; index < this._geometries.length; index++) {
  15540. var geometry = this._geometries[index];
  15541. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15542. return false;
  15543. }
  15544. }
  15545. // Meshes
  15546. for (index = 0; index < this.meshes.length; index++) {
  15547. var mesh = this.meshes[index];
  15548. if (!mesh.isEnabled()) {
  15549. continue;
  15550. }
  15551. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  15552. continue;
  15553. }
  15554. if (!mesh.isReady()) {
  15555. return false;
  15556. }
  15557. var mat = mesh.material;
  15558. if (mat) {
  15559. if (!mat.isReady(mesh)) {
  15560. return false;
  15561. }
  15562. }
  15563. }
  15564. return true;
  15565. };
  15566. Scene.prototype.resetCachedMaterial = function () {
  15567. this._cachedMaterial = null;
  15568. this._cachedEffect = null;
  15569. };
  15570. Scene.prototype.registerBeforeRender = function (func) {
  15571. this.onBeforeRenderObservable.add(func);
  15572. };
  15573. Scene.prototype.unregisterBeforeRender = function (func) {
  15574. this.onBeforeRenderObservable.removeCallback(func);
  15575. };
  15576. Scene.prototype.registerAfterRender = function (func) {
  15577. this.onAfterRenderObservable.add(func);
  15578. };
  15579. Scene.prototype.unregisterAfterRender = function (func) {
  15580. this.onAfterRenderObservable.removeCallback(func);
  15581. };
  15582. Scene.prototype._addPendingData = function (data) {
  15583. this._pendingData.push(data);
  15584. };
  15585. Scene.prototype._removePendingData = function (data) {
  15586. var index = this._pendingData.indexOf(data);
  15587. if (index !== -1) {
  15588. this._pendingData.splice(index, 1);
  15589. }
  15590. };
  15591. Scene.prototype.getWaitingItemsCount = function () {
  15592. return this._pendingData.length;
  15593. };
  15594. /**
  15595. * Registers a function to be executed when the scene is ready.
  15596. * @param {Function} func - the function to be executed.
  15597. */
  15598. Scene.prototype.executeWhenReady = function (func) {
  15599. var _this = this;
  15600. this.onReadyObservable.add(func);
  15601. if (this._executeWhenReadyTimeoutId !== -1) {
  15602. return;
  15603. }
  15604. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15605. _this._checkIsReady();
  15606. }, 150);
  15607. };
  15608. Scene.prototype._checkIsReady = function () {
  15609. var _this = this;
  15610. if (this.isReady()) {
  15611. this.onReadyObservable.notifyObservers(this);
  15612. this.onReadyObservable.clear();
  15613. this._executeWhenReadyTimeoutId = -1;
  15614. return;
  15615. }
  15616. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15617. _this._checkIsReady();
  15618. }, 150);
  15619. };
  15620. // Animations
  15621. /**
  15622. * Will start the animation sequence of a given target
  15623. * @param target - the target
  15624. * @param {number} from - from which frame should animation start
  15625. * @param {number} to - till which frame should animation run.
  15626. * @param {boolean} [loop] - should the animation loop
  15627. * @param {number} [speedRatio] - the speed in which to run the animation
  15628. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15629. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15630. * @return {BABYLON.Animatable} the animatable object created for this animation
  15631. * @see BABYLON.Animatable
  15632. * @see http://doc.babylonjs.com/page.php?p=22081
  15633. */
  15634. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15635. if (speedRatio === void 0) { speedRatio = 1.0; }
  15636. this.stopAnimation(target);
  15637. if (!animatable) {
  15638. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15639. }
  15640. // Local animations
  15641. if (target.animations) {
  15642. animatable.appendAnimations(target, target.animations);
  15643. }
  15644. // Children animations
  15645. if (target.getAnimatables) {
  15646. var animatables = target.getAnimatables();
  15647. for (var index = 0; index < animatables.length; index++) {
  15648. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15649. }
  15650. }
  15651. animatable.reset();
  15652. return animatable;
  15653. };
  15654. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15655. if (speedRatio === undefined) {
  15656. speedRatio = 1.0;
  15657. }
  15658. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15659. return animatable;
  15660. };
  15661. Scene.prototype.getAnimatableByTarget = function (target) {
  15662. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15663. if (this._activeAnimatables[index].target === target) {
  15664. return this._activeAnimatables[index];
  15665. }
  15666. }
  15667. return null;
  15668. };
  15669. Object.defineProperty(Scene.prototype, "Animatables", {
  15670. get: function () {
  15671. return this._activeAnimatables;
  15672. },
  15673. enumerable: true,
  15674. configurable: true
  15675. });
  15676. /**
  15677. * Will stop the animation of the given target
  15678. * @param target - the target
  15679. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  15680. * @see beginAnimation
  15681. */
  15682. Scene.prototype.stopAnimation = function (target, animationName) {
  15683. var animatable = this.getAnimatableByTarget(target);
  15684. if (animatable) {
  15685. animatable.stop(animationName);
  15686. }
  15687. };
  15688. Scene.prototype._animate = function () {
  15689. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15690. return;
  15691. }
  15692. // Getting time
  15693. var now = BABYLON.Tools.Now;
  15694. if (!this._animationTimeLast) {
  15695. if (this._pendingData.length > 0) {
  15696. return;
  15697. }
  15698. this._animationTimeLast = now;
  15699. }
  15700. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  15701. this._animationTime += deltaTime;
  15702. this._animationTimeLast = now;
  15703. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15704. this._activeAnimatables[index]._animate(this._animationTime);
  15705. }
  15706. };
  15707. // Matrix
  15708. Scene.prototype.getViewMatrix = function () {
  15709. return this._viewMatrix;
  15710. };
  15711. Scene.prototype.getProjectionMatrix = function () {
  15712. return this._projectionMatrix;
  15713. };
  15714. Scene.prototype.getTransformMatrix = function () {
  15715. return this._transformMatrix;
  15716. };
  15717. Scene.prototype.setTransformMatrix = function (view, projection) {
  15718. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  15719. return;
  15720. }
  15721. this._viewUpdateFlag = view.updateFlag;
  15722. this._projectionUpdateFlag = projection.updateFlag;
  15723. this._viewMatrix = view;
  15724. this._projectionMatrix = projection;
  15725. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15726. // Update frustum
  15727. if (!this._frustumPlanes) {
  15728. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15729. }
  15730. else {
  15731. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15732. }
  15733. };
  15734. // Methods
  15735. Scene.prototype.getUniqueId = function () {
  15736. var result = this._uniqueIdCounter;
  15737. this._uniqueIdCounter++;
  15738. return result;
  15739. };
  15740. Scene.prototype.addMesh = function (newMesh) {
  15741. newMesh.uniqueId = this.getUniqueId();
  15742. var position = this.meshes.push(newMesh);
  15743. //notify the collision coordinator
  15744. if (this.collisionCoordinator) {
  15745. this.collisionCoordinator.onMeshAdded(newMesh);
  15746. }
  15747. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15748. };
  15749. Scene.prototype.removeMesh = function (toRemove) {
  15750. var index = this.meshes.indexOf(toRemove);
  15751. if (index !== -1) {
  15752. // Remove from the scene if mesh found
  15753. this.meshes.splice(index, 1);
  15754. }
  15755. //notify the collision coordinator
  15756. if (this.collisionCoordinator) {
  15757. this.collisionCoordinator.onMeshRemoved(toRemove);
  15758. }
  15759. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15760. return index;
  15761. };
  15762. Scene.prototype.removeSkeleton = function (toRemove) {
  15763. var index = this.skeletons.indexOf(toRemove);
  15764. if (index !== -1) {
  15765. // Remove from the scene if found
  15766. this.skeletons.splice(index, 1);
  15767. }
  15768. return index;
  15769. };
  15770. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  15771. var index = this.morphTargetManagers.indexOf(toRemove);
  15772. if (index !== -1) {
  15773. // Remove from the scene if found
  15774. this.morphTargetManagers.splice(index, 1);
  15775. }
  15776. return index;
  15777. };
  15778. Scene.prototype.removeLight = function (toRemove) {
  15779. var index = this.lights.indexOf(toRemove);
  15780. if (index !== -1) {
  15781. // Remove from the scene if mesh found
  15782. this.lights.splice(index, 1);
  15783. }
  15784. this.onLightRemovedObservable.notifyObservers(toRemove);
  15785. return index;
  15786. };
  15787. Scene.prototype.removeCamera = function (toRemove) {
  15788. var index = this.cameras.indexOf(toRemove);
  15789. if (index !== -1) {
  15790. // Remove from the scene if mesh found
  15791. this.cameras.splice(index, 1);
  15792. }
  15793. // Remove from activeCameras
  15794. var index2 = this.activeCameras.indexOf(toRemove);
  15795. if (index2 !== -1) {
  15796. // Remove from the scene if mesh found
  15797. this.activeCameras.splice(index2, 1);
  15798. }
  15799. // Reset the activeCamera
  15800. if (this.activeCamera === toRemove) {
  15801. if (this.cameras.length > 0) {
  15802. this.activeCamera = this.cameras[0];
  15803. }
  15804. else {
  15805. this.activeCamera = null;
  15806. }
  15807. }
  15808. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15809. return index;
  15810. };
  15811. Scene.prototype.addLight = function (newLight) {
  15812. newLight.uniqueId = this.getUniqueId();
  15813. var position = this.lights.push(newLight);
  15814. this.onNewLightAddedObservable.notifyObservers(newLight);
  15815. };
  15816. Scene.prototype.addCamera = function (newCamera) {
  15817. newCamera.uniqueId = this.getUniqueId();
  15818. var position = this.cameras.push(newCamera);
  15819. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15820. };
  15821. /**
  15822. * Switch active camera
  15823. * @param {Camera} newCamera - new active camera
  15824. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15825. */
  15826. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  15827. if (attachControl === void 0) { attachControl = true; }
  15828. var canvas = this._engine.getRenderingCanvas();
  15829. this.activeCamera.detachControl(canvas);
  15830. this.activeCamera = newCamera;
  15831. if (attachControl) {
  15832. newCamera.attachControl(canvas);
  15833. }
  15834. };
  15835. /**
  15836. * sets the active camera of the scene using its ID
  15837. * @param {string} id - the camera's ID
  15838. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15839. * @see activeCamera
  15840. */
  15841. Scene.prototype.setActiveCameraByID = function (id) {
  15842. var camera = this.getCameraByID(id);
  15843. if (camera) {
  15844. this.activeCamera = camera;
  15845. return camera;
  15846. }
  15847. return null;
  15848. };
  15849. /**
  15850. * sets the active camera of the scene using its name
  15851. * @param {string} name - the camera's name
  15852. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15853. * @see activeCamera
  15854. */
  15855. Scene.prototype.setActiveCameraByName = function (name) {
  15856. var camera = this.getCameraByName(name);
  15857. if (camera) {
  15858. this.activeCamera = camera;
  15859. return camera;
  15860. }
  15861. return null;
  15862. };
  15863. /**
  15864. * get a material using its id
  15865. * @param {string} the material's ID
  15866. * @return {BABYLON.Material|null} the material or null if none found.
  15867. */
  15868. Scene.prototype.getMaterialByID = function (id) {
  15869. for (var index = 0; index < this.materials.length; index++) {
  15870. if (this.materials[index].id === id) {
  15871. return this.materials[index];
  15872. }
  15873. }
  15874. return null;
  15875. };
  15876. /**
  15877. * get a material using its name
  15878. * @param {string} the material's name
  15879. * @return {BABYLON.Material|null} the material or null if none found.
  15880. */
  15881. Scene.prototype.getMaterialByName = function (name) {
  15882. for (var index = 0; index < this.materials.length; index++) {
  15883. if (this.materials[index].name === name) {
  15884. return this.materials[index];
  15885. }
  15886. }
  15887. return null;
  15888. };
  15889. Scene.prototype.getLensFlareSystemByName = function (name) {
  15890. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15891. if (this.lensFlareSystems[index].name === name) {
  15892. return this.lensFlareSystems[index];
  15893. }
  15894. }
  15895. return null;
  15896. };
  15897. Scene.prototype.getLensFlareSystemByID = function (id) {
  15898. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15899. if (this.lensFlareSystems[index].id === id) {
  15900. return this.lensFlareSystems[index];
  15901. }
  15902. }
  15903. return null;
  15904. };
  15905. Scene.prototype.getCameraByID = function (id) {
  15906. for (var index = 0; index < this.cameras.length; index++) {
  15907. if (this.cameras[index].id === id) {
  15908. return this.cameras[index];
  15909. }
  15910. }
  15911. return null;
  15912. };
  15913. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15914. for (var index = 0; index < this.cameras.length; index++) {
  15915. if (this.cameras[index].uniqueId === uniqueId) {
  15916. return this.cameras[index];
  15917. }
  15918. }
  15919. return null;
  15920. };
  15921. /**
  15922. * get a camera using its name
  15923. * @param {string} the camera's name
  15924. * @return {BABYLON.Camera|null} the camera or null if none found.
  15925. */
  15926. Scene.prototype.getCameraByName = function (name) {
  15927. for (var index = 0; index < this.cameras.length; index++) {
  15928. if (this.cameras[index].name === name) {
  15929. return this.cameras[index];
  15930. }
  15931. }
  15932. return null;
  15933. };
  15934. /**
  15935. * get a bone using its id
  15936. * @param {string} the bone's id
  15937. * @return {BABYLON.Bone|null} the bone or null if not found
  15938. */
  15939. Scene.prototype.getBoneByID = function (id) {
  15940. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15941. var skeleton = this.skeletons[skeletonIndex];
  15942. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15943. if (skeleton.bones[boneIndex].id === id) {
  15944. return skeleton.bones[boneIndex];
  15945. }
  15946. }
  15947. }
  15948. return null;
  15949. };
  15950. /**
  15951. * get a bone using its id
  15952. * @param {string} the bone's name
  15953. * @return {BABYLON.Bone|null} the bone or null if not found
  15954. */
  15955. Scene.prototype.getBoneByName = function (name) {
  15956. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15957. var skeleton = this.skeletons[skeletonIndex];
  15958. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15959. if (skeleton.bones[boneIndex].name === name) {
  15960. return skeleton.bones[boneIndex];
  15961. }
  15962. }
  15963. }
  15964. return null;
  15965. };
  15966. /**
  15967. * get a light node using its name
  15968. * @param {string} the light's name
  15969. * @return {BABYLON.Light|null} the light or null if none found.
  15970. */
  15971. Scene.prototype.getLightByName = function (name) {
  15972. for (var index = 0; index < this.lights.length; index++) {
  15973. if (this.lights[index].name === name) {
  15974. return this.lights[index];
  15975. }
  15976. }
  15977. return null;
  15978. };
  15979. /**
  15980. * get a light node using its ID
  15981. * @param {string} the light's id
  15982. * @return {BABYLON.Light|null} the light or null if none found.
  15983. */
  15984. Scene.prototype.getLightByID = function (id) {
  15985. for (var index = 0; index < this.lights.length; index++) {
  15986. if (this.lights[index].id === id) {
  15987. return this.lights[index];
  15988. }
  15989. }
  15990. return null;
  15991. };
  15992. /**
  15993. * get a light node using its scene-generated unique ID
  15994. * @param {number} the light's unique id
  15995. * @return {BABYLON.Light|null} the light or null if none found.
  15996. */
  15997. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15998. for (var index = 0; index < this.lights.length; index++) {
  15999. if (this.lights[index].uniqueId === uniqueId) {
  16000. return this.lights[index];
  16001. }
  16002. }
  16003. return null;
  16004. };
  16005. /**
  16006. * get a particle system by id
  16007. * @param id {number} the particle system id
  16008. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16009. */
  16010. Scene.prototype.getParticleSystemByID = function (id) {
  16011. for (var index = 0; index < this.particleSystems.length; index++) {
  16012. if (this.particleSystems[index].id === id) {
  16013. return this.particleSystems[index];
  16014. }
  16015. }
  16016. return null;
  16017. };
  16018. /**
  16019. * get a geometry using its ID
  16020. * @param {string} the geometry's id
  16021. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16022. */
  16023. Scene.prototype.getGeometryByID = function (id) {
  16024. for (var index = 0; index < this._geometries.length; index++) {
  16025. if (this._geometries[index].id === id) {
  16026. return this._geometries[index];
  16027. }
  16028. }
  16029. return null;
  16030. };
  16031. /**
  16032. * add a new geometry to this scene.
  16033. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16034. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16035. * @return {boolean} was the geometry added or not
  16036. */
  16037. Scene.prototype.pushGeometry = function (geometry, force) {
  16038. if (!force && this.getGeometryByID(geometry.id)) {
  16039. return false;
  16040. }
  16041. this._geometries.push(geometry);
  16042. //notify the collision coordinator
  16043. if (this.collisionCoordinator) {
  16044. this.collisionCoordinator.onGeometryAdded(geometry);
  16045. }
  16046. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16047. return true;
  16048. };
  16049. /**
  16050. * Removes an existing geometry
  16051. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16052. * @return {boolean} was the geometry removed or not
  16053. */
  16054. Scene.prototype.removeGeometry = function (geometry) {
  16055. var index = this._geometries.indexOf(geometry);
  16056. if (index > -1) {
  16057. this._geometries.splice(index, 1);
  16058. //notify the collision coordinator
  16059. if (this.collisionCoordinator) {
  16060. this.collisionCoordinator.onGeometryDeleted(geometry);
  16061. }
  16062. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16063. return true;
  16064. }
  16065. return false;
  16066. };
  16067. Scene.prototype.getGeometries = function () {
  16068. return this._geometries;
  16069. };
  16070. /**
  16071. * Get the first added mesh found of a given ID
  16072. * @param {string} id - the id to search for
  16073. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16074. */
  16075. Scene.prototype.getMeshByID = function (id) {
  16076. for (var index = 0; index < this.meshes.length; index++) {
  16077. if (this.meshes[index].id === id) {
  16078. return this.meshes[index];
  16079. }
  16080. }
  16081. return null;
  16082. };
  16083. Scene.prototype.getMeshesByID = function (id) {
  16084. return this.meshes.filter(function (m) {
  16085. return m.id === id;
  16086. });
  16087. };
  16088. /**
  16089. * Get a mesh with its auto-generated unique id
  16090. * @param {number} uniqueId - the unique id to search for
  16091. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16092. */
  16093. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16094. for (var index = 0; index < this.meshes.length; index++) {
  16095. if (this.meshes[index].uniqueId === uniqueId) {
  16096. return this.meshes[index];
  16097. }
  16098. }
  16099. return null;
  16100. };
  16101. /**
  16102. * Get a the last added mesh found of a given ID
  16103. * @param {string} id - the id to search for
  16104. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16105. */
  16106. Scene.prototype.getLastMeshByID = function (id) {
  16107. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16108. if (this.meshes[index].id === id) {
  16109. return this.meshes[index];
  16110. }
  16111. }
  16112. return null;
  16113. };
  16114. /**
  16115. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16116. * @param {string} id - the id to search for
  16117. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16118. */
  16119. Scene.prototype.getLastEntryByID = function (id) {
  16120. var index;
  16121. for (index = this.meshes.length - 1; index >= 0; index--) {
  16122. if (this.meshes[index].id === id) {
  16123. return this.meshes[index];
  16124. }
  16125. }
  16126. for (index = this.cameras.length - 1; index >= 0; index--) {
  16127. if (this.cameras[index].id === id) {
  16128. return this.cameras[index];
  16129. }
  16130. }
  16131. for (index = this.lights.length - 1; index >= 0; index--) {
  16132. if (this.lights[index].id === id) {
  16133. return this.lights[index];
  16134. }
  16135. }
  16136. return null;
  16137. };
  16138. Scene.prototype.getNodeByID = function (id) {
  16139. var mesh = this.getMeshByID(id);
  16140. if (mesh) {
  16141. return mesh;
  16142. }
  16143. var light = this.getLightByID(id);
  16144. if (light) {
  16145. return light;
  16146. }
  16147. var camera = this.getCameraByID(id);
  16148. if (camera) {
  16149. return camera;
  16150. }
  16151. var bone = this.getBoneByID(id);
  16152. return bone;
  16153. };
  16154. Scene.prototype.getNodeByName = function (name) {
  16155. var mesh = this.getMeshByName(name);
  16156. if (mesh) {
  16157. return mesh;
  16158. }
  16159. var light = this.getLightByName(name);
  16160. if (light) {
  16161. return light;
  16162. }
  16163. var camera = this.getCameraByName(name);
  16164. if (camera) {
  16165. return camera;
  16166. }
  16167. var bone = this.getBoneByName(name);
  16168. return bone;
  16169. };
  16170. Scene.prototype.getMeshByName = function (name) {
  16171. for (var index = 0; index < this.meshes.length; index++) {
  16172. if (this.meshes[index].name === name) {
  16173. return this.meshes[index];
  16174. }
  16175. }
  16176. return null;
  16177. };
  16178. Scene.prototype.getSoundByName = function (name) {
  16179. var index;
  16180. if (BABYLON.AudioEngine) {
  16181. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16182. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16183. return this.mainSoundTrack.soundCollection[index];
  16184. }
  16185. }
  16186. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16187. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16188. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16189. return this.soundTracks[sdIndex].soundCollection[index];
  16190. }
  16191. }
  16192. }
  16193. }
  16194. return null;
  16195. };
  16196. Scene.prototype.getLastSkeletonByID = function (id) {
  16197. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16198. if (this.skeletons[index].id === id) {
  16199. return this.skeletons[index];
  16200. }
  16201. }
  16202. return null;
  16203. };
  16204. Scene.prototype.getSkeletonById = function (id) {
  16205. for (var index = 0; index < this.skeletons.length; index++) {
  16206. if (this.skeletons[index].id === id) {
  16207. return this.skeletons[index];
  16208. }
  16209. }
  16210. return null;
  16211. };
  16212. Scene.prototype.getSkeletonByName = function (name) {
  16213. for (var index = 0; index < this.skeletons.length; index++) {
  16214. if (this.skeletons[index].name === name) {
  16215. return this.skeletons[index];
  16216. }
  16217. }
  16218. return null;
  16219. };
  16220. Scene.prototype.getMorphTargetManagerById = function (id) {
  16221. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  16222. if (this.morphTargetManagers[index].uniqueId === id) {
  16223. return this.morphTargetManagers[index];
  16224. }
  16225. }
  16226. return null;
  16227. };
  16228. Scene.prototype.isActiveMesh = function (mesh) {
  16229. return (this._activeMeshes.indexOf(mesh) !== -1);
  16230. };
  16231. /**
  16232. * Return a the first highlight layer of the scene with a given name.
  16233. * @param name The name of the highlight layer to look for.
  16234. * @return The highlight layer if found otherwise null.
  16235. */
  16236. Scene.prototype.getHighlightLayerByName = function (name) {
  16237. for (var index = 0; index < this.highlightLayers.length; index++) {
  16238. if (this.highlightLayers[index].name === name) {
  16239. return this.highlightLayers[index];
  16240. }
  16241. }
  16242. return null;
  16243. };
  16244. Object.defineProperty(Scene.prototype, "uid", {
  16245. /**
  16246. * Return a unique id as a string which can serve as an identifier for the scene
  16247. */
  16248. get: function () {
  16249. if (!this._uid) {
  16250. this._uid = BABYLON.Tools.RandomId();
  16251. }
  16252. return this._uid;
  16253. },
  16254. enumerable: true,
  16255. configurable: true
  16256. });
  16257. /**
  16258. * Add an externaly attached data from its key.
  16259. * This method call will fail and return false, if such key already exists.
  16260. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16261. * @param key the unique key that identifies the data
  16262. * @param data the data object to associate to the key for this Engine instance
  16263. * @return true if no such key were already present and the data was added successfully, false otherwise
  16264. */
  16265. Scene.prototype.addExternalData = function (key, data) {
  16266. if (!this._externalData) {
  16267. this._externalData = new BABYLON.StringDictionary();
  16268. }
  16269. return this._externalData.add(key, data);
  16270. };
  16271. /**
  16272. * Get an externaly attached data from its key
  16273. * @param key the unique key that identifies the data
  16274. * @return the associated data, if present (can be null), or undefined if not present
  16275. */
  16276. Scene.prototype.getExternalData = function (key) {
  16277. if (!this._externalData) {
  16278. return null;
  16279. }
  16280. return this._externalData.get(key);
  16281. };
  16282. /**
  16283. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16284. * @param key the unique key that identifies the data
  16285. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16286. * @return the associated data, can be null if the factory returned null.
  16287. */
  16288. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16289. if (!this._externalData) {
  16290. this._externalData = new BABYLON.StringDictionary();
  16291. }
  16292. return this._externalData.getOrAddWithFactory(key, factory);
  16293. };
  16294. /**
  16295. * Remove an externaly attached data from the Engine instance
  16296. * @param key the unique key that identifies the data
  16297. * @return true if the data was successfully removed, false if it doesn't exist
  16298. */
  16299. Scene.prototype.removeExternalData = function (key) {
  16300. return this._externalData.remove(key);
  16301. };
  16302. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16303. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16304. var material = subMesh.getMaterial();
  16305. if (mesh.showSubMeshesBoundingBox) {
  16306. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  16307. }
  16308. if (material) {
  16309. // Render targets
  16310. if (material.getRenderTargetTextures) {
  16311. if (this._processedMaterials.indexOf(material) === -1) {
  16312. this._processedMaterials.push(material);
  16313. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16314. }
  16315. }
  16316. // Dispatch
  16317. this._activeIndices.addCount(subMesh.indexCount, false);
  16318. this._renderingManager.dispatch(subMesh);
  16319. }
  16320. }
  16321. };
  16322. Scene.prototype._isInIntermediateRendering = function () {
  16323. return this._intermediateRendering;
  16324. };
  16325. Scene.prototype._evaluateActiveMeshes = function () {
  16326. this.activeCamera._activeMeshes.reset();
  16327. this._activeMeshes.reset();
  16328. this._renderingManager.reset();
  16329. this._processedMaterials.reset();
  16330. this._activeParticleSystems.reset();
  16331. this._activeSkeletons.reset();
  16332. this._softwareSkinnedMeshes.reset();
  16333. if (this._boundingBoxRenderer) {
  16334. this._boundingBoxRenderer.reset();
  16335. }
  16336. this._edgesRenderers.reset();
  16337. // Meshes
  16338. var meshes;
  16339. var len;
  16340. if (this._selectionOctree) {
  16341. var selection = this._selectionOctree.select(this._frustumPlanes);
  16342. meshes = selection.data;
  16343. len = selection.length;
  16344. }
  16345. else {
  16346. len = this.meshes.length;
  16347. meshes = this.meshes;
  16348. }
  16349. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16350. var mesh = meshes[meshIndex];
  16351. if (mesh.isBlocked) {
  16352. continue;
  16353. }
  16354. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16355. if (!mesh.isReady() || !mesh.isEnabled()) {
  16356. continue;
  16357. }
  16358. mesh.computeWorldMatrix();
  16359. // Intersections
  16360. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16361. this._meshesForIntersections.pushNoDuplicate(mesh);
  16362. }
  16363. // Switch to current LOD
  16364. var meshLOD = mesh.getLOD(this.activeCamera);
  16365. if (!meshLOD) {
  16366. continue;
  16367. }
  16368. mesh._preActivate();
  16369. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16370. this._activeMeshes.push(mesh);
  16371. this.activeCamera._activeMeshes.push(mesh);
  16372. mesh._activate(this._renderId);
  16373. this._activeMesh(mesh, meshLOD);
  16374. }
  16375. }
  16376. // Particle systems
  16377. this._particlesDuration.beginMonitoring();
  16378. var beforeParticlesDate = BABYLON.Tools.Now;
  16379. if (this.particlesEnabled) {
  16380. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16381. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16382. var particleSystem = this.particleSystems[particleIndex];
  16383. if (!particleSystem.isStarted()) {
  16384. continue;
  16385. }
  16386. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16387. this._activeParticleSystems.push(particleSystem);
  16388. particleSystem.animate();
  16389. this._renderingManager.dispatchParticles(particleSystem);
  16390. }
  16391. }
  16392. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16393. }
  16394. this._particlesDuration.endMonitoring(false);
  16395. };
  16396. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  16397. if (mesh.skeleton && this.skeletonsEnabled) {
  16398. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16399. mesh.skeleton.prepare();
  16400. }
  16401. if (!mesh.computeBonesUsingShaders) {
  16402. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16403. }
  16404. }
  16405. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16406. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  16407. }
  16408. if (sourceMesh._edgesRenderer) {
  16409. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  16410. }
  16411. if (mesh && mesh.subMeshes) {
  16412. // Submeshes Octrees
  16413. var len;
  16414. var subMeshes;
  16415. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16416. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16417. len = intersections.length;
  16418. subMeshes = intersections.data;
  16419. }
  16420. else {
  16421. subMeshes = mesh.subMeshes;
  16422. len = subMeshes.length;
  16423. }
  16424. for (var subIndex = 0; subIndex < len; subIndex++) {
  16425. var subMesh = subMeshes[subIndex];
  16426. this._evaluateSubMesh(subMesh, mesh);
  16427. }
  16428. }
  16429. };
  16430. Scene.prototype.updateTransformMatrix = function (force) {
  16431. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16432. };
  16433. Scene.prototype._renderForCamera = function (camera) {
  16434. var engine = this._engine;
  16435. var startTime = BABYLON.Tools.Now;
  16436. this.activeCamera = camera;
  16437. if (!this.activeCamera)
  16438. throw new Error("Active camera not set");
  16439. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16440. // Viewport
  16441. engine.setViewport(this.activeCamera.viewport);
  16442. // Camera
  16443. this.resetCachedMaterial();
  16444. this._renderId++;
  16445. this.updateTransformMatrix();
  16446. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16447. // Meshes
  16448. this._evaluateActiveMeshesDuration.beginMonitoring();
  16449. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16450. this._evaluateActiveMeshes();
  16451. this._evaluateActiveMeshesDuration.endMonitoring(false);
  16452. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16453. // Software skinning
  16454. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16455. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16456. mesh.applySkeleton(mesh.skeleton);
  16457. }
  16458. // Render targets
  16459. this._renderTargetsDuration.beginMonitoring();
  16460. var needsRestoreFrameBuffer = false;
  16461. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16462. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16463. this._intermediateRendering = true;
  16464. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16465. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16466. var renderTarget = this._renderTargets.data[renderIndex];
  16467. if (renderTarget._shouldRender()) {
  16468. this._renderId++;
  16469. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16470. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16471. }
  16472. }
  16473. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16474. this._intermediateRendering = false;
  16475. this._renderId++;
  16476. needsRestoreFrameBuffer = true; // Restore back buffer
  16477. }
  16478. // Render HighlightLayer Texture
  16479. var stencilState = this._engine.getStencilBuffer();
  16480. var renderhighlights = false;
  16481. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  16482. this._intermediateRendering = true;
  16483. for (var i = 0; i < this.highlightLayers.length; i++) {
  16484. var highlightLayer = this.highlightLayers[i];
  16485. if (highlightLayer.shouldRender() &&
  16486. (!highlightLayer.camera ||
  16487. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  16488. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  16489. renderhighlights = true;
  16490. var renderTarget = highlightLayer._mainTexture;
  16491. if (renderTarget._shouldRender()) {
  16492. this._renderId++;
  16493. renderTarget.render(false, false);
  16494. needsRestoreFrameBuffer = true;
  16495. }
  16496. }
  16497. }
  16498. this._intermediateRendering = false;
  16499. this._renderId++;
  16500. }
  16501. if (needsRestoreFrameBuffer) {
  16502. engine.restoreDefaultFramebuffer();
  16503. }
  16504. this._renderTargetsDuration.endMonitoring(false);
  16505. // Prepare Frame
  16506. this.postProcessManager._prepareFrame();
  16507. this._renderDuration.beginMonitoring();
  16508. // Backgrounds
  16509. var layerIndex;
  16510. var layer;
  16511. if (this.layers.length) {
  16512. engine.setDepthBuffer(false);
  16513. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16514. layer = this.layers[layerIndex];
  16515. if (layer.isBackground) {
  16516. layer.render();
  16517. }
  16518. }
  16519. engine.setDepthBuffer(true);
  16520. }
  16521. // Render
  16522. BABYLON.Tools.StartPerformanceCounter("Main render");
  16523. // Activate HighlightLayer stencil
  16524. if (renderhighlights) {
  16525. this._engine.setStencilBuffer(true);
  16526. }
  16527. this._renderingManager.render(null, null, true, true);
  16528. // Restore HighlightLayer stencil
  16529. if (renderhighlights) {
  16530. this._engine.setStencilBuffer(stencilState);
  16531. }
  16532. BABYLON.Tools.EndPerformanceCounter("Main render");
  16533. // Bounding boxes
  16534. if (this._boundingBoxRenderer) {
  16535. this._boundingBoxRenderer.render();
  16536. }
  16537. // Edges
  16538. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16539. this._edgesRenderers.data[edgesRendererIndex].render();
  16540. }
  16541. // Lens flares
  16542. if (this.lensFlaresEnabled) {
  16543. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16544. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16545. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16546. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16547. lensFlareSystem.render();
  16548. }
  16549. }
  16550. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16551. }
  16552. // Foregrounds
  16553. if (this.layers.length) {
  16554. engine.setDepthBuffer(false);
  16555. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16556. layer = this.layers[layerIndex];
  16557. if (!layer.isBackground) {
  16558. layer.render();
  16559. }
  16560. }
  16561. engine.setDepthBuffer(true);
  16562. }
  16563. // Highlight Layer
  16564. if (renderhighlights) {
  16565. engine.setDepthBuffer(false);
  16566. for (var i = 0; i < this.highlightLayers.length; i++) {
  16567. if (this.highlightLayers[i].shouldRender()) {
  16568. this.highlightLayers[i].render();
  16569. }
  16570. }
  16571. engine.setDepthBuffer(true);
  16572. }
  16573. this._renderDuration.endMonitoring(false);
  16574. // Finalize frame
  16575. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16576. // Update camera
  16577. this.activeCamera._updateFromScene();
  16578. // Reset some special arrays
  16579. this._renderTargets.reset();
  16580. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16581. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16582. };
  16583. Scene.prototype._processSubCameras = function (camera) {
  16584. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16585. this._renderForCamera(camera);
  16586. return;
  16587. }
  16588. // rig cameras
  16589. for (var index = 0; index < camera._rigCameras.length; index++) {
  16590. this._renderForCamera(camera._rigCameras[index]);
  16591. }
  16592. this.activeCamera = camera;
  16593. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16594. // Update camera
  16595. this.activeCamera._updateFromScene();
  16596. };
  16597. Scene.prototype._checkIntersections = function () {
  16598. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16599. var sourceMesh = this._meshesForIntersections.data[index];
  16600. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16601. var action = sourceMesh.actionManager.actions[actionIndex];
  16602. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16603. var parameters = action.getTriggerParameter();
  16604. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16605. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16606. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16607. if (areIntersecting && currentIntersectionInProgress === -1) {
  16608. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16609. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16610. sourceMesh._intersectionsInProgress.push(otherMesh);
  16611. }
  16612. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16613. sourceMesh._intersectionsInProgress.push(otherMesh);
  16614. }
  16615. }
  16616. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16617. //They intersected, and now they don't.
  16618. //is this trigger an exit trigger? execute an event.
  16619. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16620. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16621. }
  16622. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16623. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16624. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16625. }
  16626. }
  16627. }
  16628. }
  16629. }
  16630. };
  16631. Scene.prototype.render = function () {
  16632. if (this.isDisposed) {
  16633. return;
  16634. }
  16635. this._lastFrameDuration.beginMonitoring();
  16636. this._particlesDuration.fetchNewFrame();
  16637. this._spritesDuration.fetchNewFrame();
  16638. this._activeParticles.fetchNewFrame();
  16639. this._renderDuration.fetchNewFrame();
  16640. this._renderTargetsDuration.fetchNewFrame();
  16641. this._evaluateActiveMeshesDuration.fetchNewFrame();
  16642. this._totalVertices.fetchNewFrame();
  16643. this._activeIndices.fetchNewFrame();
  16644. this._activeBones.fetchNewFrame();
  16645. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  16646. this._meshesForIntersections.reset();
  16647. this.resetCachedMaterial();
  16648. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16649. // Actions
  16650. if (this.actionManager) {
  16651. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16652. }
  16653. //Simplification Queue
  16654. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16655. this.simplificationQueue.executeNext();
  16656. }
  16657. // Animations
  16658. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16659. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16660. this._animate();
  16661. // Physics
  16662. if (this._physicsEngine) {
  16663. BABYLON.Tools.StartPerformanceCounter("Physics");
  16664. this._physicsEngine._step(deltaTime / 1000.0);
  16665. BABYLON.Tools.EndPerformanceCounter("Physics");
  16666. }
  16667. // Before render
  16668. this.onBeforeRenderObservable.notifyObservers(this);
  16669. // Customs render targets
  16670. this._renderTargetsDuration.beginMonitoring();
  16671. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16672. var engine = this.getEngine();
  16673. var currentActiveCamera = this.activeCamera;
  16674. if (this.renderTargetsEnabled) {
  16675. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16676. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16677. var renderTarget = this.customRenderTargets[customIndex];
  16678. if (renderTarget._shouldRender()) {
  16679. this._renderId++;
  16680. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16681. if (!this.activeCamera)
  16682. throw new Error("Active camera not set");
  16683. // Viewport
  16684. engine.setViewport(this.activeCamera.viewport);
  16685. // Camera
  16686. this.updateTransformMatrix();
  16687. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16688. }
  16689. }
  16690. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16691. this._renderId++;
  16692. }
  16693. if (this.customRenderTargets.length > 0) {
  16694. engine.restoreDefaultFramebuffer();
  16695. }
  16696. this._renderTargetsDuration.endMonitoring();
  16697. this.activeCamera = currentActiveCamera;
  16698. // Procedural textures
  16699. if (this.proceduralTexturesEnabled) {
  16700. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16701. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16702. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16703. if (proceduralTexture._shouldRender()) {
  16704. proceduralTexture.render();
  16705. }
  16706. }
  16707. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16708. }
  16709. // Clear
  16710. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  16711. // Shadows
  16712. if (this.shadowsEnabled) {
  16713. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16714. var light = this.lights[lightIndex];
  16715. var shadowGenerator = light.getShadowGenerator();
  16716. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16717. this._renderTargets.push(shadowGenerator.getShadowMap());
  16718. }
  16719. }
  16720. }
  16721. // Depth renderer
  16722. if (this._depthRenderer) {
  16723. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16724. }
  16725. // RenderPipeline
  16726. if (this._postProcessRenderPipelineManager) {
  16727. this._postProcessRenderPipelineManager.update();
  16728. }
  16729. // Multi-cameras?
  16730. if (this.activeCameras.length > 0) {
  16731. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16732. if (cameraIndex > 0) {
  16733. this._engine.clear(null, false, true, true);
  16734. }
  16735. this._processSubCameras(this.activeCameras[cameraIndex]);
  16736. }
  16737. }
  16738. else {
  16739. if (!this.activeCamera) {
  16740. throw new Error("No camera defined");
  16741. }
  16742. this._processSubCameras(this.activeCamera);
  16743. }
  16744. // Intersection checks
  16745. this._checkIntersections();
  16746. // Update the audio listener attached to the camera
  16747. if (BABYLON.AudioEngine) {
  16748. this._updateAudioParameters();
  16749. }
  16750. // After render
  16751. if (this.afterRender) {
  16752. this.afterRender();
  16753. }
  16754. this.onAfterRenderObservable.notifyObservers(this);
  16755. // Cleaning
  16756. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16757. this._toBeDisposed.data[index].dispose();
  16758. this._toBeDisposed[index] = null;
  16759. }
  16760. this._toBeDisposed.reset();
  16761. if (this.dumpNextRenderTargets) {
  16762. this.dumpNextRenderTargets = false;
  16763. }
  16764. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16765. this._lastFrameDuration.endMonitoring();
  16766. this._totalMeshesCounter.addCount(this.meshes.length, true);
  16767. this._totalLightsCounter.addCount(this.lights.length, true);
  16768. this._totalMaterialsCounter.addCount(this.materials.length, true);
  16769. this._totalTexturesCounter.addCount(this.textures.length, true);
  16770. this._activeBones.addCount(0, true);
  16771. this._activeIndices.addCount(0, true);
  16772. this._activeParticles.addCount(0, true);
  16773. };
  16774. Scene.prototype._updateAudioParameters = function () {
  16775. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16776. return;
  16777. }
  16778. var listeningCamera;
  16779. var audioEngine = BABYLON.Engine.audioEngine;
  16780. if (this.activeCameras.length > 0) {
  16781. listeningCamera = this.activeCameras[0];
  16782. }
  16783. else {
  16784. listeningCamera = this.activeCamera;
  16785. }
  16786. if (listeningCamera && audioEngine.canUseWebAudio) {
  16787. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16788. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16789. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16790. cameraDirection.normalize();
  16791. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16792. var i;
  16793. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16794. var sound = this.mainSoundTrack.soundCollection[i];
  16795. if (sound.useCustomAttenuation) {
  16796. sound.updateDistanceFromListener();
  16797. }
  16798. }
  16799. for (i = 0; i < this.soundTracks.length; i++) {
  16800. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16801. sound = this.soundTracks[i].soundCollection[j];
  16802. if (sound.useCustomAttenuation) {
  16803. sound.updateDistanceFromListener();
  16804. }
  16805. }
  16806. }
  16807. }
  16808. };
  16809. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16810. // Audio
  16811. get: function () {
  16812. return this._audioEnabled;
  16813. },
  16814. set: function (value) {
  16815. this._audioEnabled = value;
  16816. if (BABYLON.AudioEngine) {
  16817. if (this._audioEnabled) {
  16818. this._enableAudio();
  16819. }
  16820. else {
  16821. this._disableAudio();
  16822. }
  16823. }
  16824. },
  16825. enumerable: true,
  16826. configurable: true
  16827. });
  16828. Scene.prototype._disableAudio = function () {
  16829. var i;
  16830. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16831. this.mainSoundTrack.soundCollection[i].pause();
  16832. }
  16833. for (i = 0; i < this.soundTracks.length; i++) {
  16834. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16835. this.soundTracks[i].soundCollection[j].pause();
  16836. }
  16837. }
  16838. };
  16839. Scene.prototype._enableAudio = function () {
  16840. var i;
  16841. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16842. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16843. this.mainSoundTrack.soundCollection[i].play();
  16844. }
  16845. }
  16846. for (i = 0; i < this.soundTracks.length; i++) {
  16847. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16848. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16849. this.soundTracks[i].soundCollection[j].play();
  16850. }
  16851. }
  16852. }
  16853. };
  16854. Object.defineProperty(Scene.prototype, "headphone", {
  16855. get: function () {
  16856. return this._headphone;
  16857. },
  16858. set: function (value) {
  16859. this._headphone = value;
  16860. if (BABYLON.AudioEngine) {
  16861. if (this._headphone) {
  16862. this._switchAudioModeForHeadphones();
  16863. }
  16864. else {
  16865. this._switchAudioModeForNormalSpeakers();
  16866. }
  16867. }
  16868. },
  16869. enumerable: true,
  16870. configurable: true
  16871. });
  16872. Scene.prototype._switchAudioModeForHeadphones = function () {
  16873. this.mainSoundTrack.switchPanningModelToHRTF();
  16874. for (var i = 0; i < this.soundTracks.length; i++) {
  16875. this.soundTracks[i].switchPanningModelToHRTF();
  16876. }
  16877. };
  16878. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16879. this.mainSoundTrack.switchPanningModelToEqualPower();
  16880. for (var i = 0; i < this.soundTracks.length; i++) {
  16881. this.soundTracks[i].switchPanningModelToEqualPower();
  16882. }
  16883. };
  16884. Scene.prototype.enableDepthRenderer = function () {
  16885. if (this._depthRenderer) {
  16886. return this._depthRenderer;
  16887. }
  16888. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16889. return this._depthRenderer;
  16890. };
  16891. Scene.prototype.disableDepthRenderer = function () {
  16892. if (!this._depthRenderer) {
  16893. return;
  16894. }
  16895. this._depthRenderer.dispose();
  16896. this._depthRenderer = null;
  16897. };
  16898. Scene.prototype.freezeMaterials = function () {
  16899. for (var i = 0; i < this.materials.length; i++) {
  16900. this.materials[i].freeze();
  16901. }
  16902. };
  16903. Scene.prototype.unfreezeMaterials = function () {
  16904. for (var i = 0; i < this.materials.length; i++) {
  16905. this.materials[i].unfreeze();
  16906. }
  16907. };
  16908. Scene.prototype.dispose = function () {
  16909. this.beforeRender = null;
  16910. this.afterRender = null;
  16911. this.skeletons = [];
  16912. this.morphTargetManagers = [];
  16913. if (this._depthRenderer) {
  16914. this._depthRenderer.dispose();
  16915. }
  16916. // Smart arrays
  16917. if (this.activeCamera) {
  16918. this.activeCamera._activeMeshes.dispose();
  16919. this.activeCamera = null;
  16920. }
  16921. this._activeMeshes.dispose();
  16922. this._renderingManager.dispose();
  16923. this._processedMaterials.dispose();
  16924. this._activeParticleSystems.dispose();
  16925. this._activeSkeletons.dispose();
  16926. this._softwareSkinnedMeshes.dispose();
  16927. if (this._boundingBoxRenderer) {
  16928. this._boundingBoxRenderer.dispose();
  16929. }
  16930. this._edgesRenderers.dispose();
  16931. this._meshesForIntersections.dispose();
  16932. this._toBeDisposed.dispose();
  16933. // Debug layer
  16934. if (this._debugLayer) {
  16935. this._debugLayer.hide();
  16936. }
  16937. // Events
  16938. this.onDisposeObservable.notifyObservers(this);
  16939. this.onDisposeObservable.clear();
  16940. this.onBeforeRenderObservable.clear();
  16941. this.onAfterRenderObservable.clear();
  16942. this.detachControl();
  16943. // Release sounds & sounds tracks
  16944. if (BABYLON.AudioEngine) {
  16945. this.disposeSounds();
  16946. }
  16947. // Detach cameras
  16948. var canvas = this._engine.getRenderingCanvas();
  16949. var index;
  16950. for (index = 0; index < this.cameras.length; index++) {
  16951. this.cameras[index].detachControl(canvas);
  16952. }
  16953. // Release lights
  16954. while (this.lights.length) {
  16955. this.lights[0].dispose();
  16956. }
  16957. // Release meshes
  16958. while (this.meshes.length) {
  16959. this.meshes[0].dispose(true);
  16960. }
  16961. // Release cameras
  16962. while (this.cameras.length) {
  16963. this.cameras[0].dispose();
  16964. }
  16965. // Release materials
  16966. while (this.materials.length) {
  16967. this.materials[0].dispose();
  16968. }
  16969. // Release particles
  16970. while (this.particleSystems.length) {
  16971. this.particleSystems[0].dispose();
  16972. }
  16973. // Release sprites
  16974. while (this.spriteManagers.length) {
  16975. this.spriteManagers[0].dispose();
  16976. }
  16977. // Release layers
  16978. while (this.layers.length) {
  16979. this.layers[0].dispose();
  16980. }
  16981. while (this.highlightLayers.length) {
  16982. this.highlightLayers[0].dispose();
  16983. }
  16984. // Release textures
  16985. while (this.textures.length) {
  16986. this.textures[0].dispose();
  16987. }
  16988. // Post-processes
  16989. this.postProcessManager.dispose();
  16990. // Physics
  16991. if (this._physicsEngine) {
  16992. this.disablePhysicsEngine();
  16993. }
  16994. // Remove from engine
  16995. index = this._engine.scenes.indexOf(this);
  16996. if (index > -1) {
  16997. this._engine.scenes.splice(index, 1);
  16998. }
  16999. this._engine.wipeCaches();
  17000. this._engine = null;
  17001. };
  17002. Object.defineProperty(Scene.prototype, "isDisposed", {
  17003. get: function () {
  17004. return !this._engine;
  17005. },
  17006. enumerable: true,
  17007. configurable: true
  17008. });
  17009. // Release sounds & sounds tracks
  17010. Scene.prototype.disposeSounds = function () {
  17011. this.mainSoundTrack.dispose();
  17012. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17013. this.soundTracks[scIndex].dispose();
  17014. }
  17015. };
  17016. // Octrees
  17017. Scene.prototype.getWorldExtends = function () {
  17018. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17019. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17020. for (var index = 0; index < this.meshes.length; index++) {
  17021. var mesh = this.meshes[index];
  17022. mesh.computeWorldMatrix(true);
  17023. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17024. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17025. BABYLON.Tools.CheckExtends(minBox, min, max);
  17026. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17027. }
  17028. return {
  17029. min: min,
  17030. max: max
  17031. };
  17032. };
  17033. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17034. if (maxCapacity === void 0) { maxCapacity = 64; }
  17035. if (maxDepth === void 0) { maxDepth = 2; }
  17036. if (!this._selectionOctree) {
  17037. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17038. }
  17039. var worldExtends = this.getWorldExtends();
  17040. // Update octree
  17041. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17042. return this._selectionOctree;
  17043. };
  17044. // Picking
  17045. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17046. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17047. var engine = this._engine;
  17048. if (!camera) {
  17049. if (!this.activeCamera)
  17050. throw new Error("Active camera not set");
  17051. camera = this.activeCamera;
  17052. }
  17053. var cameraViewport = camera.viewport;
  17054. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17055. // Moving coordinates to local viewport world
  17056. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17057. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17058. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17059. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17060. };
  17061. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17062. if (!BABYLON.PickingInfo) {
  17063. return null;
  17064. }
  17065. var engine = this._engine;
  17066. if (!camera) {
  17067. if (!this.activeCamera)
  17068. throw new Error("Active camera not set");
  17069. camera = this.activeCamera;
  17070. }
  17071. var cameraViewport = camera.viewport;
  17072. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17073. var identity = BABYLON.Matrix.Identity();
  17074. // Moving coordinates to local viewport world
  17075. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17076. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17077. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17078. };
  17079. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17080. if (!BABYLON.PickingInfo) {
  17081. return null;
  17082. }
  17083. var pickingInfo = null;
  17084. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17085. var mesh = this.meshes[meshIndex];
  17086. if (predicate) {
  17087. if (!predicate(mesh)) {
  17088. continue;
  17089. }
  17090. }
  17091. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17092. continue;
  17093. }
  17094. var world = mesh.getWorldMatrix();
  17095. var ray = rayFunction(world);
  17096. var result = mesh.intersects(ray, fastCheck);
  17097. if (!result || !result.hit)
  17098. continue;
  17099. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17100. continue;
  17101. pickingInfo = result;
  17102. if (fastCheck) {
  17103. break;
  17104. }
  17105. }
  17106. return pickingInfo || new BABYLON.PickingInfo();
  17107. };
  17108. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  17109. if (!BABYLON.PickingInfo) {
  17110. return null;
  17111. }
  17112. var pickingInfos = new Array();
  17113. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17114. var mesh = this.meshes[meshIndex];
  17115. if (predicate) {
  17116. if (!predicate(mesh)) {
  17117. continue;
  17118. }
  17119. }
  17120. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17121. continue;
  17122. }
  17123. var world = mesh.getWorldMatrix();
  17124. var ray = rayFunction(world);
  17125. var result = mesh.intersects(ray, false);
  17126. if (!result || !result.hit)
  17127. continue;
  17128. pickingInfos.push(result);
  17129. }
  17130. return pickingInfos;
  17131. };
  17132. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17133. if (!BABYLON.PickingInfo) {
  17134. return null;
  17135. }
  17136. var pickingInfo = null;
  17137. camera = camera || this.activeCamera;
  17138. if (this.spriteManagers.length > 0) {
  17139. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17140. var spriteManager = this.spriteManagers[spriteIndex];
  17141. if (!spriteManager.isPickable) {
  17142. continue;
  17143. }
  17144. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17145. if (!result || !result.hit)
  17146. continue;
  17147. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17148. continue;
  17149. pickingInfo = result;
  17150. if (fastCheck) {
  17151. break;
  17152. }
  17153. }
  17154. }
  17155. return pickingInfo || new BABYLON.PickingInfo();
  17156. };
  17157. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17158. /// <param name="x">X position on screen</param>
  17159. /// <param name="y">Y position on screen</param>
  17160. /// <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>
  17161. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17162. /// <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>
  17163. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17164. var _this = this;
  17165. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17166. };
  17167. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17168. /// <param name="x">X position on screen</param>
  17169. /// <param name="y">Y position on screen</param>
  17170. /// <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>
  17171. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17172. /// <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>
  17173. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17174. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17175. };
  17176. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17177. var _this = this;
  17178. return this._internalPick(function (world) {
  17179. if (!_this._pickWithRayInverseMatrix) {
  17180. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17181. }
  17182. world.invertToRef(_this._pickWithRayInverseMatrix);
  17183. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17184. }, predicate, fastCheck);
  17185. };
  17186. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17187. /// <param name="x">X position on screen</param>
  17188. /// <param name="y">Y position on screen</param>
  17189. /// <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>
  17190. /// <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>
  17191. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  17192. var _this = this;
  17193. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  17194. };
  17195. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17196. /// <param name="ray">Ray to use</param>
  17197. /// <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>
  17198. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  17199. var _this = this;
  17200. return this._internalMultiPick(function (world) {
  17201. if (!_this._pickWithRayInverseMatrix) {
  17202. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17203. }
  17204. world.invertToRef(_this._pickWithRayInverseMatrix);
  17205. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17206. }, predicate);
  17207. };
  17208. Scene.prototype.setPointerOverMesh = function (mesh) {
  17209. if (this._pointerOverMesh === mesh) {
  17210. return;
  17211. }
  17212. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17213. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17214. }
  17215. this._pointerOverMesh = mesh;
  17216. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17217. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17218. }
  17219. };
  17220. Scene.prototype.getPointerOverMesh = function () {
  17221. return this._pointerOverMesh;
  17222. };
  17223. Scene.prototype.setPointerOverSprite = function (sprite) {
  17224. if (this._pointerOverSprite === sprite) {
  17225. return;
  17226. }
  17227. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17228. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17229. }
  17230. this._pointerOverSprite = sprite;
  17231. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17232. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17233. }
  17234. };
  17235. Scene.prototype.getPointerOverSprite = function () {
  17236. return this._pointerOverSprite;
  17237. };
  17238. // Physics
  17239. Scene.prototype.getPhysicsEngine = function () {
  17240. return this._physicsEngine;
  17241. };
  17242. /**
  17243. * Enables physics to the current scene
  17244. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17245. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17246. * @return {boolean} was the physics engine initialized
  17247. */
  17248. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17249. if (this._physicsEngine) {
  17250. return true;
  17251. }
  17252. try {
  17253. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17254. return true;
  17255. }
  17256. catch (e) {
  17257. BABYLON.Tools.Error(e.message);
  17258. return false;
  17259. }
  17260. };
  17261. Scene.prototype.disablePhysicsEngine = function () {
  17262. if (!this._physicsEngine) {
  17263. return;
  17264. }
  17265. this._physicsEngine.dispose();
  17266. this._physicsEngine = undefined;
  17267. };
  17268. Scene.prototype.isPhysicsEnabled = function () {
  17269. return this._physicsEngine !== undefined;
  17270. };
  17271. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17272. var mesh = compound.parts[0].mesh;
  17273. mesh.physicsImpostor.dispose();
  17274. mesh.physicsImpostor = null;
  17275. };
  17276. // Misc.
  17277. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  17278. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  17279. // Light
  17280. if (this.lights.length === 0) {
  17281. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17282. }
  17283. // Camera
  17284. if (!this.activeCamera) {
  17285. // Compute position
  17286. var worldExtends = this.getWorldExtends();
  17287. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17288. var camera;
  17289. if (createArcRotateCamera) {
  17290. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  17291. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  17292. camera.lowerRadiusLimit = 0.5;
  17293. camera.setTarget(worldCenter);
  17294. }
  17295. else {
  17296. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17297. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17298. camera.setTarget(worldCenter);
  17299. }
  17300. camera.minZ = 0.1;
  17301. var maxDist = worldExtends.max.subtract(worldExtends.min).length();
  17302. camera.wheelPrecision = 100.0 / maxDist;
  17303. this.activeCamera = camera;
  17304. }
  17305. };
  17306. // Tags
  17307. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17308. if (tagsQuery === undefined) {
  17309. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17310. return list;
  17311. }
  17312. var listByTags = [];
  17313. forEach = forEach || (function (item) { return; });
  17314. for (var i in list) {
  17315. var item = list[i];
  17316. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17317. listByTags.push(item);
  17318. forEach(item);
  17319. }
  17320. }
  17321. return listByTags;
  17322. };
  17323. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17324. return this._getByTags(this.meshes, tagsQuery, forEach);
  17325. };
  17326. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17327. return this._getByTags(this.cameras, tagsQuery, forEach);
  17328. };
  17329. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17330. return this._getByTags(this.lights, tagsQuery, forEach);
  17331. };
  17332. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17333. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17334. };
  17335. /**
  17336. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17337. * This allowed control for front to back rendering or reversly depending of the special needs.
  17338. *
  17339. * @param renderingGroupId The rendering group id corresponding to its index
  17340. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17341. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17342. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17343. */
  17344. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17345. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17346. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17347. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17348. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  17349. };
  17350. /**
  17351. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17352. *
  17353. * @param renderingGroupId The rendering group id corresponding to its index
  17354. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17355. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17356. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17357. */
  17358. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17359. if (depth === void 0) { depth = true; }
  17360. if (stencil === void 0) { stencil = true; }
  17361. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  17362. };
  17363. /**
  17364. * Will flag all materials as dirty to trigger new shader compilation
  17365. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  17366. */
  17367. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  17368. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  17369. var material = _a[_i];
  17370. if (predicate && !predicate(material)) {
  17371. continue;
  17372. }
  17373. material.markAsDirty(flag);
  17374. }
  17375. };
  17376. return Scene;
  17377. }());
  17378. // Statics
  17379. Scene._FOGMODE_NONE = 0;
  17380. Scene._FOGMODE_EXP = 1;
  17381. Scene._FOGMODE_EXP2 = 2;
  17382. Scene._FOGMODE_LINEAR = 3;
  17383. Scene.MinDeltaTime = 1.0;
  17384. Scene.MaxDeltaTime = 1000.0;
  17385. Scene.DragMovementThreshold = 10; // in pixels
  17386. Scene.LongPressDelay = 500; // in milliseconds
  17387. Scene.DoubleClickDelay = 300; // in milliseconds
  17388. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  17389. BABYLON.Scene = Scene;
  17390. })(BABYLON || (BABYLON = {}));
  17391. //# sourceMappingURL=babylon.scene.js.map
  17392. var BABYLON;
  17393. (function (BABYLON) {
  17394. var Buffer = (function () {
  17395. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17396. if (engine instanceof BABYLON.Mesh) {
  17397. this._engine = engine.getScene().getEngine();
  17398. }
  17399. else {
  17400. this._engine = engine;
  17401. }
  17402. this._updatable = updatable;
  17403. this._data = data;
  17404. this._strideSize = stride;
  17405. if (!postponeInternalCreation) {
  17406. this.create();
  17407. }
  17408. this._instanced = instanced;
  17409. }
  17410. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17411. // a lot of these parameters are ignored as they are overriden by the buffer
  17412. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17413. };
  17414. // Properties
  17415. Buffer.prototype.isUpdatable = function () {
  17416. return this._updatable;
  17417. };
  17418. Buffer.prototype.getData = function () {
  17419. return this._data;
  17420. };
  17421. Buffer.prototype.getBuffer = function () {
  17422. return this._buffer;
  17423. };
  17424. Buffer.prototype.getStrideSize = function () {
  17425. return this._strideSize;
  17426. };
  17427. Buffer.prototype.getIsInstanced = function () {
  17428. return this._instanced;
  17429. };
  17430. // Methods
  17431. Buffer.prototype.create = function (data) {
  17432. if (!data && this._buffer) {
  17433. return; // nothing to do
  17434. }
  17435. data = data || this._data;
  17436. if (!this._buffer) {
  17437. if (this._updatable) {
  17438. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17439. this._data = data;
  17440. }
  17441. else {
  17442. this._buffer = this._engine.createVertexBuffer(data);
  17443. }
  17444. }
  17445. else if (this._updatable) {
  17446. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17447. this._data = data;
  17448. }
  17449. };
  17450. Buffer.prototype.update = function (data) {
  17451. this.create(data);
  17452. };
  17453. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17454. if (!this._buffer) {
  17455. return;
  17456. }
  17457. if (this._updatable) {
  17458. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17459. this._data = null;
  17460. }
  17461. };
  17462. Buffer.prototype.dispose = function () {
  17463. if (!this._buffer) {
  17464. return;
  17465. }
  17466. if (this._engine._releaseBuffer(this._buffer)) {
  17467. this._buffer = null;
  17468. }
  17469. };
  17470. return Buffer;
  17471. }());
  17472. BABYLON.Buffer = Buffer;
  17473. })(BABYLON || (BABYLON = {}));
  17474. //# sourceMappingURL=babylon.buffer.js.map
  17475. var BABYLON;
  17476. (function (BABYLON) {
  17477. var VertexBuffer = (function () {
  17478. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17479. if (!stride) {
  17480. // Deduce stride from kind
  17481. switch (kind) {
  17482. case VertexBuffer.PositionKind:
  17483. stride = 3;
  17484. break;
  17485. case VertexBuffer.NormalKind:
  17486. stride = 3;
  17487. break;
  17488. case VertexBuffer.UVKind:
  17489. case VertexBuffer.UV2Kind:
  17490. case VertexBuffer.UV3Kind:
  17491. case VertexBuffer.UV4Kind:
  17492. case VertexBuffer.UV5Kind:
  17493. case VertexBuffer.UV6Kind:
  17494. stride = 2;
  17495. break;
  17496. case VertexBuffer.TangentKind:
  17497. case VertexBuffer.ColorKind:
  17498. stride = 4;
  17499. break;
  17500. case VertexBuffer.MatricesIndicesKind:
  17501. case VertexBuffer.MatricesIndicesExtraKind:
  17502. stride = 4;
  17503. break;
  17504. case VertexBuffer.MatricesWeightsKind:
  17505. case VertexBuffer.MatricesWeightsExtraKind:
  17506. stride = 4;
  17507. break;
  17508. }
  17509. }
  17510. if (data instanceof BABYLON.Buffer) {
  17511. if (!stride) {
  17512. stride = data.getStrideSize();
  17513. }
  17514. this._buffer = data;
  17515. this._ownsBuffer = false;
  17516. }
  17517. else {
  17518. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17519. this._ownsBuffer = true;
  17520. }
  17521. this._stride = stride;
  17522. this._offset = offset ? offset : 0;
  17523. this._size = size ? size : stride;
  17524. this._kind = kind;
  17525. }
  17526. /**
  17527. * Returns the kind of the VertexBuffer (string).
  17528. */
  17529. VertexBuffer.prototype.getKind = function () {
  17530. return this._kind;
  17531. };
  17532. // Properties
  17533. /**
  17534. * Boolean : is the VertexBuffer updatable ?
  17535. */
  17536. VertexBuffer.prototype.isUpdatable = function () {
  17537. return this._buffer.isUpdatable();
  17538. };
  17539. /**
  17540. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  17541. */
  17542. VertexBuffer.prototype.getData = function () {
  17543. return this._buffer.getData();
  17544. };
  17545. /**
  17546. * Returns the WebGLBuffer associated to the VertexBuffer.
  17547. */
  17548. VertexBuffer.prototype.getBuffer = function () {
  17549. return this._buffer.getBuffer();
  17550. };
  17551. /**
  17552. * Returns the stride of the VertexBuffer (integer).
  17553. */
  17554. VertexBuffer.prototype.getStrideSize = function () {
  17555. return this._stride;
  17556. };
  17557. /**
  17558. * Returns the offset (integer).
  17559. */
  17560. VertexBuffer.prototype.getOffset = function () {
  17561. return this._offset;
  17562. };
  17563. /**
  17564. * Returns the VertexBuffer total size (integer).
  17565. */
  17566. VertexBuffer.prototype.getSize = function () {
  17567. return this._size;
  17568. };
  17569. /**
  17570. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  17571. */
  17572. VertexBuffer.prototype.getIsInstanced = function () {
  17573. return this._buffer.getIsInstanced();
  17574. };
  17575. // Methods
  17576. /**
  17577. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  17578. * Returns the created WebGLBuffer.
  17579. */
  17580. VertexBuffer.prototype.create = function (data) {
  17581. return this._buffer.create(data);
  17582. };
  17583. /**
  17584. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17585. * Returns the updated WebGLBuffer.
  17586. */
  17587. VertexBuffer.prototype.update = function (data) {
  17588. return this._buffer.update(data);
  17589. };
  17590. /**
  17591. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17592. * Returns the directly updated WebGLBuffer.
  17593. */
  17594. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17595. return this._buffer.updateDirectly(data, offset);
  17596. };
  17597. /**
  17598. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  17599. */
  17600. VertexBuffer.prototype.dispose = function () {
  17601. if (this._ownsBuffer) {
  17602. this._buffer.dispose();
  17603. }
  17604. };
  17605. Object.defineProperty(VertexBuffer, "PositionKind", {
  17606. get: function () {
  17607. return VertexBuffer._PositionKind;
  17608. },
  17609. enumerable: true,
  17610. configurable: true
  17611. });
  17612. Object.defineProperty(VertexBuffer, "NormalKind", {
  17613. get: function () {
  17614. return VertexBuffer._NormalKind;
  17615. },
  17616. enumerable: true,
  17617. configurable: true
  17618. });
  17619. Object.defineProperty(VertexBuffer, "TangentKind", {
  17620. get: function () {
  17621. return VertexBuffer._TangentKind;
  17622. },
  17623. enumerable: true,
  17624. configurable: true
  17625. });
  17626. Object.defineProperty(VertexBuffer, "UVKind", {
  17627. get: function () {
  17628. return VertexBuffer._UVKind;
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17634. get: function () {
  17635. return VertexBuffer._UV2Kind;
  17636. },
  17637. enumerable: true,
  17638. configurable: true
  17639. });
  17640. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17641. get: function () {
  17642. return VertexBuffer._UV3Kind;
  17643. },
  17644. enumerable: true,
  17645. configurable: true
  17646. });
  17647. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17648. get: function () {
  17649. return VertexBuffer._UV4Kind;
  17650. },
  17651. enumerable: true,
  17652. configurable: true
  17653. });
  17654. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17655. get: function () {
  17656. return VertexBuffer._UV5Kind;
  17657. },
  17658. enumerable: true,
  17659. configurable: true
  17660. });
  17661. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17662. get: function () {
  17663. return VertexBuffer._UV6Kind;
  17664. },
  17665. enumerable: true,
  17666. configurable: true
  17667. });
  17668. Object.defineProperty(VertexBuffer, "ColorKind", {
  17669. get: function () {
  17670. return VertexBuffer._ColorKind;
  17671. },
  17672. enumerable: true,
  17673. configurable: true
  17674. });
  17675. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17676. get: function () {
  17677. return VertexBuffer._MatricesIndicesKind;
  17678. },
  17679. enumerable: true,
  17680. configurable: true
  17681. });
  17682. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17683. get: function () {
  17684. return VertexBuffer._MatricesWeightsKind;
  17685. },
  17686. enumerable: true,
  17687. configurable: true
  17688. });
  17689. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17690. get: function () {
  17691. return VertexBuffer._MatricesIndicesExtraKind;
  17692. },
  17693. enumerable: true,
  17694. configurable: true
  17695. });
  17696. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17697. get: function () {
  17698. return VertexBuffer._MatricesWeightsExtraKind;
  17699. },
  17700. enumerable: true,
  17701. configurable: true
  17702. });
  17703. return VertexBuffer;
  17704. }());
  17705. // Enums
  17706. VertexBuffer._PositionKind = "position";
  17707. VertexBuffer._NormalKind = "normal";
  17708. VertexBuffer._TangentKind = "tangent";
  17709. VertexBuffer._UVKind = "uv";
  17710. VertexBuffer._UV2Kind = "uv2";
  17711. VertexBuffer._UV3Kind = "uv3";
  17712. VertexBuffer._UV4Kind = "uv4";
  17713. VertexBuffer._UV5Kind = "uv5";
  17714. VertexBuffer._UV6Kind = "uv6";
  17715. VertexBuffer._ColorKind = "color";
  17716. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17717. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17718. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17719. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17720. BABYLON.VertexBuffer = VertexBuffer;
  17721. })(BABYLON || (BABYLON = {}));
  17722. //# sourceMappingURL=babylon.vertexBuffer.js.map
  17723. var BABYLON;
  17724. (function (BABYLON) {
  17725. var BaseTexture = (function () {
  17726. function BaseTexture(scene) {
  17727. this._hasAlpha = false;
  17728. this.getAlphaFromRGB = false;
  17729. this.level = 1;
  17730. this.coordinatesIndex = 0;
  17731. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17732. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17733. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17734. this.anisotropicFilteringLevel = 4;
  17735. this.isCube = false;
  17736. this.isRenderTarget = false;
  17737. this.animations = new Array();
  17738. /**
  17739. * An event triggered when the texture is disposed.
  17740. * @type {BABYLON.Observable}
  17741. */
  17742. this.onDisposeObservable = new BABYLON.Observable();
  17743. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17744. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  17745. this._scene.textures.push(this);
  17746. this._uid = null;
  17747. }
  17748. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  17749. get: function () {
  17750. return this._hasAlpha;
  17751. },
  17752. set: function (value) {
  17753. if (this._hasAlpha === value) {
  17754. return;
  17755. }
  17756. this._hasAlpha = value;
  17757. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17758. },
  17759. enumerable: true,
  17760. configurable: true
  17761. });
  17762. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  17763. get: function () {
  17764. return this._coordinatesMode;
  17765. },
  17766. set: function (value) {
  17767. if (this._coordinatesMode === value) {
  17768. return;
  17769. }
  17770. this._coordinatesMode = value;
  17771. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17772. },
  17773. enumerable: true,
  17774. configurable: true
  17775. });
  17776. Object.defineProperty(BaseTexture.prototype, "uid", {
  17777. get: function () {
  17778. if (!this._uid) {
  17779. this._uid = BABYLON.Tools.RandomId();
  17780. }
  17781. return this._uid;
  17782. },
  17783. enumerable: true,
  17784. configurable: true
  17785. });
  17786. BaseTexture.prototype.toString = function () {
  17787. return this.name;
  17788. };
  17789. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  17790. set: function (callback) {
  17791. if (this._onDisposeObserver) {
  17792. this.onDisposeObservable.remove(this._onDisposeObserver);
  17793. }
  17794. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17795. },
  17796. enumerable: true,
  17797. configurable: true
  17798. });
  17799. BaseTexture.prototype.getScene = function () {
  17800. return this._scene;
  17801. };
  17802. BaseTexture.prototype.getTextureMatrix = function () {
  17803. return null;
  17804. };
  17805. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17806. return null;
  17807. };
  17808. BaseTexture.prototype.getInternalTexture = function () {
  17809. return this._texture;
  17810. };
  17811. BaseTexture.prototype.isReady = function () {
  17812. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17813. return true;
  17814. }
  17815. if (this._texture) {
  17816. return this._texture.isReady;
  17817. }
  17818. return false;
  17819. };
  17820. BaseTexture.prototype.getSize = function () {
  17821. if (this._texture._width) {
  17822. return new BABYLON.Size(this._texture._width, this._texture._height);
  17823. }
  17824. if (this._texture._size) {
  17825. return new BABYLON.Size(this._texture._size, this._texture._size);
  17826. }
  17827. return BABYLON.Size.Zero();
  17828. };
  17829. BaseTexture.prototype.getBaseSize = function () {
  17830. if (!this.isReady() || !this._texture)
  17831. return BABYLON.Size.Zero();
  17832. if (this._texture._size) {
  17833. return new BABYLON.Size(this._texture._size, this._texture._size);
  17834. }
  17835. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  17836. };
  17837. BaseTexture.prototype.scale = function (ratio) {
  17838. };
  17839. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17840. get: function () {
  17841. return false;
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17847. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17848. for (var index = 0; index < texturesCache.length; index++) {
  17849. var texturesCacheEntry = texturesCache[index];
  17850. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17851. texturesCache.splice(index, 1);
  17852. return;
  17853. }
  17854. }
  17855. };
  17856. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17857. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17858. for (var index = 0; index < texturesCache.length; index++) {
  17859. var texturesCacheEntry = texturesCache[index];
  17860. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17861. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17862. texturesCacheEntry.references++;
  17863. return texturesCacheEntry;
  17864. }
  17865. }
  17866. }
  17867. return null;
  17868. };
  17869. BaseTexture.prototype.delayLoad = function () {
  17870. };
  17871. BaseTexture.prototype.clone = function () {
  17872. return null;
  17873. };
  17874. BaseTexture.prototype.releaseInternalTexture = function () {
  17875. if (this._texture) {
  17876. this._scene.getEngine().releaseInternalTexture(this._texture);
  17877. delete this._texture;
  17878. }
  17879. };
  17880. BaseTexture.prototype.dispose = function () {
  17881. // Animations
  17882. this.getScene().stopAnimation(this);
  17883. // Remove from scene
  17884. this._scene._removePendingData(this);
  17885. var index = this._scene.textures.indexOf(this);
  17886. if (index >= 0) {
  17887. this._scene.textures.splice(index, 1);
  17888. }
  17889. if (this._texture === undefined) {
  17890. return;
  17891. }
  17892. // Release
  17893. this.releaseInternalTexture();
  17894. // Callback
  17895. this.onDisposeObservable.notifyObservers(this);
  17896. this.onDisposeObservable.clear();
  17897. };
  17898. BaseTexture.prototype.serialize = function () {
  17899. if (!this.name) {
  17900. return null;
  17901. }
  17902. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17903. // Animations
  17904. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17905. return serializationObject;
  17906. };
  17907. return BaseTexture;
  17908. }());
  17909. __decorate([
  17910. BABYLON.serialize()
  17911. ], BaseTexture.prototype, "name", void 0);
  17912. __decorate([
  17913. BABYLON.serialize("hasAlpha")
  17914. ], BaseTexture.prototype, "_hasAlpha", void 0);
  17915. __decorate([
  17916. BABYLON.serialize()
  17917. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  17918. __decorate([
  17919. BABYLON.serialize()
  17920. ], BaseTexture.prototype, "level", void 0);
  17921. __decorate([
  17922. BABYLON.serialize()
  17923. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  17924. __decorate([
  17925. BABYLON.serialize("coordinatesMode")
  17926. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  17927. __decorate([
  17928. BABYLON.serialize()
  17929. ], BaseTexture.prototype, "wrapU", void 0);
  17930. __decorate([
  17931. BABYLON.serialize()
  17932. ], BaseTexture.prototype, "wrapV", void 0);
  17933. __decorate([
  17934. BABYLON.serialize()
  17935. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  17936. __decorate([
  17937. BABYLON.serialize()
  17938. ], BaseTexture.prototype, "isCube", void 0);
  17939. __decorate([
  17940. BABYLON.serialize()
  17941. ], BaseTexture.prototype, "isRenderTarget", void 0);
  17942. BABYLON.BaseTexture = BaseTexture;
  17943. })(BABYLON || (BABYLON = {}));
  17944. //# sourceMappingURL=babylon.baseTexture.js.map
  17945. var BABYLON;
  17946. (function (BABYLON) {
  17947. var Texture = (function (_super) {
  17948. __extends(Texture, _super);
  17949. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  17950. if (noMipmap === void 0) { noMipmap = false; }
  17951. if (invertY === void 0) { invertY = true; }
  17952. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17953. if (onLoad === void 0) { onLoad = null; }
  17954. if (onError === void 0) { onError = null; }
  17955. if (buffer === void 0) { buffer = null; }
  17956. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17957. var _this = _super.call(this, scene) || this;
  17958. _this.uOffset = 0;
  17959. _this.vOffset = 0;
  17960. _this.uScale = 1.0;
  17961. _this.vScale = 1.0;
  17962. _this.uAng = 0;
  17963. _this.vAng = 0;
  17964. _this.wAng = 0;
  17965. _this.name = url;
  17966. _this.url = url;
  17967. _this._noMipmap = noMipmap;
  17968. _this._invertY = invertY;
  17969. _this._samplingMode = samplingMode;
  17970. _this._buffer = buffer;
  17971. _this._deleteBuffer = deleteBuffer;
  17972. _this._format = format;
  17973. if (!url) {
  17974. return _this;
  17975. }
  17976. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  17977. var load = function () {
  17978. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  17979. _this.onLoadObservable.notifyObservers(true);
  17980. }
  17981. if (onLoad) {
  17982. onLoad();
  17983. }
  17984. };
  17985. if (!_this._texture) {
  17986. if (!scene.useDelayedTextureLoading) {
  17987. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  17988. if (deleteBuffer) {
  17989. delete _this._buffer;
  17990. }
  17991. }
  17992. else {
  17993. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17994. _this._delayedOnLoad = load;
  17995. _this._delayedOnError = onError;
  17996. }
  17997. }
  17998. else {
  17999. if (_this._texture.isReady) {
  18000. BABYLON.Tools.SetImmediate(function () { return load(); });
  18001. }
  18002. else {
  18003. _this._texture.onLoadedCallbacks.push(load);
  18004. }
  18005. }
  18006. return _this;
  18007. }
  18008. Object.defineProperty(Texture.prototype, "noMipmap", {
  18009. get: function () {
  18010. return this._noMipmap;
  18011. },
  18012. enumerable: true,
  18013. configurable: true
  18014. });
  18015. Texture.prototype.delayLoad = function () {
  18016. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18017. return;
  18018. }
  18019. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18020. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  18021. if (!this._texture) {
  18022. 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);
  18023. if (this._deleteBuffer) {
  18024. delete this._buffer;
  18025. }
  18026. }
  18027. };
  18028. Texture.prototype.updateSamplingMode = function (samplingMode) {
  18029. if (!this._texture) {
  18030. return;
  18031. }
  18032. this._samplingMode = samplingMode;
  18033. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  18034. };
  18035. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  18036. x *= this.uScale;
  18037. y *= this.vScale;
  18038. x -= 0.5 * this.uScale;
  18039. y -= 0.5 * this.vScale;
  18040. z -= 0.5;
  18041. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  18042. t.x += 0.5 * this.uScale + this.uOffset;
  18043. t.y += 0.5 * this.vScale + this.vOffset;
  18044. t.z += 0.5;
  18045. };
  18046. Texture.prototype.getTextureMatrix = function () {
  18047. if (this.uOffset === this._cachedUOffset &&
  18048. this.vOffset === this._cachedVOffset &&
  18049. this.uScale === this._cachedUScale &&
  18050. this.vScale === this._cachedVScale &&
  18051. this.uAng === this._cachedUAng &&
  18052. this.vAng === this._cachedVAng &&
  18053. this.wAng === this._cachedWAng) {
  18054. return this._cachedTextureMatrix;
  18055. }
  18056. this._cachedUOffset = this.uOffset;
  18057. this._cachedVOffset = this.vOffset;
  18058. this._cachedUScale = this.uScale;
  18059. this._cachedVScale = this.vScale;
  18060. this._cachedUAng = this.uAng;
  18061. this._cachedVAng = this.vAng;
  18062. this._cachedWAng = this.wAng;
  18063. if (!this._cachedTextureMatrix) {
  18064. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18065. this._rowGenerationMatrix = new BABYLON.Matrix();
  18066. this._t0 = BABYLON.Vector3.Zero();
  18067. this._t1 = BABYLON.Vector3.Zero();
  18068. this._t2 = BABYLON.Vector3.Zero();
  18069. }
  18070. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  18071. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  18072. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  18073. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  18074. this._t1.subtractInPlace(this._t0);
  18075. this._t2.subtractInPlace(this._t0);
  18076. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18077. this._cachedTextureMatrix.m[0] = this._t1.x;
  18078. this._cachedTextureMatrix.m[1] = this._t1.y;
  18079. this._cachedTextureMatrix.m[2] = this._t1.z;
  18080. this._cachedTextureMatrix.m[4] = this._t2.x;
  18081. this._cachedTextureMatrix.m[5] = this._t2.y;
  18082. this._cachedTextureMatrix.m[6] = this._t2.z;
  18083. this._cachedTextureMatrix.m[8] = this._t0.x;
  18084. this._cachedTextureMatrix.m[9] = this._t0.y;
  18085. this._cachedTextureMatrix.m[10] = this._t0.z;
  18086. return this._cachedTextureMatrix;
  18087. };
  18088. Texture.prototype.getReflectionTextureMatrix = function () {
  18089. if (this.uOffset === this._cachedUOffset &&
  18090. this.vOffset === this._cachedVOffset &&
  18091. this.uScale === this._cachedUScale &&
  18092. this.vScale === this._cachedVScale &&
  18093. this.coordinatesMode === this._cachedCoordinatesMode) {
  18094. return this._cachedTextureMatrix;
  18095. }
  18096. if (!this._cachedTextureMatrix) {
  18097. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18098. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  18099. }
  18100. this._cachedCoordinatesMode = this.coordinatesMode;
  18101. switch (this.coordinatesMode) {
  18102. case Texture.PLANAR_MODE:
  18103. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18104. this._cachedTextureMatrix[0] = this.uScale;
  18105. this._cachedTextureMatrix[5] = this.vScale;
  18106. this._cachedTextureMatrix[12] = this.uOffset;
  18107. this._cachedTextureMatrix[13] = this.vOffset;
  18108. break;
  18109. case Texture.PROJECTION_MODE:
  18110. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  18111. this._projectionModeMatrix.m[0] = 0.5;
  18112. this._projectionModeMatrix.m[5] = -0.5;
  18113. this._projectionModeMatrix.m[10] = 0.0;
  18114. this._projectionModeMatrix.m[12] = 0.5;
  18115. this._projectionModeMatrix.m[13] = 0.5;
  18116. this._projectionModeMatrix.m[14] = 1.0;
  18117. this._projectionModeMatrix.m[15] = 1.0;
  18118. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  18119. break;
  18120. default:
  18121. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18122. break;
  18123. }
  18124. return this._cachedTextureMatrix;
  18125. };
  18126. Texture.prototype.clone = function () {
  18127. var _this = this;
  18128. return BABYLON.SerializationHelper.Clone(function () {
  18129. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  18130. }, this);
  18131. };
  18132. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  18133. get: function () {
  18134. if (!this._onLoadObservarble) {
  18135. this._onLoadObservarble = new BABYLON.Observable();
  18136. }
  18137. return this._onLoadObservarble;
  18138. },
  18139. enumerable: true,
  18140. configurable: true
  18141. });
  18142. // Statics
  18143. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18144. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18145. if (onLoad === void 0) { onLoad = null; }
  18146. if (onError === void 0) { onError = null; }
  18147. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18148. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  18149. };
  18150. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  18151. if (parsedTexture.customType) {
  18152. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  18153. // Update Sampling Mode
  18154. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  18155. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  18156. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  18157. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  18158. }
  18159. }
  18160. return parsedCustomTexture;
  18161. }
  18162. if (parsedTexture.isCube) {
  18163. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  18164. }
  18165. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18166. return null;
  18167. }
  18168. var texture = BABYLON.SerializationHelper.Parse(function () {
  18169. if (parsedTexture.mirrorPlane) {
  18170. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18171. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  18172. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18173. return mirrorTexture;
  18174. }
  18175. else if (parsedTexture.isRenderTarget) {
  18176. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18177. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  18178. return renderTargetTexture;
  18179. }
  18180. else {
  18181. var texture;
  18182. if (parsedTexture.base64String) {
  18183. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  18184. }
  18185. else {
  18186. texture = new Texture(rootUrl + parsedTexture.name, scene);
  18187. }
  18188. return texture;
  18189. }
  18190. }, parsedTexture, scene);
  18191. // Update Sampling Mode
  18192. if (parsedTexture.samplingMode) {
  18193. var sampling = parsedTexture.samplingMode;
  18194. if (texture._samplingMode !== sampling) {
  18195. texture.updateSamplingMode(sampling);
  18196. }
  18197. }
  18198. // Animations
  18199. if (parsedTexture.animations) {
  18200. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18201. var parsedAnimation = parsedTexture.animations[animationIndex];
  18202. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18203. }
  18204. }
  18205. return texture;
  18206. };
  18207. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18208. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18209. if (noMipmap === void 0) { noMipmap = false; }
  18210. if (invertY === void 0) { invertY = true; }
  18211. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18212. if (onLoad === void 0) { onLoad = null; }
  18213. if (onError === void 0) { onError = null; }
  18214. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18215. if (name.substr(0, 5) !== "data:") {
  18216. name = "data:" + name;
  18217. }
  18218. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  18219. };
  18220. return Texture;
  18221. }(BABYLON.BaseTexture));
  18222. // Constants
  18223. Texture.NEAREST_SAMPLINGMODE = 1;
  18224. Texture.BILINEAR_SAMPLINGMODE = 2;
  18225. Texture.TRILINEAR_SAMPLINGMODE = 3;
  18226. Texture.EXPLICIT_MODE = 0;
  18227. Texture.SPHERICAL_MODE = 1;
  18228. Texture.PLANAR_MODE = 2;
  18229. Texture.CUBIC_MODE = 3;
  18230. Texture.PROJECTION_MODE = 4;
  18231. Texture.SKYBOX_MODE = 5;
  18232. Texture.INVCUBIC_MODE = 6;
  18233. Texture.EQUIRECTANGULAR_MODE = 7;
  18234. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  18235. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18236. Texture.CLAMP_ADDRESSMODE = 0;
  18237. Texture.WRAP_ADDRESSMODE = 1;
  18238. Texture.MIRROR_ADDRESSMODE = 2;
  18239. __decorate([
  18240. BABYLON.serialize()
  18241. ], Texture.prototype, "url", void 0);
  18242. __decorate([
  18243. BABYLON.serialize()
  18244. ], Texture.prototype, "uOffset", void 0);
  18245. __decorate([
  18246. BABYLON.serialize()
  18247. ], Texture.prototype, "vOffset", void 0);
  18248. __decorate([
  18249. BABYLON.serialize()
  18250. ], Texture.prototype, "uScale", void 0);
  18251. __decorate([
  18252. BABYLON.serialize()
  18253. ], Texture.prototype, "vScale", void 0);
  18254. __decorate([
  18255. BABYLON.serialize()
  18256. ], Texture.prototype, "uAng", void 0);
  18257. __decorate([
  18258. BABYLON.serialize()
  18259. ], Texture.prototype, "vAng", void 0);
  18260. __decorate([
  18261. BABYLON.serialize()
  18262. ], Texture.prototype, "wAng", void 0);
  18263. BABYLON.Texture = Texture;
  18264. })(BABYLON || (BABYLON = {}));
  18265. //# sourceMappingURL=babylon.texture.js.map
  18266. var BABYLON;
  18267. (function (BABYLON) {
  18268. var _InstancesBatch = (function () {
  18269. function _InstancesBatch() {
  18270. this.mustReturn = false;
  18271. this.visibleInstances = new Array();
  18272. this.renderSelf = new Array();
  18273. }
  18274. return _InstancesBatch;
  18275. }());
  18276. BABYLON._InstancesBatch = _InstancesBatch;
  18277. var Mesh = (function (_super) {
  18278. __extends(Mesh, _super);
  18279. /**
  18280. * @constructor
  18281. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18282. * @param {Scene} scene The scene to add this mesh to.
  18283. * @param {Node} parent The parent of this mesh, if it has one
  18284. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18285. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18286. * When false, achieved by calling a clone(), also passing False.
  18287. * This will make creation of children, recursive.
  18288. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  18289. */
  18290. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18291. if (parent === void 0) { parent = null; }
  18292. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18293. var _this = _super.call(this, name, scene) || this;
  18294. // Events
  18295. /**
  18296. * An event triggered before rendering the mesh
  18297. * @type {BABYLON.Observable}
  18298. */
  18299. _this.onBeforeRenderObservable = new BABYLON.Observable();
  18300. /**
  18301. * An event triggered after rendering the mesh
  18302. * @type {BABYLON.Observable}
  18303. */
  18304. _this.onAfterRenderObservable = new BABYLON.Observable();
  18305. /**
  18306. * An event triggered before drawing the mesh
  18307. * @type {BABYLON.Observable}
  18308. */
  18309. _this.onBeforeDrawObservable = new BABYLON.Observable();
  18310. // Members
  18311. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18312. _this.instances = new Array();
  18313. _this._LODLevels = new Array();
  18314. _this._visibleInstances = {};
  18315. _this._renderIdForInstances = new Array();
  18316. _this._batchCache = new _InstancesBatch();
  18317. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18318. _this._sideOrientation = Mesh._DEFAULTSIDE;
  18319. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18320. // Will be used to save a source mesh reference, If any
  18321. _this._source = null;
  18322. if (source) {
  18323. // Source mesh
  18324. _this._source = source;
  18325. // Geometry
  18326. if (source._geometry) {
  18327. source._geometry.applyToMesh(_this);
  18328. }
  18329. // Deep copy
  18330. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  18331. // Parent
  18332. _this.parent = source.parent;
  18333. // Pivot
  18334. _this.setPivotMatrix(source.getPivotMatrix());
  18335. _this.id = name + "." + source.id;
  18336. // Material
  18337. _this.material = source.material;
  18338. var index;
  18339. if (!doNotCloneChildren) {
  18340. // Children
  18341. for (index = 0; index < scene.meshes.length; index++) {
  18342. var mesh = scene.meshes[index];
  18343. if (mesh.parent === source) {
  18344. // doNotCloneChildren is always going to be False
  18345. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  18346. }
  18347. }
  18348. }
  18349. // Physics clone
  18350. var physicsEngine = _this.getScene().getPhysicsEngine();
  18351. if (clonePhysicsImpostor && physicsEngine) {
  18352. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18353. if (impostor) {
  18354. _this.physicsImpostor = impostor.clone(_this);
  18355. }
  18356. }
  18357. // Particles
  18358. for (index = 0; index < scene.particleSystems.length; index++) {
  18359. var system = scene.particleSystems[index];
  18360. if (system.emitter === source) {
  18361. system.clone(system.name, _this);
  18362. }
  18363. }
  18364. _this.computeWorldMatrix(true);
  18365. }
  18366. // Parent
  18367. if (parent !== null) {
  18368. _this.parent = parent;
  18369. }
  18370. return _this;
  18371. }
  18372. Object.defineProperty(Mesh, "FRONTSIDE", {
  18373. /**
  18374. * Mesh side orientation : usually the external or front surface
  18375. */
  18376. get: function () {
  18377. return Mesh._FRONTSIDE;
  18378. },
  18379. enumerable: true,
  18380. configurable: true
  18381. });
  18382. Object.defineProperty(Mesh, "BACKSIDE", {
  18383. /**
  18384. * Mesh side orientation : usually the internal or back surface
  18385. */
  18386. get: function () {
  18387. return Mesh._BACKSIDE;
  18388. },
  18389. enumerable: true,
  18390. configurable: true
  18391. });
  18392. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18393. /**
  18394. * Mesh side orientation : both internal and external or front and back surfaces
  18395. */
  18396. get: function () {
  18397. return Mesh._DOUBLESIDE;
  18398. },
  18399. enumerable: true,
  18400. configurable: true
  18401. });
  18402. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18403. /**
  18404. * Mesh side orientation : by default, `FRONTSIDE`
  18405. */
  18406. get: function () {
  18407. return Mesh._DEFAULTSIDE;
  18408. },
  18409. enumerable: true,
  18410. configurable: true
  18411. });
  18412. Object.defineProperty(Mesh, "NO_CAP", {
  18413. /**
  18414. * Mesh cap setting : no cap
  18415. */
  18416. get: function () {
  18417. return Mesh._NO_CAP;
  18418. },
  18419. enumerable: true,
  18420. configurable: true
  18421. });
  18422. Object.defineProperty(Mesh, "CAP_START", {
  18423. /**
  18424. * Mesh cap setting : one cap at the beginning of the mesh
  18425. */
  18426. get: function () {
  18427. return Mesh._CAP_START;
  18428. },
  18429. enumerable: true,
  18430. configurable: true
  18431. });
  18432. Object.defineProperty(Mesh, "CAP_END", {
  18433. /**
  18434. * Mesh cap setting : one cap at the end of the mesh
  18435. */
  18436. get: function () {
  18437. return Mesh._CAP_END;
  18438. },
  18439. enumerable: true,
  18440. configurable: true
  18441. });
  18442. Object.defineProperty(Mesh, "CAP_ALL", {
  18443. /**
  18444. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18445. */
  18446. get: function () {
  18447. return Mesh._CAP_ALL;
  18448. },
  18449. enumerable: true,
  18450. configurable: true
  18451. });
  18452. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18453. set: function (callback) {
  18454. if (this._onBeforeDrawObserver) {
  18455. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18456. }
  18457. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18458. },
  18459. enumerable: true,
  18460. configurable: true
  18461. });
  18462. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  18463. get: function () {
  18464. return this._morphTargetManager;
  18465. },
  18466. set: function (value) {
  18467. if (this._morphTargetManager === value) {
  18468. return;
  18469. }
  18470. this._morphTargetManager = value;
  18471. this._syncGeometryWithMorphTargetManager();
  18472. },
  18473. enumerable: true,
  18474. configurable: true
  18475. });
  18476. Object.defineProperty(Mesh.prototype, "source", {
  18477. get: function () {
  18478. return this._source;
  18479. },
  18480. enumerable: true,
  18481. configurable: true
  18482. });
  18483. // Methods
  18484. /**
  18485. * Returns the string "Mesh".
  18486. */
  18487. Mesh.prototype.getClassName = function () {
  18488. return "Mesh";
  18489. };
  18490. /**
  18491. * Returns a string.
  18492. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18493. */
  18494. Mesh.prototype.toString = function (fullDetails) {
  18495. var ret = _super.prototype.toString.call(this, fullDetails);
  18496. ret += ", n vertices: " + this.getTotalVertices();
  18497. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18498. if (this.animations) {
  18499. for (var i = 0; i < this.animations.length; i++) {
  18500. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18501. }
  18502. }
  18503. if (fullDetails) {
  18504. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18505. }
  18506. return ret;
  18507. };
  18508. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18509. /**
  18510. * True if the mesh has some Levels Of Details (LOD).
  18511. * Returns a boolean.
  18512. */
  18513. get: function () {
  18514. return this._LODLevels.length > 0;
  18515. },
  18516. enumerable: true,
  18517. configurable: true
  18518. });
  18519. Mesh.prototype._sortLODLevels = function () {
  18520. this._LODLevels.sort(function (a, b) {
  18521. if (a.distance < b.distance) {
  18522. return 1;
  18523. }
  18524. if (a.distance > b.distance) {
  18525. return -1;
  18526. }
  18527. return 0;
  18528. });
  18529. };
  18530. /**
  18531. * Add a mesh as LOD level triggered at the given distance.
  18532. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18533. * @param {number} distance The distance from the center of the object to show this level
  18534. * @param {Mesh} mesh The mesh to be added as LOD level
  18535. * @return {Mesh} This mesh (for chaining)
  18536. */
  18537. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18538. if (mesh && mesh._masterMesh) {
  18539. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18540. return this;
  18541. }
  18542. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18543. this._LODLevels.push(level);
  18544. if (mesh) {
  18545. mesh._masterMesh = this;
  18546. }
  18547. this._sortLODLevels();
  18548. return this;
  18549. };
  18550. /**
  18551. * Returns the LOD level mesh at the passed distance or null if not found.
  18552. * It is related to the method `addLODLevel(distance, mesh)`.
  18553. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18554. * Returns an object Mesh or `null`.
  18555. */
  18556. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18557. for (var index = 0; index < this._LODLevels.length; index++) {
  18558. var level = this._LODLevels[index];
  18559. if (level.distance === distance) {
  18560. return level.mesh;
  18561. }
  18562. }
  18563. return null;
  18564. };
  18565. /**
  18566. * Remove a mesh from the LOD array
  18567. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18568. * @param {Mesh} mesh The mesh to be removed.
  18569. * @return {Mesh} This mesh (for chaining)
  18570. */
  18571. Mesh.prototype.removeLODLevel = function (mesh) {
  18572. for (var index = 0; index < this._LODLevels.length; index++) {
  18573. if (this._LODLevels[index].mesh === mesh) {
  18574. this._LODLevels.splice(index, 1);
  18575. if (mesh) {
  18576. mesh._masterMesh = null;
  18577. }
  18578. }
  18579. }
  18580. this._sortLODLevels();
  18581. return this;
  18582. };
  18583. /**
  18584. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18585. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18586. */
  18587. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18588. if (!this._LODLevels || this._LODLevels.length === 0) {
  18589. return this;
  18590. }
  18591. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18592. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18593. if (this.onLODLevelSelection) {
  18594. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18595. }
  18596. return this;
  18597. }
  18598. for (var index = 0; index < this._LODLevels.length; index++) {
  18599. var level = this._LODLevels[index];
  18600. if (level.distance < distanceToCamera) {
  18601. if (level.mesh) {
  18602. level.mesh._preActivate();
  18603. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18604. }
  18605. if (this.onLODLevelSelection) {
  18606. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18607. }
  18608. return level.mesh;
  18609. }
  18610. }
  18611. if (this.onLODLevelSelection) {
  18612. this.onLODLevelSelection(distanceToCamera, this, this);
  18613. }
  18614. return this;
  18615. };
  18616. Object.defineProperty(Mesh.prototype, "geometry", {
  18617. /**
  18618. * Returns the mesh internal Geometry object.
  18619. */
  18620. get: function () {
  18621. return this._geometry;
  18622. },
  18623. enumerable: true,
  18624. configurable: true
  18625. });
  18626. /**
  18627. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18628. */
  18629. Mesh.prototype.getTotalVertices = function () {
  18630. if (!this._geometry) {
  18631. return 0;
  18632. }
  18633. return this._geometry.getTotalVertices();
  18634. };
  18635. /**
  18636. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18637. * 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.
  18638. * Returns null if the mesh has no geometry or no vertex buffer.
  18639. * Possible `kind` values :
  18640. * - BABYLON.VertexBuffer.PositionKind
  18641. * - BABYLON.VertexBuffer.UVKind
  18642. * - BABYLON.VertexBuffer.UV2Kind
  18643. * - BABYLON.VertexBuffer.UV3Kind
  18644. * - BABYLON.VertexBuffer.UV4Kind
  18645. * - BABYLON.VertexBuffer.UV5Kind
  18646. * - BABYLON.VertexBuffer.UV6Kind
  18647. * - BABYLON.VertexBuffer.ColorKind
  18648. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18649. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18650. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18651. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18652. */
  18653. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18654. if (!this._geometry) {
  18655. return null;
  18656. }
  18657. return this._geometry.getVerticesData(kind, copyWhenShared);
  18658. };
  18659. /**
  18660. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18661. * Returns `undefined` if the mesh has no geometry.
  18662. * Possible `kind` values :
  18663. * - BABYLON.VertexBuffer.PositionKind
  18664. * - BABYLON.VertexBuffer.UVKind
  18665. * - BABYLON.VertexBuffer.UV2Kind
  18666. * - BABYLON.VertexBuffer.UV3Kind
  18667. * - BABYLON.VertexBuffer.UV4Kind
  18668. * - BABYLON.VertexBuffer.UV5Kind
  18669. * - BABYLON.VertexBuffer.UV6Kind
  18670. * - BABYLON.VertexBuffer.ColorKind
  18671. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18672. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18673. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18674. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18675. */
  18676. Mesh.prototype.getVertexBuffer = function (kind) {
  18677. if (!this._geometry) {
  18678. return undefined;
  18679. }
  18680. return this._geometry.getVertexBuffer(kind);
  18681. };
  18682. /**
  18683. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18684. * Possible `kind` values :
  18685. * - BABYLON.VertexBuffer.PositionKind
  18686. * - BABYLON.VertexBuffer.UVKind
  18687. * - BABYLON.VertexBuffer.UV2Kind
  18688. * - BABYLON.VertexBuffer.UV3Kind
  18689. * - BABYLON.VertexBuffer.UV4Kind
  18690. * - BABYLON.VertexBuffer.UV5Kind
  18691. * - BABYLON.VertexBuffer.UV6Kind
  18692. * - BABYLON.VertexBuffer.ColorKind
  18693. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18694. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18695. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18696. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18697. */
  18698. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18699. if (!this._geometry) {
  18700. if (this._delayInfo) {
  18701. return this._delayInfo.indexOf(kind) !== -1;
  18702. }
  18703. return false;
  18704. }
  18705. return this._geometry.isVerticesDataPresent(kind);
  18706. };
  18707. /**
  18708. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18709. * Possible `kind` values :
  18710. * - BABYLON.VertexBuffer.PositionKind
  18711. * - BABYLON.VertexBuffer.UVKind
  18712. * - BABYLON.VertexBuffer.UV2Kind
  18713. * - BABYLON.VertexBuffer.UV3Kind
  18714. * - BABYLON.VertexBuffer.UV4Kind
  18715. * - BABYLON.VertexBuffer.UV5Kind
  18716. * - BABYLON.VertexBuffer.UV6Kind
  18717. * - BABYLON.VertexBuffer.ColorKind
  18718. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18719. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18720. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18721. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18722. */
  18723. Mesh.prototype.getVerticesDataKinds = function () {
  18724. if (!this._geometry) {
  18725. var result = [];
  18726. if (this._delayInfo) {
  18727. this._delayInfo.forEach(function (kind, index, array) {
  18728. result.push(kind);
  18729. });
  18730. }
  18731. return result;
  18732. }
  18733. return this._geometry.getVerticesDataKinds();
  18734. };
  18735. /**
  18736. * Returns a positive integer : the total number of indices in this mesh geometry.
  18737. * Returns zero if the mesh has no geometry.
  18738. */
  18739. Mesh.prototype.getTotalIndices = function () {
  18740. if (!this._geometry) {
  18741. return 0;
  18742. }
  18743. return this._geometry.getTotalIndices();
  18744. };
  18745. /**
  18746. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  18747. * 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.
  18748. * Returns an empty array if the mesh has no geometry.
  18749. */
  18750. Mesh.prototype.getIndices = function (copyWhenShared) {
  18751. if (!this._geometry) {
  18752. return [];
  18753. }
  18754. return this._geometry.getIndices(copyWhenShared);
  18755. };
  18756. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18757. get: function () {
  18758. return this._masterMesh !== null && this._masterMesh !== undefined;
  18759. },
  18760. enumerable: true,
  18761. configurable: true
  18762. });
  18763. /**
  18764. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18765. */
  18766. Mesh.prototype.isReady = function () {
  18767. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18768. return false;
  18769. }
  18770. return _super.prototype.isReady.call(this);
  18771. };
  18772. /**
  18773. * Boolean : true if the mesh has been disposed.
  18774. */
  18775. Mesh.prototype.isDisposed = function () {
  18776. return this._isDisposed;
  18777. };
  18778. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18779. get: function () {
  18780. return this._sideOrientation;
  18781. },
  18782. /**
  18783. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18784. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18785. */
  18786. set: function (sideO) {
  18787. this._sideOrientation = sideO;
  18788. },
  18789. enumerable: true,
  18790. configurable: true
  18791. });
  18792. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18793. /**
  18794. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18795. * This property is pertinent only for updatable parametric shapes.
  18796. */
  18797. get: function () {
  18798. return this._areNormalsFrozen;
  18799. },
  18800. enumerable: true,
  18801. configurable: true
  18802. });
  18803. /**
  18804. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18805. * It has no effect at all on other shapes.
  18806. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18807. * Returns the Mesh.
  18808. */
  18809. Mesh.prototype.freezeNormals = function () {
  18810. this._areNormalsFrozen = true;
  18811. return this;
  18812. };
  18813. /**
  18814. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18815. * It has no effect at all on other shapes.
  18816. * It reactivates the mesh normals computation if it was previously frozen.
  18817. * Returns the Mesh.
  18818. */
  18819. Mesh.prototype.unfreezeNormals = function () {
  18820. this._areNormalsFrozen = false;
  18821. return this;
  18822. };
  18823. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18824. /**
  18825. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18826. */
  18827. set: function (count) {
  18828. this._overridenInstanceCount = count;
  18829. },
  18830. enumerable: true,
  18831. configurable: true
  18832. });
  18833. // Methods
  18834. Mesh.prototype._preActivate = function () {
  18835. var sceneRenderId = this.getScene().getRenderId();
  18836. if (this._preActivateId === sceneRenderId) {
  18837. return this;
  18838. }
  18839. this._preActivateId = sceneRenderId;
  18840. this._visibleInstances = null;
  18841. return this;
  18842. };
  18843. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18844. if (this._visibleInstances) {
  18845. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18846. }
  18847. return this;
  18848. };
  18849. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18850. if (!this._visibleInstances) {
  18851. this._visibleInstances = {};
  18852. this._visibleInstances.defaultRenderId = renderId;
  18853. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18854. }
  18855. if (!this._visibleInstances[renderId]) {
  18856. this._visibleInstances[renderId] = new Array();
  18857. }
  18858. this._visibleInstances[renderId].push(instance);
  18859. return this;
  18860. };
  18861. /**
  18862. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  18863. * This means the mesh underlying bounding box and sphere are recomputed.
  18864. * Returns the Mesh.
  18865. */
  18866. Mesh.prototype.refreshBoundingInfo = function () {
  18867. if (this._boundingInfo.isLocked) {
  18868. return;
  18869. }
  18870. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18871. if (data) {
  18872. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  18873. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18874. }
  18875. if (this.subMeshes) {
  18876. for (var index = 0; index < this.subMeshes.length; index++) {
  18877. this.subMeshes[index].refreshBoundingInfo();
  18878. }
  18879. }
  18880. this._updateBoundingInfo();
  18881. return this;
  18882. };
  18883. Mesh.prototype._createGlobalSubMesh = function () {
  18884. var totalVertices = this.getTotalVertices();
  18885. if (!totalVertices || !this.getIndices()) {
  18886. return null;
  18887. }
  18888. this.releaseSubMeshes();
  18889. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  18890. };
  18891. Mesh.prototype.subdivide = function (count) {
  18892. if (count < 1) {
  18893. return;
  18894. }
  18895. var totalIndices = this.getTotalIndices();
  18896. var subdivisionSize = (totalIndices / count) | 0;
  18897. var offset = 0;
  18898. // Ensure that subdivisionSize is a multiple of 3
  18899. while (subdivisionSize % 3 !== 0) {
  18900. subdivisionSize++;
  18901. }
  18902. this.releaseSubMeshes();
  18903. for (var index = 0; index < count; index++) {
  18904. if (offset >= totalIndices) {
  18905. break;
  18906. }
  18907. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  18908. offset += subdivisionSize;
  18909. }
  18910. this.synchronizeInstances();
  18911. };
  18912. /**
  18913. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18914. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18915. * The `data` are either a numeric array either a Float32Array.
  18916. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18917. * 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).
  18918. * Note that a new underlying VertexBuffer object is created each call.
  18919. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18920. *
  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. * Returns the Mesh.
  18936. */
  18937. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18938. if (!this._geometry) {
  18939. var vertexData = new BABYLON.VertexData();
  18940. vertexData.set(data, kind);
  18941. var scene = this.getScene();
  18942. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  18943. }
  18944. else {
  18945. this._geometry.setVerticesData(kind, data, updatable, stride);
  18946. }
  18947. return this;
  18948. };
  18949. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  18950. if (updatable === void 0) { updatable = true; }
  18951. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  18952. return;
  18953. }
  18954. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  18955. };
  18956. /**
  18957. * Sets the mesh VertexBuffer.
  18958. * Returns the Mesh.
  18959. */
  18960. Mesh.prototype.setVerticesBuffer = function (buffer) {
  18961. if (!this._geometry) {
  18962. var scene = this.getScene();
  18963. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  18964. }
  18965. this._geometry.setVerticesBuffer(buffer);
  18966. return this;
  18967. };
  18968. /**
  18969. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18970. * If the mesh has no geometry, it is simply returned as it is.
  18971. * The `data` are either a numeric array either a Float32Array.
  18972. * No new underlying VertexBuffer object is created.
  18973. * 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.
  18974. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18975. *
  18976. * Possible `kind` values :
  18977. * - BABYLON.VertexBuffer.PositionKind
  18978. * - BABYLON.VertexBuffer.UVKind
  18979. * - BABYLON.VertexBuffer.UV2Kind
  18980. * - BABYLON.VertexBuffer.UV3Kind
  18981. * - BABYLON.VertexBuffer.UV4Kind
  18982. * - BABYLON.VertexBuffer.UV5Kind
  18983. * - BABYLON.VertexBuffer.UV6Kind
  18984. * - BABYLON.VertexBuffer.ColorKind
  18985. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18986. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18987. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18988. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18989. *
  18990. * Returns the Mesh.
  18991. */
  18992. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18993. if (!this._geometry) {
  18994. return;
  18995. }
  18996. if (!makeItUnique) {
  18997. this._geometry.updateVerticesData(kind, data, updateExtends);
  18998. }
  18999. else {
  19000. this.makeGeometryUnique();
  19001. this.updateVerticesData(kind, data, updateExtends, false);
  19002. }
  19003. return this;
  19004. };
  19005. /**
  19006. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19007. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19008. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19009. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19010. * Returns the Mesh.
  19011. */
  19012. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19013. if (computeNormals === void 0) { computeNormals = true; }
  19014. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19015. positionFunction(positions);
  19016. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19017. if (computeNormals) {
  19018. var indices = this.getIndices();
  19019. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19020. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19021. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19022. }
  19023. return this;
  19024. };
  19025. /**
  19026. * Creates a un-shared specific occurence of the geometry for the mesh.
  19027. * Returns the Mesh.
  19028. */
  19029. Mesh.prototype.makeGeometryUnique = function () {
  19030. if (!this._geometry) {
  19031. return;
  19032. }
  19033. var oldGeometry = this._geometry;
  19034. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19035. oldGeometry.releaseForMesh(this, true);
  19036. geometry.applyToMesh(this);
  19037. return this;
  19038. };
  19039. /**
  19040. * Sets the mesh indices.
  19041. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19042. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19043. * This method creates a new index buffer each call.
  19044. * Returns the Mesh.
  19045. */
  19046. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19047. if (!this._geometry) {
  19048. var vertexData = new BABYLON.VertexData();
  19049. vertexData.indices = indices;
  19050. var scene = this.getScene();
  19051. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19052. }
  19053. else {
  19054. this._geometry.setIndices(indices, totalVertices);
  19055. }
  19056. return this;
  19057. };
  19058. /**
  19059. * Invert the geometry to move from a right handed system to a left handed one.
  19060. * Returns the Mesh.
  19061. */
  19062. Mesh.prototype.toLeftHanded = function () {
  19063. if (!this._geometry) {
  19064. return;
  19065. }
  19066. this._geometry.toLeftHanded();
  19067. return this;
  19068. };
  19069. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19070. var engine = this.getScene().getEngine();
  19071. // Wireframe
  19072. var indexToBind;
  19073. if (this._unIndexed) {
  19074. indexToBind = null;
  19075. }
  19076. else {
  19077. switch (fillMode) {
  19078. case BABYLON.Material.PointFillMode:
  19079. indexToBind = null;
  19080. break;
  19081. case BABYLON.Material.WireFrameFillMode:
  19082. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19083. break;
  19084. default:
  19085. case BABYLON.Material.TriangleFillMode:
  19086. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19087. break;
  19088. }
  19089. }
  19090. // VBOs
  19091. this._geometry._bind(effect, indexToBind);
  19092. return this;
  19093. };
  19094. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19095. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19096. return this;
  19097. }
  19098. this.onBeforeDrawObservable.notifyObservers(this);
  19099. var engine = this.getScene().getEngine();
  19100. // Draw order
  19101. switch (fillMode) {
  19102. case BABYLON.Material.PointFillMode:
  19103. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19104. break;
  19105. case BABYLON.Material.WireFrameFillMode:
  19106. if (this._unIndexed) {
  19107. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19108. }
  19109. else {
  19110. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19111. }
  19112. break;
  19113. default:
  19114. if (this._unIndexed) {
  19115. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19116. }
  19117. else {
  19118. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19119. }
  19120. }
  19121. return this;
  19122. };
  19123. /**
  19124. * Registers for this mesh a javascript function called just before the rendering process.
  19125. * This function is passed the current mesh.
  19126. * Return the Mesh.
  19127. */
  19128. Mesh.prototype.registerBeforeRender = function (func) {
  19129. this.onBeforeRenderObservable.add(func);
  19130. return this;
  19131. };
  19132. /**
  19133. * Disposes a previously registered javascript function called before the rendering.
  19134. * This function is passed the current mesh.
  19135. * Returns the Mesh.
  19136. */
  19137. Mesh.prototype.unregisterBeforeRender = function (func) {
  19138. this.onBeforeRenderObservable.removeCallback(func);
  19139. return this;
  19140. };
  19141. /**
  19142. * Registers for this mesh a javascript function called just after the rendering is complete.
  19143. * This function is passed the current mesh.
  19144. * Returns the Mesh.
  19145. */
  19146. Mesh.prototype.registerAfterRender = function (func) {
  19147. this.onAfterRenderObservable.add(func);
  19148. return this;
  19149. };
  19150. /**
  19151. * Disposes a previously registered javascript function called after the rendering.
  19152. * This function is passed the current mesh.
  19153. * Return the Mesh.
  19154. */
  19155. Mesh.prototype.unregisterAfterRender = function (func) {
  19156. this.onAfterRenderObservable.removeCallback(func);
  19157. return this;
  19158. };
  19159. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19160. var scene = this.getScene();
  19161. this._batchCache.mustReturn = false;
  19162. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19163. this._batchCache.visibleInstances[subMeshId] = null;
  19164. if (this._visibleInstances) {
  19165. var currentRenderId = scene.getRenderId();
  19166. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19167. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19168. var selfRenderId = this._renderId;
  19169. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19170. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19171. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19172. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19173. }
  19174. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19175. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19176. this._batchCache.mustReturn = true;
  19177. return this._batchCache;
  19178. }
  19179. if (currentRenderId !== selfRenderId) {
  19180. this._batchCache.renderSelf[subMeshId] = false;
  19181. }
  19182. }
  19183. this._renderIdForInstances[subMeshId] = currentRenderId;
  19184. }
  19185. return this._batchCache;
  19186. };
  19187. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19188. var visibleInstances = batch.visibleInstances[subMesh._id];
  19189. var matricesCount = visibleInstances.length + 1;
  19190. var bufferSize = matricesCount * 16 * 4;
  19191. var currentInstancesBufferSize = this._instancesBufferSize;
  19192. var instancesBuffer = this._instancesBuffer;
  19193. while (this._instancesBufferSize < bufferSize) {
  19194. this._instancesBufferSize *= 2;
  19195. }
  19196. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19197. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19198. }
  19199. var offset = 0;
  19200. var instancesCount = 0;
  19201. var world = this.getWorldMatrix();
  19202. if (batch.renderSelf[subMesh._id]) {
  19203. world.copyToArray(this._instancesData, offset);
  19204. offset += 16;
  19205. instancesCount++;
  19206. }
  19207. if (visibleInstances) {
  19208. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19209. var instance = visibleInstances[instanceIndex];
  19210. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19211. offset += 16;
  19212. instancesCount++;
  19213. }
  19214. }
  19215. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19216. if (instancesBuffer) {
  19217. instancesBuffer.dispose();
  19218. }
  19219. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19220. this._instancesBuffer = instancesBuffer;
  19221. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19222. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19223. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19224. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19225. }
  19226. else {
  19227. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19228. }
  19229. this.geometry._bind(effect);
  19230. this._draw(subMesh, fillMode, instancesCount);
  19231. engine.unbindInstanceAttributes();
  19232. return this;
  19233. };
  19234. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19235. var scene = this.getScene();
  19236. var engine = scene.getEngine();
  19237. if (hardwareInstancedRendering) {
  19238. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19239. }
  19240. else {
  19241. if (batch.renderSelf[subMesh._id]) {
  19242. // Draw
  19243. if (onBeforeDraw) {
  19244. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19245. }
  19246. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19247. }
  19248. if (batch.visibleInstances[subMesh._id]) {
  19249. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19250. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19251. // World
  19252. var world = instance.getWorldMatrix();
  19253. if (onBeforeDraw) {
  19254. onBeforeDraw(true, world, effectiveMaterial);
  19255. }
  19256. // Draw
  19257. this._draw(subMesh, fillMode);
  19258. }
  19259. }
  19260. }
  19261. return this;
  19262. };
  19263. /**
  19264. * Triggers the draw call for the mesh.
  19265. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19266. * Returns the Mesh.
  19267. */
  19268. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19269. var scene = this.getScene();
  19270. // Managing instances
  19271. var batch = this._getInstancesRenderList(subMesh._id);
  19272. if (batch.mustReturn) {
  19273. return this;
  19274. }
  19275. // Checking geometry state
  19276. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19277. return this;
  19278. }
  19279. var callbackIndex;
  19280. this.onBeforeRenderObservable.notifyObservers(this);
  19281. var engine = scene.getEngine();
  19282. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19283. // Material
  19284. var effectiveMaterial = subMesh.getMaterial();
  19285. if (!effectiveMaterial) {
  19286. return this;
  19287. }
  19288. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19289. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  19290. return this;
  19291. }
  19292. }
  19293. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19294. return this;
  19295. }
  19296. // Outline - step 1
  19297. var savedDepthWrite = engine.getDepthWrite();
  19298. if (this.renderOutline) {
  19299. engine.setDepthWrite(false);
  19300. scene.getOutlineRenderer().render(subMesh, batch);
  19301. engine.setDepthWrite(savedDepthWrite);
  19302. }
  19303. var effect;
  19304. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19305. effect = subMesh.effect;
  19306. }
  19307. else {
  19308. effect = effectiveMaterial.getEffect();
  19309. }
  19310. effectiveMaterial._preBind(effect);
  19311. // Bind
  19312. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19313. this._bind(subMesh, effect, fillMode);
  19314. var world = this.getWorldMatrix();
  19315. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19316. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  19317. }
  19318. else {
  19319. effectiveMaterial.bind(world, this);
  19320. }
  19321. // Alpha mode
  19322. if (enableAlphaMode) {
  19323. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19324. }
  19325. // Draw
  19326. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  19327. // Unbind
  19328. effectiveMaterial.unbind();
  19329. // Outline - step 2
  19330. if (this.renderOutline && savedDepthWrite) {
  19331. engine.setDepthWrite(true);
  19332. engine.setColorWrite(false);
  19333. scene.getOutlineRenderer().render(subMesh, batch);
  19334. engine.setColorWrite(true);
  19335. }
  19336. // Overlay
  19337. if (this.renderOverlay) {
  19338. var currentMode = engine.getAlphaMode();
  19339. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19340. scene.getOutlineRenderer().render(subMesh, batch, true);
  19341. engine.setAlphaMode(currentMode);
  19342. }
  19343. this.onAfterRenderObservable.notifyObservers(this);
  19344. return this;
  19345. };
  19346. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19347. if (isInstance) {
  19348. effectiveMaterial.bindOnlyWorldMatrix(world);
  19349. }
  19350. return this;
  19351. };
  19352. /**
  19353. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19354. */
  19355. Mesh.prototype.getEmittedParticleSystems = function () {
  19356. var results = new Array();
  19357. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19358. var particleSystem = this.getScene().particleSystems[index];
  19359. if (particleSystem.emitter === this) {
  19360. results.push(particleSystem);
  19361. }
  19362. }
  19363. return results;
  19364. };
  19365. /**
  19366. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19367. */
  19368. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19369. var results = new Array();
  19370. var descendants = this.getDescendants();
  19371. descendants.push(this);
  19372. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19373. var particleSystem = this.getScene().particleSystems[index];
  19374. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19375. results.push(particleSystem);
  19376. }
  19377. }
  19378. return results;
  19379. };
  19380. Mesh.prototype._checkDelayState = function () {
  19381. var scene = this.getScene();
  19382. if (this._geometry) {
  19383. this._geometry.load(scene);
  19384. }
  19385. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19386. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19387. this._queueLoad(this, scene);
  19388. }
  19389. return this;
  19390. };
  19391. Mesh.prototype._queueLoad = function (mesh, scene) {
  19392. var _this = this;
  19393. scene._addPendingData(mesh);
  19394. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19395. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19396. if (data instanceof ArrayBuffer) {
  19397. _this._delayLoadingFunction(data, _this);
  19398. }
  19399. else {
  19400. _this._delayLoadingFunction(JSON.parse(data), _this);
  19401. }
  19402. _this.instances.forEach(function (instance) {
  19403. instance._syncSubMeshes();
  19404. });
  19405. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19406. scene._removePendingData(_this);
  19407. }, function () { }, scene.database, getBinaryData);
  19408. return this;
  19409. };
  19410. /**
  19411. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19412. */
  19413. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19414. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19415. return false;
  19416. }
  19417. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19418. return false;
  19419. }
  19420. this._checkDelayState();
  19421. return true;
  19422. };
  19423. /**
  19424. * Sets the mesh material by the material or multiMaterial `id` property.
  19425. * The material `id` is a string identifying the material or the multiMaterial.
  19426. * This method returns the Mesh.
  19427. */
  19428. Mesh.prototype.setMaterialByID = function (id) {
  19429. var materials = this.getScene().materials;
  19430. var index;
  19431. for (index = 0; index < materials.length; index++) {
  19432. if (materials[index].id === id) {
  19433. this.material = materials[index];
  19434. return this;
  19435. }
  19436. }
  19437. // Multi
  19438. var multiMaterials = this.getScene().multiMaterials;
  19439. for (index = 0; index < multiMaterials.length; index++) {
  19440. if (multiMaterials[index].id === id) {
  19441. this.material = multiMaterials[index];
  19442. return this;
  19443. }
  19444. }
  19445. return this;
  19446. };
  19447. /**
  19448. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19449. */
  19450. Mesh.prototype.getAnimatables = function () {
  19451. var results = [];
  19452. if (this.material) {
  19453. results.push(this.material);
  19454. }
  19455. if (this.skeleton) {
  19456. results.push(this.skeleton);
  19457. }
  19458. return results;
  19459. };
  19460. /**
  19461. * Modifies the mesh geometry according to the passed transformation matrix.
  19462. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19463. * The mesh normals are modified accordingly the same transformation.
  19464. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19465. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19466. * Returns the Mesh.
  19467. */
  19468. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19469. // Position
  19470. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19471. return this;
  19472. }
  19473. var submeshes = this.subMeshes.splice(0);
  19474. this._resetPointsArrayCache();
  19475. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19476. var temp = [];
  19477. var index;
  19478. for (index = 0; index < data.length; index += 3) {
  19479. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19480. }
  19481. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19482. // Normals
  19483. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19484. return this;
  19485. }
  19486. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19487. temp = [];
  19488. for (index = 0; index < data.length; index += 3) {
  19489. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19490. }
  19491. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19492. // flip faces?
  19493. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19494. this.flipFaces();
  19495. }
  19496. // Restore submeshes
  19497. this.releaseSubMeshes();
  19498. this.subMeshes = submeshes;
  19499. return this;
  19500. };
  19501. /**
  19502. * Modifies the mesh geometry according to its own current World Matrix.
  19503. * The mesh World Matrix is then reset.
  19504. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19505. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19506. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19507. * Returns the Mesh.
  19508. */
  19509. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19510. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19511. this.scaling.copyFromFloats(1, 1, 1);
  19512. this.position.copyFromFloats(0, 0, 0);
  19513. this.rotation.copyFromFloats(0, 0, 0);
  19514. //only if quaternion is already set
  19515. if (this.rotationQuaternion) {
  19516. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19517. }
  19518. this._worldMatrix = BABYLON.Matrix.Identity();
  19519. return this;
  19520. };
  19521. // Cache
  19522. Mesh.prototype._resetPointsArrayCache = function () {
  19523. this._positions = null;
  19524. return this;
  19525. };
  19526. Mesh.prototype._generatePointsArray = function () {
  19527. if (this._positions)
  19528. return true;
  19529. this._positions = [];
  19530. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19531. if (!data) {
  19532. return false;
  19533. }
  19534. for (var index = 0; index < data.length; index += 3) {
  19535. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19536. }
  19537. return true;
  19538. };
  19539. /**
  19540. * Returns a new Mesh object generated from the current mesh properties.
  19541. * This method must not get confused with createInstance().
  19542. * The parameter `name` is a string, the name given to the new mesh.
  19543. * The optional parameter `newParent` can be any Node object (default `null`).
  19544. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19545. * 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.
  19546. */
  19547. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19548. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19549. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19550. };
  19551. /**
  19552. * Disposes the mesh.
  19553. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19554. */
  19555. Mesh.prototype.dispose = function (doNotRecurse) {
  19556. var _this = this;
  19557. this.morphTargetManager = undefined;
  19558. if (this._geometry) {
  19559. this._geometry.releaseForMesh(this, true);
  19560. }
  19561. // Sources
  19562. var meshes = this.getScene().meshes;
  19563. meshes.forEach(function (mesh) {
  19564. if (mesh._source && mesh._source === _this) {
  19565. mesh._source = null;
  19566. }
  19567. });
  19568. this._source = null;
  19569. // Instances
  19570. if (this._instancesBuffer) {
  19571. this._instancesBuffer.dispose();
  19572. this._instancesBuffer = null;
  19573. }
  19574. while (this.instances.length) {
  19575. this.instances[0].dispose();
  19576. }
  19577. // Highlight layers.
  19578. var highlightLayers = this.getScene().highlightLayers;
  19579. for (var i = 0; i < highlightLayers.length; i++) {
  19580. var highlightLayer = highlightLayers[i];
  19581. if (highlightLayer) {
  19582. highlightLayer.removeMesh(this);
  19583. highlightLayer.removeExcludedMesh(this);
  19584. }
  19585. }
  19586. _super.prototype.dispose.call(this, doNotRecurse);
  19587. };
  19588. /**
  19589. * Modifies the mesh geometry according to a displacement map.
  19590. * 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.
  19591. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19592. * This method returns nothing.
  19593. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19594. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19595. * 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.
  19596. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19597. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19598. *
  19599. * Returns the Mesh.
  19600. */
  19601. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  19602. var _this = this;
  19603. var scene = this.getScene();
  19604. var onload = function (img) {
  19605. // Getting height map data
  19606. var canvas = document.createElement("canvas");
  19607. var context = canvas.getContext("2d");
  19608. var heightMapWidth = img.width;
  19609. var heightMapHeight = img.height;
  19610. canvas.width = heightMapWidth;
  19611. canvas.height = heightMapHeight;
  19612. context.drawImage(img, 0, 0);
  19613. // Create VertexData from map data
  19614. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19615. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19616. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  19617. //execute success callback, if set
  19618. if (onSuccess) {
  19619. onSuccess(_this);
  19620. }
  19621. };
  19622. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19623. return this;
  19624. };
  19625. /**
  19626. * Modifies the mesh geometry according to a displacementMap buffer.
  19627. * 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.
  19628. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19629. * This method returns nothing.
  19630. * 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.
  19631. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19632. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19633. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19634. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19635. *
  19636. * Returns the Mesh.
  19637. */
  19638. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  19639. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19640. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19641. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19642. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19643. return this;
  19644. }
  19645. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19646. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19647. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19648. var position = BABYLON.Vector3.Zero();
  19649. var normal = BABYLON.Vector3.Zero();
  19650. var uv = BABYLON.Vector2.Zero();
  19651. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  19652. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  19653. for (var index = 0; index < positions.length; index += 3) {
  19654. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19655. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19656. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19657. // Compute height
  19658. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  19659. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  19660. var pos = (u + v * heightMapWidth) * 4;
  19661. var r = buffer[pos] / 255.0;
  19662. var g = buffer[pos + 1] / 255.0;
  19663. var b = buffer[pos + 2] / 255.0;
  19664. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19665. normal.normalize();
  19666. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19667. position = position.add(normal);
  19668. position.toArray(positions, index);
  19669. }
  19670. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19671. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19672. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19673. return this;
  19674. };
  19675. /**
  19676. * Modify the mesh to get a flat shading rendering.
  19677. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19678. * This method returns the Mesh.
  19679. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19680. */
  19681. Mesh.prototype.convertToFlatShadedMesh = function () {
  19682. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19683. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19684. var kinds = this.getVerticesDataKinds();
  19685. var vbs = [];
  19686. var data = [];
  19687. var newdata = [];
  19688. var updatableNormals = false;
  19689. var kindIndex;
  19690. var kind;
  19691. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19692. kind = kinds[kindIndex];
  19693. var vertexBuffer = this.getVertexBuffer(kind);
  19694. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19695. updatableNormals = vertexBuffer.isUpdatable();
  19696. kinds.splice(kindIndex, 1);
  19697. kindIndex--;
  19698. continue;
  19699. }
  19700. vbs[kind] = vertexBuffer;
  19701. data[kind] = vbs[kind].getData();
  19702. newdata[kind] = [];
  19703. }
  19704. // Save previous submeshes
  19705. var previousSubmeshes = this.subMeshes.slice(0);
  19706. var indices = this.getIndices();
  19707. var totalIndices = this.getTotalIndices();
  19708. // Generating unique vertices per face
  19709. var index;
  19710. for (index = 0; index < totalIndices; index++) {
  19711. var vertexIndex = indices[index];
  19712. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19713. kind = kinds[kindIndex];
  19714. var stride = vbs[kind].getStrideSize();
  19715. for (var offset = 0; offset < stride; offset++) {
  19716. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19717. }
  19718. }
  19719. }
  19720. // Updating faces & normal
  19721. var normals = [];
  19722. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19723. for (index = 0; index < totalIndices; index += 3) {
  19724. indices[index] = index;
  19725. indices[index + 1] = index + 1;
  19726. indices[index + 2] = index + 2;
  19727. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19728. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19729. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19730. var p1p2 = p1.subtract(p2);
  19731. var p3p2 = p3.subtract(p2);
  19732. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19733. // Store same normals for every vertex
  19734. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19735. normals.push(normal.x);
  19736. normals.push(normal.y);
  19737. normals.push(normal.z);
  19738. }
  19739. }
  19740. this.setIndices(indices);
  19741. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19742. // Updating vertex buffers
  19743. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19744. kind = kinds[kindIndex];
  19745. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19746. }
  19747. // Updating submeshes
  19748. this.releaseSubMeshes();
  19749. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19750. var previousOne = previousSubmeshes[submeshIndex];
  19751. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19752. }
  19753. this.synchronizeInstances();
  19754. return this;
  19755. };
  19756. /**
  19757. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19758. * In other words, more vertices, no more indices and a single bigger VBO.
  19759. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19760. * Returns the Mesh.
  19761. */
  19762. Mesh.prototype.convertToUnIndexedMesh = function () {
  19763. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19764. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19765. var kinds = this.getVerticesDataKinds();
  19766. var vbs = [];
  19767. var data = [];
  19768. var newdata = [];
  19769. var updatableNormals = false;
  19770. var kindIndex;
  19771. var kind;
  19772. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19773. kind = kinds[kindIndex];
  19774. var vertexBuffer = this.getVertexBuffer(kind);
  19775. vbs[kind] = vertexBuffer;
  19776. data[kind] = vbs[kind].getData();
  19777. newdata[kind] = [];
  19778. }
  19779. // Save previous submeshes
  19780. var previousSubmeshes = this.subMeshes.slice(0);
  19781. var indices = this.getIndices();
  19782. var totalIndices = this.getTotalIndices();
  19783. // Generating unique vertices per face
  19784. var index;
  19785. for (index = 0; index < totalIndices; index++) {
  19786. var vertexIndex = indices[index];
  19787. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19788. kind = kinds[kindIndex];
  19789. var stride = vbs[kind].getStrideSize();
  19790. for (var offset = 0; offset < stride; offset++) {
  19791. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19792. }
  19793. }
  19794. }
  19795. // Updating indices
  19796. for (index = 0; index < totalIndices; index += 3) {
  19797. indices[index] = index;
  19798. indices[index + 1] = index + 1;
  19799. indices[index + 2] = index + 2;
  19800. }
  19801. this.setIndices(indices);
  19802. // Updating vertex buffers
  19803. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19804. kind = kinds[kindIndex];
  19805. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19806. }
  19807. // Updating submeshes
  19808. this.releaseSubMeshes();
  19809. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19810. var previousOne = previousSubmeshes[submeshIndex];
  19811. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19812. }
  19813. this._unIndexed = true;
  19814. this.synchronizeInstances();
  19815. return this;
  19816. };
  19817. /**
  19818. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19819. * This method returns the Mesh.
  19820. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19821. */
  19822. Mesh.prototype.flipFaces = function (flipNormals) {
  19823. if (flipNormals === void 0) { flipNormals = false; }
  19824. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19825. var i;
  19826. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19827. for (i = 0; i < vertex_data.normals.length; i++) {
  19828. vertex_data.normals[i] *= -1;
  19829. }
  19830. }
  19831. var temp;
  19832. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19833. // reassign indices
  19834. temp = vertex_data.indices[i + 1];
  19835. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19836. vertex_data.indices[i + 2] = temp;
  19837. }
  19838. vertex_data.applyToMesh(this);
  19839. return this;
  19840. };
  19841. // Instances
  19842. /**
  19843. * Creates a new InstancedMesh object from the mesh model.
  19844. * An instance shares the same properties and the same material than its model.
  19845. * Only these properties of each instance can then be set individually :
  19846. * - position
  19847. * - rotation
  19848. * - rotationQuaternion
  19849. * - setPivotMatrix
  19850. * - scaling
  19851. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19852. * Warning : this method is not supported for Line mesh and LineSystem
  19853. */
  19854. Mesh.prototype.createInstance = function (name) {
  19855. return new BABYLON.InstancedMesh(name, this);
  19856. };
  19857. /**
  19858. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19859. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19860. * This method returns the Mesh.
  19861. */
  19862. Mesh.prototype.synchronizeInstances = function () {
  19863. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19864. var instance = this.instances[instanceIndex];
  19865. instance._syncSubMeshes();
  19866. }
  19867. return this;
  19868. };
  19869. /**
  19870. * Simplify the mesh according to the given array of settings.
  19871. * Function will return immediately and will simplify async. It returns the Mesh.
  19872. * @param settings a collection of simplification settings.
  19873. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19874. * @param type the type of simplification to run.
  19875. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19876. */
  19877. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19878. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19879. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19880. this.getScene().simplificationQueue.addTask({
  19881. settings: settings,
  19882. parallelProcessing: parallelProcessing,
  19883. mesh: this,
  19884. simplificationType: simplificationType,
  19885. successCallback: successCallback
  19886. });
  19887. return this;
  19888. };
  19889. /**
  19890. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19891. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19892. * This should be used together with the simplification to avoid disappearing triangles.
  19893. * Returns the Mesh.
  19894. * @param successCallback an optional success callback to be called after the optimization finished.
  19895. */
  19896. Mesh.prototype.optimizeIndices = function (successCallback) {
  19897. var _this = this;
  19898. var indices = this.getIndices();
  19899. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19900. var vectorPositions = [];
  19901. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19902. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19903. }
  19904. var dupes = [];
  19905. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19906. var realPos = vectorPositions.length - 1 - iteration;
  19907. var testedPosition = vectorPositions[realPos];
  19908. for (var j = 0; j < realPos; ++j) {
  19909. var againstPosition = vectorPositions[j];
  19910. if (testedPosition.equals(againstPosition)) {
  19911. dupes[realPos] = j;
  19912. break;
  19913. }
  19914. }
  19915. }, function () {
  19916. for (var i = 0; i < indices.length; ++i) {
  19917. indices[i] = dupes[indices[i]] || indices[i];
  19918. }
  19919. //indices are now reordered
  19920. var originalSubMeshes = _this.subMeshes.slice(0);
  19921. _this.setIndices(indices);
  19922. _this.subMeshes = originalSubMeshes;
  19923. if (successCallback) {
  19924. successCallback(_this);
  19925. }
  19926. });
  19927. return this;
  19928. };
  19929. Mesh.prototype.serialize = function (serializationObject) {
  19930. serializationObject.name = this.name;
  19931. serializationObject.id = this.id;
  19932. serializationObject.type = this.getClassName();
  19933. if (BABYLON.Tags.HasTags(this)) {
  19934. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19935. }
  19936. serializationObject.position = this.position.asArray();
  19937. if (this.rotationQuaternion) {
  19938. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  19939. }
  19940. else if (this.rotation) {
  19941. serializationObject.rotation = this.rotation.asArray();
  19942. }
  19943. serializationObject.scaling = this.scaling.asArray();
  19944. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19945. serializationObject.isEnabled = this.isEnabled();
  19946. serializationObject.isVisible = this.isVisible;
  19947. serializationObject.infiniteDistance = this.infiniteDistance;
  19948. serializationObject.pickable = this.isPickable;
  19949. serializationObject.receiveShadows = this.receiveShadows;
  19950. serializationObject.billboardMode = this.billboardMode;
  19951. serializationObject.visibility = this.visibility;
  19952. serializationObject.checkCollisions = this.checkCollisions;
  19953. serializationObject.isBlocker = this.isBlocker;
  19954. // Parent
  19955. if (this.parent) {
  19956. serializationObject.parentId = this.parent.id;
  19957. }
  19958. // Geometry
  19959. var geometry = this._geometry;
  19960. if (geometry) {
  19961. var geometryId = geometry.id;
  19962. serializationObject.geometryId = geometryId;
  19963. // SubMeshes
  19964. serializationObject.subMeshes = [];
  19965. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  19966. var subMesh = this.subMeshes[subIndex];
  19967. serializationObject.subMeshes.push({
  19968. materialIndex: subMesh.materialIndex,
  19969. verticesStart: subMesh.verticesStart,
  19970. verticesCount: subMesh.verticesCount,
  19971. indexStart: subMesh.indexStart,
  19972. indexCount: subMesh.indexCount
  19973. });
  19974. }
  19975. }
  19976. // Material
  19977. if (this.material) {
  19978. serializationObject.materialId = this.material.id;
  19979. }
  19980. else {
  19981. this.material = null;
  19982. }
  19983. // Morph targets
  19984. if (this.morphTargetManager) {
  19985. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  19986. }
  19987. // Skeleton
  19988. if (this.skeleton) {
  19989. serializationObject.skeletonId = this.skeleton.id;
  19990. }
  19991. // Physics
  19992. //TODO implement correct serialization for physics impostors.
  19993. if (this.getPhysicsImpostor()) {
  19994. var impostor = this.getPhysicsImpostor();
  19995. serializationObject.physicsMass = impostor.getParam("mass");
  19996. serializationObject.physicsFriction = impostor.getParam("friction");
  19997. serializationObject.physicsRestitution = impostor.getParam("mass");
  19998. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  19999. }
  20000. // Metadata
  20001. if (this.metadata) {
  20002. serializationObject.metadata = this.metadata;
  20003. }
  20004. // Instances
  20005. serializationObject.instances = [];
  20006. for (var index = 0; index < this.instances.length; index++) {
  20007. var instance = this.instances[index];
  20008. var serializationInstance = {
  20009. name: instance.name,
  20010. position: instance.position.asArray(),
  20011. scaling: instance.scaling.asArray()
  20012. };
  20013. if (instance.rotationQuaternion) {
  20014. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  20015. }
  20016. else if (instance.rotation) {
  20017. serializationInstance.rotation = instance.rotation.asArray();
  20018. }
  20019. serializationObject.instances.push(serializationInstance);
  20020. // Animations
  20021. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  20022. serializationInstance.ranges = instance.serializeAnimationRanges();
  20023. }
  20024. //
  20025. // Animations
  20026. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20027. serializationObject.ranges = this.serializeAnimationRanges();
  20028. // Layer mask
  20029. serializationObject.layerMask = this.layerMask;
  20030. // Alpha
  20031. serializationObject.alphaIndex = this.alphaIndex;
  20032. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  20033. // Overlay
  20034. serializationObject.overlayAlpha = this.overlayAlpha;
  20035. serializationObject.overlayColor = this.overlayColor.asArray();
  20036. serializationObject.renderOverlay = this.renderOverlay;
  20037. // Fog
  20038. serializationObject.applyFog = this.applyFog;
  20039. // Action Manager
  20040. if (this.actionManager) {
  20041. serializationObject.actions = this.actionManager.serialize(this.name);
  20042. }
  20043. };
  20044. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  20045. if (!this.geometry) {
  20046. return;
  20047. }
  20048. this._markSubMeshesAsAttributesDirty();
  20049. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  20050. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  20051. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  20052. this.morphTargetManager = undefined;
  20053. return;
  20054. }
  20055. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  20056. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  20057. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  20058. if (morphTarget.hasNormals) {
  20059. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  20060. }
  20061. }
  20062. }
  20063. else {
  20064. var index = 0;
  20065. // Positions
  20066. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  20067. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  20068. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  20069. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  20070. }
  20071. index++;
  20072. }
  20073. }
  20074. };
  20075. // Statics
  20076. /**
  20077. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20078. * The parameter `parsedMesh` is the mesh to be copied.
  20079. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20080. */
  20081. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20082. var mesh;
  20083. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  20084. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  20085. }
  20086. else {
  20087. mesh = new Mesh(parsedMesh.name, scene);
  20088. }
  20089. mesh.id = parsedMesh.id;
  20090. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20091. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20092. if (parsedMesh.metadata !== undefined) {
  20093. mesh.metadata = parsedMesh.metadata;
  20094. }
  20095. if (parsedMesh.rotationQuaternion) {
  20096. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20097. }
  20098. else if (parsedMesh.rotation) {
  20099. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20100. }
  20101. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20102. if (parsedMesh.localMatrix) {
  20103. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20104. }
  20105. else if (parsedMesh.pivotMatrix) {
  20106. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20107. }
  20108. mesh.setEnabled(parsedMesh.isEnabled);
  20109. mesh.isVisible = parsedMesh.isVisible;
  20110. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20111. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20112. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20113. if (parsedMesh.applyFog !== undefined) {
  20114. mesh.applyFog = parsedMesh.applyFog;
  20115. }
  20116. if (parsedMesh.pickable !== undefined) {
  20117. mesh.isPickable = parsedMesh.pickable;
  20118. }
  20119. if (parsedMesh.alphaIndex !== undefined) {
  20120. mesh.alphaIndex = parsedMesh.alphaIndex;
  20121. }
  20122. mesh.receiveShadows = parsedMesh.receiveShadows;
  20123. mesh.billboardMode = parsedMesh.billboardMode;
  20124. if (parsedMesh.visibility !== undefined) {
  20125. mesh.visibility = parsedMesh.visibility;
  20126. }
  20127. mesh.checkCollisions = parsedMesh.checkCollisions;
  20128. if (parsedMesh.isBlocker !== undefined) {
  20129. mesh.isBlocker = parsedMesh.isBlocker;
  20130. }
  20131. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20132. // freezeWorldMatrix
  20133. if (parsedMesh.freezeWorldMatrix) {
  20134. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20135. }
  20136. // Parent
  20137. if (parsedMesh.parentId) {
  20138. mesh._waitingParentId = parsedMesh.parentId;
  20139. }
  20140. // Actions
  20141. if (parsedMesh.actions !== undefined) {
  20142. mesh._waitingActions = parsedMesh.actions;
  20143. }
  20144. // Overlay
  20145. if (parsedMesh.overlayAlpha !== undefined) {
  20146. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  20147. }
  20148. if (parsedMesh.overlayColor !== undefined) {
  20149. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  20150. }
  20151. if (parsedMesh.renderOverlay !== undefined) {
  20152. mesh.renderOverlay = parsedMesh.renderOverlay;
  20153. }
  20154. // Geometry
  20155. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20156. if (parsedMesh.delayLoadingFile) {
  20157. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20158. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20159. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20160. if (parsedMesh._binaryInfo) {
  20161. mesh._binaryInfo = parsedMesh._binaryInfo;
  20162. }
  20163. mesh._delayInfo = [];
  20164. if (parsedMesh.hasUVs) {
  20165. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20166. }
  20167. if (parsedMesh.hasUVs2) {
  20168. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20169. }
  20170. if (parsedMesh.hasUVs3) {
  20171. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20172. }
  20173. if (parsedMesh.hasUVs4) {
  20174. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20175. }
  20176. if (parsedMesh.hasUVs5) {
  20177. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20178. }
  20179. if (parsedMesh.hasUVs6) {
  20180. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20181. }
  20182. if (parsedMesh.hasColors) {
  20183. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20184. }
  20185. if (parsedMesh.hasMatricesIndices) {
  20186. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20187. }
  20188. if (parsedMesh.hasMatricesWeights) {
  20189. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20190. }
  20191. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20192. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20193. mesh._checkDelayState();
  20194. }
  20195. }
  20196. else {
  20197. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20198. }
  20199. // Material
  20200. if (parsedMesh.materialId) {
  20201. mesh.setMaterialByID(parsedMesh.materialId);
  20202. }
  20203. else {
  20204. mesh.material = null;
  20205. }
  20206. // Morph targets
  20207. if (parsedMesh.morphTargetManagerId > -1) {
  20208. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  20209. }
  20210. // Skeleton
  20211. if (parsedMesh.skeletonId > -1) {
  20212. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20213. if (parsedMesh.numBoneInfluencers) {
  20214. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20215. }
  20216. }
  20217. // Animations
  20218. if (parsedMesh.animations) {
  20219. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20220. var parsedAnimation = parsedMesh.animations[animationIndex];
  20221. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20222. }
  20223. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20224. }
  20225. if (parsedMesh.autoAnimate) {
  20226. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20227. }
  20228. // Layer Mask
  20229. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20230. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20231. }
  20232. else {
  20233. mesh.layerMask = 0x0FFFFFFF;
  20234. }
  20235. // Physics
  20236. if (parsedMesh.physicsImpostor) {
  20237. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20238. mass: parsedMesh.physicsMass,
  20239. friction: parsedMesh.physicsFriction,
  20240. restitution: parsedMesh.physicsRestitution
  20241. }, scene);
  20242. }
  20243. // Instances
  20244. if (parsedMesh.instances) {
  20245. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20246. var parsedInstance = parsedMesh.instances[index];
  20247. var instance = mesh.createInstance(parsedInstance.name);
  20248. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20249. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20250. if (parsedInstance.parentId) {
  20251. instance._waitingParentId = parsedInstance.parentId;
  20252. }
  20253. if (parsedInstance.rotationQuaternion) {
  20254. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20255. }
  20256. else if (parsedInstance.rotation) {
  20257. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20258. }
  20259. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20260. instance.checkCollisions = mesh.checkCollisions;
  20261. if (parsedMesh.animations) {
  20262. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20263. parsedAnimation = parsedMesh.animations[animationIndex];
  20264. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20265. }
  20266. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20267. }
  20268. }
  20269. }
  20270. return mesh;
  20271. };
  20272. /**
  20273. * Creates a ribbon mesh.
  20274. * Please consider using the same method from the MeshBuilder class instead.
  20275. * 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.
  20276. *
  20277. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20278. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20279. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20280. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20281. * 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.
  20282. * 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.
  20283. * 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
  20284. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20285. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20286. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20287. */
  20288. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20289. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20290. pathArray: pathArray,
  20291. closeArray: closeArray,
  20292. closePath: closePath,
  20293. offset: offset,
  20294. updatable: updatable,
  20295. sideOrientation: sideOrientation,
  20296. instance: instance
  20297. }, scene);
  20298. };
  20299. /**
  20300. * Creates a plane polygonal mesh. By default, this is a disc.
  20301. * Please consider using the same method from the MeshBuilder class instead.
  20302. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20303. * 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.
  20304. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20305. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20306. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20307. */
  20308. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20309. var options = {
  20310. radius: radius,
  20311. tessellation: tessellation,
  20312. sideOrientation: sideOrientation,
  20313. updatable: updatable
  20314. };
  20315. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20316. };
  20317. /**
  20318. * Creates a box mesh.
  20319. * Please consider using the same method from the MeshBuilder class instead.
  20320. * The parameter `size` sets the size (float) of each box side (default 1).
  20321. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20322. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20323. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20324. */
  20325. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20326. var options = {
  20327. size: size,
  20328. sideOrientation: sideOrientation,
  20329. updatable: updatable
  20330. };
  20331. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20332. };
  20333. /**
  20334. * Creates a sphere mesh.
  20335. * Please consider using the same method from the MeshBuilder class instead.
  20336. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20337. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20338. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20339. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20341. */
  20342. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20343. var options = {
  20344. segments: segments,
  20345. diameterX: diameter,
  20346. diameterY: diameter,
  20347. diameterZ: diameter,
  20348. sideOrientation: sideOrientation,
  20349. updatable: updatable
  20350. };
  20351. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20352. };
  20353. /**
  20354. * Creates a cylinder or a cone mesh.
  20355. * Please consider using the same method from the MeshBuilder class instead.
  20356. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20357. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20358. * 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.
  20359. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20360. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20361. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20362. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20363. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20364. */
  20365. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20366. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20367. if (scene !== undefined) {
  20368. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20369. updatable = scene;
  20370. }
  20371. scene = subdivisions;
  20372. subdivisions = 1;
  20373. }
  20374. var options = {
  20375. height: height,
  20376. diameterTop: diameterTop,
  20377. diameterBottom: diameterBottom,
  20378. tessellation: tessellation,
  20379. subdivisions: subdivisions,
  20380. sideOrientation: sideOrientation,
  20381. updatable: updatable
  20382. };
  20383. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20384. };
  20385. // Torus (Code from SharpDX.org)
  20386. /**
  20387. * Creates a torus mesh.
  20388. * Please consider using the same method from the MeshBuilder class instead.
  20389. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20390. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20391. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20392. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20393. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20394. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20395. */
  20396. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20397. var options = {
  20398. diameter: diameter,
  20399. thickness: thickness,
  20400. tessellation: tessellation,
  20401. sideOrientation: sideOrientation,
  20402. updatable: updatable
  20403. };
  20404. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20405. };
  20406. /**
  20407. * Creates a torus knot mesh.
  20408. * Please consider using the same method from the MeshBuilder class instead.
  20409. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20410. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20411. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20412. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20413. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20414. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20415. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20416. */
  20417. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20418. var options = {
  20419. radius: radius,
  20420. tube: tube,
  20421. radialSegments: radialSegments,
  20422. tubularSegments: tubularSegments,
  20423. p: p,
  20424. q: q,
  20425. sideOrientation: sideOrientation,
  20426. updatable: updatable
  20427. };
  20428. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20429. };
  20430. /**
  20431. * Creates a line mesh.
  20432. * Please consider using the same method from the MeshBuilder class instead.
  20433. * 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.
  20434. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20435. * The parameter `points` is an array successive Vector3.
  20436. * 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
  20437. * When updating an instance, remember that only point positions can change, not the number of points.
  20438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20439. */
  20440. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20441. var options = {
  20442. points: points,
  20443. updatable: updatable,
  20444. instance: instance
  20445. };
  20446. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20447. };
  20448. /**
  20449. * Creates a dashed line mesh.
  20450. * Please consider using the same method from the MeshBuilder class instead.
  20451. * 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.
  20452. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20453. * The parameter `points` is an array successive Vector3.
  20454. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20455. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20456. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20457. * 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
  20458. * When updating an instance, remember that only point positions can change, not the number of points.
  20459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20460. */
  20461. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20462. var options = {
  20463. points: points,
  20464. dashSize: dashSize,
  20465. gapSize: gapSize,
  20466. dashNb: dashNb,
  20467. updatable: updatable,
  20468. instance: instance
  20469. };
  20470. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20471. };
  20472. /**
  20473. * Creates an extruded shape mesh.
  20474. * 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.
  20475. * Please consider using the same method from the MeshBuilder class instead.
  20476. *
  20477. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20478. * 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
  20479. * extruded along the Z axis.
  20480. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20481. * 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.
  20482. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20483. * 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
  20484. * 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
  20485. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20486. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20487. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20489. */
  20490. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20491. var options = {
  20492. shape: shape,
  20493. path: path,
  20494. scale: scale,
  20495. rotation: rotation,
  20496. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20497. sideOrientation: sideOrientation,
  20498. instance: instance,
  20499. updatable: updatable
  20500. };
  20501. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20502. };
  20503. /**
  20504. * Creates an custom extruded shape mesh.
  20505. * 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.
  20506. * Please consider using the same method from the MeshBuilder class instead.
  20507. *
  20508. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20509. * 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
  20510. * extruded along the Z axis.
  20511. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20512. * 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
  20513. * and the distance of this point from the begining of the path :
  20514. * ```javascript
  20515. * var rotationFunction = function(i, distance) {
  20516. * // do things
  20517. * return rotationValue; }
  20518. * ```
  20519. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20520. * 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
  20521. * and the distance of this point from the begining of the path :
  20522. * ```javascript
  20523. * var scaleFunction = function(i, distance) {
  20524. * // do things
  20525. * return scaleValue;}
  20526. * ```
  20527. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20528. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20529. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20530. * 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
  20531. * 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
  20532. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20533. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20534. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20536. */
  20537. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20538. var options = {
  20539. shape: shape,
  20540. path: path,
  20541. scaleFunction: scaleFunction,
  20542. rotationFunction: rotationFunction,
  20543. ribbonCloseArray: ribbonCloseArray,
  20544. ribbonClosePath: ribbonClosePath,
  20545. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20546. sideOrientation: sideOrientation,
  20547. instance: instance,
  20548. updatable: updatable
  20549. };
  20550. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20551. };
  20552. /**
  20553. * Creates lathe mesh.
  20554. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20555. * Please consider using the same method from the MeshBuilder class instead.
  20556. * 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
  20557. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20558. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20559. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20560. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20561. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20562. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20563. */
  20564. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20565. var options = {
  20566. shape: shape,
  20567. radius: radius,
  20568. tessellation: tessellation,
  20569. sideOrientation: sideOrientation,
  20570. updatable: updatable
  20571. };
  20572. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20573. };
  20574. /**
  20575. * Creates a plane mesh.
  20576. * Please consider using the same method from the MeshBuilder class instead.
  20577. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20578. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20579. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20580. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20581. */
  20582. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20583. var options = {
  20584. size: size,
  20585. width: size,
  20586. height: size,
  20587. sideOrientation: sideOrientation,
  20588. updatable: updatable
  20589. };
  20590. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20591. };
  20592. /**
  20593. * Creates a ground mesh.
  20594. * Please consider using the same method from the MeshBuilder class instead.
  20595. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20596. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20598. */
  20599. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20600. var options = {
  20601. width: width,
  20602. height: height,
  20603. subdivisions: subdivisions,
  20604. updatable: updatable
  20605. };
  20606. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20607. };
  20608. /**
  20609. * Creates a tiled ground mesh.
  20610. * Please consider using the same method from the MeshBuilder class instead.
  20611. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20612. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20613. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20614. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20615. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20616. * numbers of subdivisions on the ground width and height of each tile.
  20617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20618. */
  20619. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20620. var options = {
  20621. xmin: xmin,
  20622. zmin: zmin,
  20623. xmax: xmax,
  20624. zmax: zmax,
  20625. subdivisions: subdivisions,
  20626. precision: precision,
  20627. updatable: updatable
  20628. };
  20629. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20630. };
  20631. /**
  20632. * Creates a ground mesh from a height map.
  20633. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20634. * Please consider using the same method from the MeshBuilder class instead.
  20635. * The parameter `url` sets the URL of the height map image resource.
  20636. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20637. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20638. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20639. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20640. * 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).
  20641. * This function is passed the newly built mesh :
  20642. * ```javascript
  20643. * function(mesh) { // do things
  20644. * return; }
  20645. * ```
  20646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20647. */
  20648. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20649. var options = {
  20650. width: width,
  20651. height: height,
  20652. subdivisions: subdivisions,
  20653. minHeight: minHeight,
  20654. maxHeight: maxHeight,
  20655. updatable: updatable,
  20656. onReady: onReady
  20657. };
  20658. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20659. };
  20660. /**
  20661. * Creates a tube mesh.
  20662. * 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.
  20663. * Please consider using the same method from the MeshBuilder class instead.
  20664. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20665. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20666. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20667. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20668. * 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.
  20669. * It must return a radius value (positive float) :
  20670. * ```javascript
  20671. * var radiusFunction = function(i, distance) {
  20672. * // do things
  20673. * return radius; }
  20674. * ```
  20675. * 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
  20676. * 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
  20677. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20678. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20679. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20680. */
  20681. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20682. var options = {
  20683. path: path,
  20684. radius: radius,
  20685. tessellation: tessellation,
  20686. radiusFunction: radiusFunction,
  20687. arc: 1,
  20688. cap: cap,
  20689. updatable: updatable,
  20690. sideOrientation: sideOrientation,
  20691. instance: instance
  20692. };
  20693. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20694. };
  20695. /**
  20696. * Creates a polyhedron mesh.
  20697. * Please consider using the same method from the MeshBuilder class instead.
  20698. * 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
  20699. * to choose the wanted type.
  20700. * The parameter `size` (positive float, default 1) sets the polygon size.
  20701. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20702. * 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`.
  20703. * 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
  20704. * 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)`).
  20705. * 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
  20706. * 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.
  20707. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20708. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20709. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20710. */
  20711. Mesh.CreatePolyhedron = function (name, options, scene) {
  20712. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20713. };
  20714. /**
  20715. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20716. * Please consider using the same method from the MeshBuilder class instead.
  20717. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20718. * 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`).
  20719. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20720. * 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.
  20721. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20722. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20723. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20724. */
  20725. Mesh.CreateIcoSphere = function (name, options, scene) {
  20726. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20727. };
  20728. /**
  20729. * Creates a decal mesh.
  20730. * Please consider using the same method from the MeshBuilder class instead.
  20731. * 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.
  20732. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20733. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20734. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20735. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20736. */
  20737. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20738. var options = {
  20739. position: position,
  20740. normal: normal,
  20741. size: size,
  20742. angle: angle
  20743. };
  20744. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20745. };
  20746. // Skeletons
  20747. /**
  20748. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20749. */
  20750. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20751. var source;
  20752. if (!this._sourcePositions) {
  20753. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20754. this._sourcePositions = new Float32Array(source);
  20755. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20756. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20757. }
  20758. }
  20759. return this._sourcePositions;
  20760. };
  20761. /**
  20762. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20763. */
  20764. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20765. var source;
  20766. if (!this._sourceNormals) {
  20767. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20768. this._sourceNormals = new Float32Array(source);
  20769. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20770. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20771. }
  20772. }
  20773. return this._sourceNormals;
  20774. };
  20775. /**
  20776. * Updates the vertex buffer by applying transformation from the bones.
  20777. * Returns the Mesh.
  20778. *
  20779. * @param {skeleton} skeleton to apply
  20780. */
  20781. Mesh.prototype.applySkeleton = function (skeleton) {
  20782. if (!this.geometry) {
  20783. return this;
  20784. }
  20785. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20786. return this;
  20787. }
  20788. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20789. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20790. return this;
  20791. }
  20792. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20793. return this;
  20794. }
  20795. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20796. return this;
  20797. }
  20798. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20799. return this;
  20800. }
  20801. if (!this._sourcePositions) {
  20802. var submeshes = this.subMeshes.slice();
  20803. this.setPositionsForCPUSkinning();
  20804. this.subMeshes = submeshes;
  20805. }
  20806. if (!this._sourceNormals) {
  20807. this.setNormalsForCPUSkinning();
  20808. }
  20809. // positionsData checks for not being Float32Array will only pass at most once
  20810. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20811. if (!(positionsData instanceof Float32Array)) {
  20812. positionsData = new Float32Array(positionsData);
  20813. }
  20814. // normalsData checks for not being Float32Array will only pass at most once
  20815. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20816. if (!(normalsData instanceof Float32Array)) {
  20817. normalsData = new Float32Array(normalsData);
  20818. }
  20819. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20820. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20821. var needExtras = this.numBoneInfluencers > 4;
  20822. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20823. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20824. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20825. var tempVector3 = BABYLON.Vector3.Zero();
  20826. var finalMatrix = new BABYLON.Matrix();
  20827. var tempMatrix = new BABYLON.Matrix();
  20828. var matWeightIdx = 0;
  20829. var inf;
  20830. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20831. var weight;
  20832. for (inf = 0; inf < 4; inf++) {
  20833. weight = matricesWeightsData[matWeightIdx + inf];
  20834. if (weight > 0) {
  20835. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20836. finalMatrix.addToSelf(tempMatrix);
  20837. }
  20838. else
  20839. break;
  20840. }
  20841. if (needExtras) {
  20842. for (inf = 0; inf < 4; inf++) {
  20843. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20844. if (weight > 0) {
  20845. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20846. finalMatrix.addToSelf(tempMatrix);
  20847. }
  20848. else
  20849. break;
  20850. }
  20851. }
  20852. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20853. tempVector3.toArray(positionsData, index);
  20854. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20855. tempVector3.toArray(normalsData, index);
  20856. finalMatrix.reset();
  20857. }
  20858. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20859. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20860. return this;
  20861. };
  20862. // Tools
  20863. /**
  20864. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20865. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20866. */
  20867. Mesh.MinMax = function (meshes) {
  20868. var minVector = null;
  20869. var maxVector = null;
  20870. meshes.forEach(function (mesh, index, array) {
  20871. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20872. if (!minVector) {
  20873. minVector = boundingBox.minimumWorld;
  20874. maxVector = boundingBox.maximumWorld;
  20875. }
  20876. else {
  20877. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20878. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20879. }
  20880. });
  20881. return {
  20882. min: minVector,
  20883. max: maxVector
  20884. };
  20885. };
  20886. /**
  20887. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20888. */
  20889. Mesh.Center = function (meshesOrMinMaxVector) {
  20890. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  20891. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20892. };
  20893. /**
  20894. * Merge the array of meshes into a single mesh for performance reasons.
  20895. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20896. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20897. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20898. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20899. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  20900. */
  20901. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  20902. if (disposeSource === void 0) { disposeSource = true; }
  20903. var index;
  20904. if (!allow32BitsIndices) {
  20905. var totalVertices = 0;
  20906. // Counting vertices
  20907. for (index = 0; index < meshes.length; index++) {
  20908. if (meshes[index]) {
  20909. totalVertices += meshes[index].getTotalVertices();
  20910. if (totalVertices > 65536) {
  20911. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20912. return null;
  20913. }
  20914. }
  20915. }
  20916. }
  20917. // Merge
  20918. var vertexData;
  20919. var otherVertexData;
  20920. var indiceArray = new Array();
  20921. var source;
  20922. for (index = 0; index < meshes.length; index++) {
  20923. if (meshes[index]) {
  20924. meshes[index].computeWorldMatrix(true);
  20925. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20926. otherVertexData.transform(meshes[index].getWorldMatrix());
  20927. if (vertexData) {
  20928. vertexData.merge(otherVertexData);
  20929. }
  20930. else {
  20931. vertexData = otherVertexData;
  20932. source = meshes[index];
  20933. }
  20934. if (subdivideWithSubMeshes) {
  20935. indiceArray.push(meshes[index].getTotalIndices());
  20936. }
  20937. }
  20938. }
  20939. if (!meshSubclass) {
  20940. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  20941. }
  20942. vertexData.applyToMesh(meshSubclass);
  20943. // Setting properties
  20944. meshSubclass.material = source.material;
  20945. meshSubclass.checkCollisions = source.checkCollisions;
  20946. // Cleaning
  20947. if (disposeSource) {
  20948. for (index = 0; index < meshes.length; index++) {
  20949. if (meshes[index]) {
  20950. meshes[index].dispose();
  20951. }
  20952. }
  20953. }
  20954. // Subdivide
  20955. if (subdivideWithSubMeshes) {
  20956. //-- Suppresions du submesh global
  20957. meshSubclass.releaseSubMeshes();
  20958. index = 0;
  20959. var offset = 0;
  20960. //-- aplique la subdivision en fonction du tableau d'indices
  20961. while (index < indiceArray.length) {
  20962. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  20963. offset += indiceArray[index];
  20964. index++;
  20965. }
  20966. }
  20967. return meshSubclass;
  20968. };
  20969. return Mesh;
  20970. }(BABYLON.AbstractMesh));
  20971. // Consts
  20972. Mesh._FRONTSIDE = 0;
  20973. Mesh._BACKSIDE = 1;
  20974. Mesh._DOUBLESIDE = 2;
  20975. Mesh._DEFAULTSIDE = 0;
  20976. Mesh._NO_CAP = 0;
  20977. Mesh._CAP_START = 1;
  20978. Mesh._CAP_END = 2;
  20979. Mesh._CAP_ALL = 3;
  20980. BABYLON.Mesh = Mesh;
  20981. })(BABYLON || (BABYLON = {}));
  20982. //# sourceMappingURL=babylon.mesh.js.map
  20983. var BABYLON;
  20984. (function (BABYLON) {
  20985. var SubMesh = (function () {
  20986. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  20987. if (createBoundingBox === void 0) { createBoundingBox = true; }
  20988. this.materialIndex = materialIndex;
  20989. this.verticesStart = verticesStart;
  20990. this.verticesCount = verticesCount;
  20991. this.indexStart = indexStart;
  20992. this.indexCount = indexCount;
  20993. this._renderId = 0;
  20994. this._mesh = mesh;
  20995. this._renderingMesh = renderingMesh || mesh;
  20996. mesh.subMeshes.push(this);
  20997. this._trianglePlanes = [];
  20998. this._id = mesh.subMeshes.length - 1;
  20999. if (createBoundingBox) {
  21000. this.refreshBoundingInfo();
  21001. mesh.computeWorldMatrix(true);
  21002. }
  21003. }
  21004. Object.defineProperty(SubMesh.prototype, "effect", {
  21005. get: function () {
  21006. return this._materialEffect;
  21007. },
  21008. enumerable: true,
  21009. configurable: true
  21010. });
  21011. SubMesh.prototype.setEffect = function (effect, defines) {
  21012. if (this._materialEffect === effect) {
  21013. return;
  21014. }
  21015. this._materialDefines = defines;
  21016. this._materialEffect = effect;
  21017. };
  21018. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21019. get: function () {
  21020. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21021. },
  21022. enumerable: true,
  21023. configurable: true
  21024. });
  21025. /**
  21026. * Returns the submesh BoudingInfo object.
  21027. */
  21028. SubMesh.prototype.getBoundingInfo = function () {
  21029. if (this.IsGlobal) {
  21030. return this._mesh.getBoundingInfo();
  21031. }
  21032. return this._boundingInfo;
  21033. };
  21034. /**
  21035. * Sets the submesh BoundingInfo.
  21036. * Return the SubMesh.
  21037. */
  21038. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21039. this._boundingInfo = boundingInfo;
  21040. return this;
  21041. };
  21042. /**
  21043. * Returns the mesh of the current submesh.
  21044. */
  21045. SubMesh.prototype.getMesh = function () {
  21046. return this._mesh;
  21047. };
  21048. /**
  21049. * Returns the rendering mesh of the submesh.
  21050. */
  21051. SubMesh.prototype.getRenderingMesh = function () {
  21052. return this._renderingMesh;
  21053. };
  21054. /**
  21055. * Returns the submesh material.
  21056. */
  21057. SubMesh.prototype.getMaterial = function () {
  21058. var rootMaterial = this._renderingMesh.material;
  21059. if (rootMaterial && rootMaterial.getSubMaterial) {
  21060. var multiMaterial = rootMaterial;
  21061. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  21062. if (this._currentMaterial !== effectiveMaterial) {
  21063. this._currentMaterial = effectiveMaterial;
  21064. if (this._materialDefines) {
  21065. this._materialDefines.markAllAsDirty();
  21066. }
  21067. }
  21068. return effectiveMaterial;
  21069. }
  21070. if (!rootMaterial) {
  21071. return this._mesh.getScene().defaultMaterial;
  21072. }
  21073. return rootMaterial;
  21074. };
  21075. // Methods
  21076. /**
  21077. * Sets a new updated BoundingInfo object to the submesh.
  21078. * Returns the SubMesh.
  21079. */
  21080. SubMesh.prototype.refreshBoundingInfo = function () {
  21081. this._lastColliderWorldVertices = null;
  21082. if (this.IsGlobal) {
  21083. return;
  21084. }
  21085. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21086. if (!data) {
  21087. this._boundingInfo = this._mesh._boundingInfo;
  21088. return;
  21089. }
  21090. var indices = this._renderingMesh.getIndices();
  21091. var extend;
  21092. //is this the only submesh?
  21093. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21094. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21095. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21096. }
  21097. else {
  21098. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21099. }
  21100. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21101. return this;
  21102. };
  21103. SubMesh.prototype._checkCollision = function (collider) {
  21104. return this.getBoundingInfo()._checkCollision(collider);
  21105. };
  21106. /**
  21107. * Updates the submesh BoundingInfo.
  21108. * Returns the Submesh.
  21109. */
  21110. SubMesh.prototype.updateBoundingInfo = function (world) {
  21111. if (!this.getBoundingInfo()) {
  21112. this.refreshBoundingInfo();
  21113. }
  21114. this.getBoundingInfo().update(world);
  21115. return this;
  21116. };
  21117. /**
  21118. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  21119. * Boolean returned.
  21120. */
  21121. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21122. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21123. };
  21124. /**
  21125. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  21126. * Boolean returned.
  21127. */
  21128. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21129. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21130. };
  21131. /**
  21132. * Renders the submesh.
  21133. * Returns it.
  21134. */
  21135. SubMesh.prototype.render = function (enableAlphaMode) {
  21136. this._renderingMesh.render(this, enableAlphaMode);
  21137. return this;
  21138. };
  21139. /**
  21140. * Returns a new Index Buffer.
  21141. * Type returned : WebGLBuffer.
  21142. */
  21143. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21144. if (!this._linesIndexBuffer) {
  21145. var linesIndices = [];
  21146. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21147. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21148. }
  21149. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21150. this.linesIndexCount = linesIndices.length;
  21151. }
  21152. return this._linesIndexBuffer;
  21153. };
  21154. /**
  21155. * True is the passed Ray intersects the submesh bounding box.
  21156. * Boolean returned.
  21157. */
  21158. SubMesh.prototype.canIntersects = function (ray) {
  21159. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21160. };
  21161. /**
  21162. * Returns an object IntersectionInfo.
  21163. */
  21164. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21165. var intersectInfo = null;
  21166. // LineMesh first as it's also a Mesh...
  21167. if (this._mesh instanceof BABYLON.LinesMesh) {
  21168. var lineMesh = this._mesh;
  21169. // Line test
  21170. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21171. var p0 = positions[indices[index]];
  21172. var p1 = positions[indices[index + 1]];
  21173. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21174. if (length < 0) {
  21175. continue;
  21176. }
  21177. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21178. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21179. if (fastCheck) {
  21180. break;
  21181. }
  21182. }
  21183. }
  21184. }
  21185. else {
  21186. // Triangles test
  21187. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21188. var p0 = positions[indices[index]];
  21189. var p1 = positions[indices[index + 1]];
  21190. var p2 = positions[indices[index + 2]];
  21191. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21192. if (currentIntersectInfo) {
  21193. if (currentIntersectInfo.distance < 0) {
  21194. continue;
  21195. }
  21196. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21197. intersectInfo = currentIntersectInfo;
  21198. intersectInfo.faceId = index / 3;
  21199. if (fastCheck) {
  21200. break;
  21201. }
  21202. }
  21203. }
  21204. }
  21205. }
  21206. return intersectInfo;
  21207. };
  21208. // Clone
  21209. /**
  21210. * Creates a new Submesh from the passed Mesh.
  21211. */
  21212. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21213. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21214. if (!this.IsGlobal) {
  21215. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21216. }
  21217. return result;
  21218. };
  21219. // Dispose
  21220. /**
  21221. * Disposes the Submesh.
  21222. * Returns nothing.
  21223. */
  21224. SubMesh.prototype.dispose = function () {
  21225. if (this._linesIndexBuffer) {
  21226. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21227. this._linesIndexBuffer = null;
  21228. }
  21229. // Remove from mesh
  21230. var index = this._mesh.subMeshes.indexOf(this);
  21231. this._mesh.subMeshes.splice(index, 1);
  21232. };
  21233. // Statics
  21234. /**
  21235. * Creates a new Submesh from the passed parameters :
  21236. * - materialIndex (integer) : the index of the main mesh material.
  21237. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  21238. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  21239. * - mesh (Mesh) : the main mesh to create the submesh from.
  21240. * - renderingMesh (optional Mesh) : rendering mesh.
  21241. */
  21242. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21243. var minVertexIndex = Number.MAX_VALUE;
  21244. var maxVertexIndex = -Number.MAX_VALUE;
  21245. renderingMesh = renderingMesh || mesh;
  21246. var indices = renderingMesh.getIndices();
  21247. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21248. var vertexIndex = indices[index];
  21249. if (vertexIndex < minVertexIndex)
  21250. minVertexIndex = vertexIndex;
  21251. if (vertexIndex > maxVertexIndex)
  21252. maxVertexIndex = vertexIndex;
  21253. }
  21254. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21255. };
  21256. return SubMesh;
  21257. }());
  21258. BABYLON.SubMesh = SubMesh;
  21259. })(BABYLON || (BABYLON = {}));
  21260. //# sourceMappingURL=babylon.subMesh.js.map
  21261. var BABYLON;
  21262. (function (BABYLON) {
  21263. var EffectFallbacks = (function () {
  21264. function EffectFallbacks() {
  21265. this._defines = {};
  21266. this._currentRank = 32;
  21267. this._maxRank = -1;
  21268. }
  21269. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21270. if (!this._defines[rank]) {
  21271. if (rank < this._currentRank) {
  21272. this._currentRank = rank;
  21273. }
  21274. if (rank > this._maxRank) {
  21275. this._maxRank = rank;
  21276. }
  21277. this._defines[rank] = new Array();
  21278. }
  21279. this._defines[rank].push(define);
  21280. };
  21281. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21282. this._meshRank = rank;
  21283. this._mesh = mesh;
  21284. if (rank < this._currentRank) {
  21285. this._currentRank = rank;
  21286. }
  21287. if (rank > this._maxRank) {
  21288. this._maxRank = rank;
  21289. }
  21290. };
  21291. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21292. get: function () {
  21293. return this._currentRank <= this._maxRank;
  21294. },
  21295. enumerable: true,
  21296. configurable: true
  21297. });
  21298. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21299. // First we try to switch to CPU skinning
  21300. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  21301. this._mesh.computeBonesUsingShaders = false;
  21302. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21303. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21304. var scene = this._mesh.getScene();
  21305. for (var index = 0; index < scene.meshes.length; index++) {
  21306. var otherMesh = scene.meshes[index];
  21307. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  21308. otherMesh.computeBonesUsingShaders = false;
  21309. }
  21310. }
  21311. }
  21312. else {
  21313. var currentFallbacks = this._defines[this._currentRank];
  21314. if (currentFallbacks) {
  21315. for (var index = 0; index < currentFallbacks.length; index++) {
  21316. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21317. }
  21318. }
  21319. this._currentRank++;
  21320. }
  21321. return currentDefines;
  21322. };
  21323. return EffectFallbacks;
  21324. }());
  21325. BABYLON.EffectFallbacks = EffectFallbacks;
  21326. var EffectCreationOptions = (function () {
  21327. function EffectCreationOptions() {
  21328. }
  21329. return EffectCreationOptions;
  21330. }());
  21331. BABYLON.EffectCreationOptions = EffectCreationOptions;
  21332. var Effect = (function () {
  21333. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  21334. var _this = this;
  21335. this.uniqueId = 0;
  21336. this._isReady = false;
  21337. this._compilationError = "";
  21338. this._valueCache = {};
  21339. this.name = baseName;
  21340. if (attributesNamesOrOptions.attributes) {
  21341. var options = attributesNamesOrOptions;
  21342. this._engine = uniformsNamesOrEngine;
  21343. this._attributesNames = options.attributes;
  21344. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  21345. this._samplers = options.samplers;
  21346. this.defines = options.defines;
  21347. this.onError = options.onError;
  21348. this.onCompiled = options.onCompiled;
  21349. this._fallbacks = options.fallbacks;
  21350. this._indexParameters = options.indexParameters;
  21351. }
  21352. else {
  21353. this._engine = engine;
  21354. this.defines = defines;
  21355. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  21356. this._samplers = samplers;
  21357. this._attributesNames = attributesNamesOrOptions;
  21358. this.onError = onError;
  21359. this.onCompiled = onCompiled;
  21360. this._indexParameters = indexParameters;
  21361. this._fallbacks = fallbacks;
  21362. }
  21363. this.uniqueId = Effect._uniqueIdSeed++;
  21364. var vertexSource;
  21365. var fragmentSource;
  21366. if (baseName.vertexElement) {
  21367. vertexSource = document.getElementById(baseName.vertexElement);
  21368. if (!vertexSource) {
  21369. vertexSource = baseName.vertexElement;
  21370. }
  21371. }
  21372. else {
  21373. vertexSource = baseName.vertex || baseName;
  21374. }
  21375. if (baseName.fragmentElement) {
  21376. fragmentSource = document.getElementById(baseName.fragmentElement);
  21377. if (!fragmentSource) {
  21378. fragmentSource = baseName.fragmentElement;
  21379. }
  21380. }
  21381. else {
  21382. fragmentSource = baseName.fragment || baseName;
  21383. }
  21384. this._loadVertexShader(vertexSource, function (vertexCode) {
  21385. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21386. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  21387. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21388. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21389. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  21390. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  21391. });
  21392. });
  21393. });
  21394. });
  21395. });
  21396. });
  21397. }
  21398. Object.defineProperty(Effect.prototype, "key", {
  21399. get: function () {
  21400. return this._key;
  21401. },
  21402. enumerable: true,
  21403. configurable: true
  21404. });
  21405. // Properties
  21406. Effect.prototype.isReady = function () {
  21407. return this._isReady;
  21408. };
  21409. Effect.prototype.getProgram = function () {
  21410. return this._program;
  21411. };
  21412. Effect.prototype.getAttributesNames = function () {
  21413. return this._attributesNames;
  21414. };
  21415. Effect.prototype.getAttributeLocation = function (index) {
  21416. return this._attributes[index];
  21417. };
  21418. Effect.prototype.getAttributeLocationByName = function (name) {
  21419. var index = this._attributesNames.indexOf(name);
  21420. return this._attributes[index];
  21421. };
  21422. Effect.prototype.getAttributesCount = function () {
  21423. return this._attributes.length;
  21424. };
  21425. Effect.prototype.getUniformIndex = function (uniformName) {
  21426. return this._uniformsNames.indexOf(uniformName);
  21427. };
  21428. Effect.prototype.getUniform = function (uniformName) {
  21429. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21430. };
  21431. Effect.prototype.getSamplers = function () {
  21432. return this._samplers;
  21433. };
  21434. Effect.prototype.getCompilationError = function () {
  21435. return this._compilationError;
  21436. };
  21437. Effect.prototype.getVertexShaderSource = function () {
  21438. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  21439. };
  21440. Effect.prototype.getFragmentShaderSource = function () {
  21441. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  21442. };
  21443. // Methods
  21444. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21445. // DOM element ?
  21446. if (vertex instanceof HTMLElement) {
  21447. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21448. callback(vertexCode);
  21449. return;
  21450. }
  21451. // Base64 encoded ?
  21452. if (vertex.substr(0, 7) === "base64:") {
  21453. var vertexBinary = window.atob(vertex.substr(7));
  21454. callback(vertexBinary);
  21455. return;
  21456. }
  21457. // Is in local store ?
  21458. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21459. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21460. return;
  21461. }
  21462. var vertexShaderUrl;
  21463. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21464. vertexShaderUrl = vertex;
  21465. }
  21466. else {
  21467. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21468. }
  21469. // Vertex shader
  21470. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21471. };
  21472. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21473. // DOM element ?
  21474. if (fragment instanceof HTMLElement) {
  21475. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21476. callback(fragmentCode);
  21477. return;
  21478. }
  21479. // Base64 encoded ?
  21480. if (fragment.substr(0, 7) === "base64:") {
  21481. var fragmentBinary = window.atob(fragment.substr(7));
  21482. callback(fragmentBinary);
  21483. return;
  21484. }
  21485. // Is in local store ?
  21486. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21487. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21488. return;
  21489. }
  21490. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21491. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21492. return;
  21493. }
  21494. var fragmentShaderUrl;
  21495. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21496. fragmentShaderUrl = fragment;
  21497. }
  21498. else {
  21499. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21500. }
  21501. // Fragment shader
  21502. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21503. };
  21504. Effect.prototype._dumpShadersName = function () {
  21505. if (this.name.vertexElement) {
  21506. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  21507. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  21508. }
  21509. else if (this.name.vertex) {
  21510. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  21511. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  21512. }
  21513. else {
  21514. BABYLON.Tools.Error("Vertex shader:" + this.name);
  21515. BABYLON.Tools.Error("Fragment shader:" + this.name);
  21516. }
  21517. };
  21518. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  21519. var preparedSourceCode = this._processPrecision(sourceCode);
  21520. if (this._engine.webGLVersion == 1) {
  21521. callback(preparedSourceCode);
  21522. return;
  21523. }
  21524. // Already converted
  21525. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  21526. callback(preparedSourceCode);
  21527. return;
  21528. }
  21529. // Remove extensions
  21530. // #extension GL_OES_standard_derivatives : enable
  21531. // #extension GL_EXT_shader_texture_lod : enable
  21532. // #extension GL_EXT_frag_depth : enable
  21533. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  21534. var result = preparedSourceCode.replace(regex, "");
  21535. // Migrate to GLSL v300
  21536. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  21537. result = result.replace(/attribute[ \t]/g, "in ");
  21538. result = result.replace(/[ \t]attribute/g, " in");
  21539. if (isFragment) {
  21540. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  21541. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  21542. result = result.replace(/texture2D\(/g, "texture(");
  21543. result = result.replace(/textureCube\(/g, "texture(");
  21544. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  21545. result = result.replace(/gl_FragColor/g, "glFragColor");
  21546. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  21547. }
  21548. callback(result);
  21549. };
  21550. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21551. var _this = this;
  21552. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21553. var match = regex.exec(sourceCode);
  21554. var returnValue = new String(sourceCode);
  21555. while (match != null) {
  21556. var includeFile = match[1];
  21557. if (Effect.IncludesShadersStore[includeFile]) {
  21558. // Substitution
  21559. var includeContent = Effect.IncludesShadersStore[includeFile];
  21560. if (match[2]) {
  21561. var splits = match[3].split(",");
  21562. for (var index = 0; index < splits.length; index += 2) {
  21563. var source = new RegExp(splits[index], "g");
  21564. var dest = splits[index + 1];
  21565. includeContent = includeContent.replace(source, dest);
  21566. }
  21567. }
  21568. if (match[4]) {
  21569. var indexString = match[5];
  21570. if (indexString.indexOf("..") !== -1) {
  21571. var indexSplits = indexString.split("..");
  21572. var minIndex = parseInt(indexSplits[0]);
  21573. var maxIndex = parseInt(indexSplits[1]);
  21574. var sourceIncludeContent = includeContent.slice(0);
  21575. includeContent = "";
  21576. if (isNaN(maxIndex)) {
  21577. maxIndex = this._indexParameters[indexSplits[1]];
  21578. }
  21579. for (var i = minIndex; i < maxIndex; i++) {
  21580. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  21581. }
  21582. }
  21583. else {
  21584. includeContent = includeContent.replace(/\{X\}/g, indexString);
  21585. }
  21586. }
  21587. // Replace
  21588. returnValue = returnValue.replace(match[0], includeContent);
  21589. }
  21590. else {
  21591. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21592. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21593. Effect.IncludesShadersStore[includeFile] = fileContent;
  21594. _this._processIncludes(returnValue, callback);
  21595. });
  21596. return;
  21597. }
  21598. match = regex.exec(sourceCode);
  21599. }
  21600. callback(returnValue);
  21601. };
  21602. Effect.prototype._processPrecision = function (source) {
  21603. if (source.indexOf("precision highp float") === -1) {
  21604. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21605. source = "precision mediump float;\n" + source;
  21606. }
  21607. else {
  21608. source = "precision highp float;\n" + source;
  21609. }
  21610. }
  21611. else {
  21612. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21613. source = source.replace("precision highp float", "precision mediump float");
  21614. }
  21615. }
  21616. return source;
  21617. };
  21618. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21619. try {
  21620. var engine = this._engine;
  21621. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21622. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21623. this._attributes = engine.getAttributes(this._program, attributesNames);
  21624. var index;
  21625. for (index = 0; index < this._samplers.length; index++) {
  21626. var sampler = this.getUniform(this._samplers[index]);
  21627. if (sampler == null) {
  21628. this._samplers.splice(index, 1);
  21629. index--;
  21630. }
  21631. }
  21632. engine.bindSamplers(this);
  21633. this._compilationError = "";
  21634. this._isReady = true;
  21635. if (this.onCompiled) {
  21636. this.onCompiled(this);
  21637. }
  21638. }
  21639. catch (e) {
  21640. this._compilationError = e.message;
  21641. // Let's go through fallbacks then
  21642. BABYLON.Tools.Error("Unable to compile effect: ");
  21643. BABYLON.Tools.Error("Defines: " + defines);
  21644. BABYLON.Tools.Error("Error: " + this._compilationError);
  21645. this._dumpShadersName();
  21646. if (fallbacks && fallbacks.isMoreFallbacks) {
  21647. BABYLON.Tools.Error("Trying next fallback.");
  21648. defines = fallbacks.reduce(defines);
  21649. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21650. }
  21651. else {
  21652. if (this.onError) {
  21653. this.onError(this, this._compilationError);
  21654. }
  21655. }
  21656. }
  21657. };
  21658. Object.defineProperty(Effect.prototype, "isSupported", {
  21659. get: function () {
  21660. return this._compilationError === "";
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. Effect.prototype._bindTexture = function (channel, texture) {
  21666. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21667. };
  21668. Effect.prototype.setTexture = function (channel, texture) {
  21669. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  21670. };
  21671. Effect.prototype.setTextureArray = function (channel, textures) {
  21672. if (this._samplers.indexOf(channel + "Ex") === -1) {
  21673. var initialPos = this._samplers.indexOf(channel);
  21674. for (var index = 1; index < textures.length; index++) {
  21675. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  21676. }
  21677. }
  21678. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  21679. };
  21680. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21681. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21682. };
  21683. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21684. var cache = this._valueCache[uniformName];
  21685. var flag = matrix.updateFlag;
  21686. if (cache !== undefined && cache === flag) {
  21687. return false;
  21688. }
  21689. this._valueCache[uniformName] = flag;
  21690. return true;
  21691. };
  21692. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21693. var cache = this._valueCache[uniformName];
  21694. if (!cache) {
  21695. cache = [x, y];
  21696. this._valueCache[uniformName] = cache;
  21697. return true;
  21698. }
  21699. var changed = false;
  21700. if (cache[0] !== x) {
  21701. cache[0] = x;
  21702. changed = true;
  21703. }
  21704. if (cache[1] !== y) {
  21705. cache[1] = y;
  21706. changed = true;
  21707. }
  21708. return changed;
  21709. };
  21710. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21711. var cache = this._valueCache[uniformName];
  21712. if (!cache) {
  21713. cache = [x, y, z];
  21714. this._valueCache[uniformName] = cache;
  21715. return true;
  21716. }
  21717. var changed = false;
  21718. if (cache[0] !== x) {
  21719. cache[0] = x;
  21720. changed = true;
  21721. }
  21722. if (cache[1] !== y) {
  21723. cache[1] = y;
  21724. changed = true;
  21725. }
  21726. if (cache[2] !== z) {
  21727. cache[2] = z;
  21728. changed = true;
  21729. }
  21730. return changed;
  21731. };
  21732. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  21733. var cache = this._valueCache[uniformName];
  21734. if (!cache) {
  21735. cache = [x, y, z, w];
  21736. this._valueCache[uniformName] = cache;
  21737. return true;
  21738. }
  21739. var changed = false;
  21740. if (cache[0] !== x) {
  21741. cache[0] = x;
  21742. changed = true;
  21743. }
  21744. if (cache[1] !== y) {
  21745. cache[1] = y;
  21746. changed = true;
  21747. }
  21748. if (cache[2] !== z) {
  21749. cache[2] = z;
  21750. changed = true;
  21751. }
  21752. if (cache[3] !== w) {
  21753. cache[3] = w;
  21754. changed = true;
  21755. }
  21756. return changed;
  21757. };
  21758. Effect.prototype.setIntArray = function (uniformName, array) {
  21759. this._valueCache[uniformName] = null;
  21760. this._engine.setIntArray(this.getUniform(uniformName), array);
  21761. return this;
  21762. };
  21763. Effect.prototype.setIntArray2 = function (uniformName, array) {
  21764. this._valueCache[uniformName] = null;
  21765. this._engine.setIntArray2(this.getUniform(uniformName), array);
  21766. return this;
  21767. };
  21768. Effect.prototype.setIntArray3 = function (uniformName, array) {
  21769. this._valueCache[uniformName] = null;
  21770. this._engine.setIntArray3(this.getUniform(uniformName), array);
  21771. return this;
  21772. };
  21773. Effect.prototype.setIntArray4 = function (uniformName, array) {
  21774. this._valueCache[uniformName] = null;
  21775. this._engine.setIntArray4(this.getUniform(uniformName), array);
  21776. return this;
  21777. };
  21778. Effect.prototype.setFloatArray = function (uniformName, array) {
  21779. this._valueCache[uniformName] = null;
  21780. this._engine.setFloatArray(this.getUniform(uniformName), array);
  21781. return this;
  21782. };
  21783. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  21784. this._valueCache[uniformName] = null;
  21785. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  21786. return this;
  21787. };
  21788. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  21789. this._valueCache[uniformName] = null;
  21790. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  21791. return this;
  21792. };
  21793. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  21794. this._valueCache[uniformName] = null;
  21795. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  21796. return this;
  21797. };
  21798. Effect.prototype.setArray = function (uniformName, array) {
  21799. this._valueCache[uniformName] = null;
  21800. this._engine.setArray(this.getUniform(uniformName), array);
  21801. return this;
  21802. };
  21803. Effect.prototype.setArray2 = function (uniformName, array) {
  21804. this._valueCache[uniformName] = null;
  21805. this._engine.setArray2(this.getUniform(uniformName), array);
  21806. return this;
  21807. };
  21808. Effect.prototype.setArray3 = function (uniformName, array) {
  21809. this._valueCache[uniformName] = null;
  21810. this._engine.setArray3(this.getUniform(uniformName), array);
  21811. return this;
  21812. };
  21813. Effect.prototype.setArray4 = function (uniformName, array) {
  21814. this._valueCache[uniformName] = null;
  21815. this._engine.setArray4(this.getUniform(uniformName), array);
  21816. return this;
  21817. };
  21818. Effect.prototype.setMatrices = function (uniformName, matrices) {
  21819. this._valueCache[uniformName] = null;
  21820. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  21821. return this;
  21822. };
  21823. Effect.prototype.setMatrix = function (uniformName, matrix) {
  21824. if (this._cacheMatrix(uniformName, matrix)) {
  21825. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  21826. }
  21827. return this;
  21828. };
  21829. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  21830. this._valueCache[uniformName] = null;
  21831. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  21832. return this;
  21833. };
  21834. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  21835. this._valueCache[uniformName] = null;
  21836. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  21837. return this;
  21838. };
  21839. Effect.prototype.setFloat = function (uniformName, value) {
  21840. var cache = this._valueCache[uniformName];
  21841. if (cache !== undefined && cache === value)
  21842. return this;
  21843. this._valueCache[uniformName] = value;
  21844. this._engine.setFloat(this.getUniform(uniformName), value);
  21845. return this;
  21846. };
  21847. Effect.prototype.setBool = function (uniformName, bool) {
  21848. var cache = this._valueCache[uniformName];
  21849. if (cache !== undefined && cache === bool)
  21850. return this;
  21851. this._valueCache[uniformName] = bool;
  21852. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  21853. return this;
  21854. };
  21855. Effect.prototype.setVector2 = function (uniformName, vector2) {
  21856. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  21857. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  21858. }
  21859. return this;
  21860. };
  21861. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  21862. if (this._cacheFloat2(uniformName, x, y)) {
  21863. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  21864. }
  21865. return this;
  21866. };
  21867. Effect.prototype.setVector3 = function (uniformName, vector3) {
  21868. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  21869. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  21870. }
  21871. return this;
  21872. };
  21873. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  21874. if (this._cacheFloat3(uniformName, x, y, z)) {
  21875. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  21876. }
  21877. return this;
  21878. };
  21879. Effect.prototype.setVector4 = function (uniformName, vector4) {
  21880. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  21881. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  21882. }
  21883. return this;
  21884. };
  21885. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  21886. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  21887. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  21888. }
  21889. return this;
  21890. };
  21891. Effect.prototype.setColor3 = function (uniformName, color3) {
  21892. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  21893. this._engine.setColor3(this.getUniform(uniformName), color3);
  21894. }
  21895. return this;
  21896. };
  21897. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  21898. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  21899. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  21900. }
  21901. return this;
  21902. };
  21903. Effect.prototype._recombineShader = function (node) {
  21904. if (node.define) {
  21905. if (node.condition) {
  21906. var defineIndex = this.defines.indexOf("#define " + node.define);
  21907. if (defineIndex === -1) {
  21908. return null;
  21909. }
  21910. var nextComma = this.defines.indexOf("\n", defineIndex);
  21911. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  21912. var condition = defineValue + node.condition;
  21913. if (!eval(condition)) {
  21914. return null;
  21915. }
  21916. }
  21917. else if (node.ndef) {
  21918. if (this.defines.indexOf("#define " + node.define) !== -1) {
  21919. return null;
  21920. }
  21921. }
  21922. else if (this.defines.indexOf("#define " + node.define) === -1) {
  21923. return null;
  21924. }
  21925. }
  21926. var result = "";
  21927. for (var index = 0; index < node.children.length; index++) {
  21928. var line = node.children[index];
  21929. if (line.children) {
  21930. var combined = this._recombineShader(line);
  21931. if (combined !== null) {
  21932. result += combined + "\r\n";
  21933. }
  21934. continue;
  21935. }
  21936. if (line.length > 0) {
  21937. result += line + "\r\n";
  21938. }
  21939. }
  21940. return result;
  21941. };
  21942. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  21943. var root = {
  21944. children: []
  21945. };
  21946. var currentNode = root;
  21947. var lines = shaderString.split("\n");
  21948. for (var index = 0; index < lines.length; index++) {
  21949. var line = lines[index].trim();
  21950. // #ifdef
  21951. var pos = line.indexOf("#ifdef ");
  21952. if (pos !== -1) {
  21953. var define = line.substr(pos + 7);
  21954. var newNode = {
  21955. condition: null,
  21956. ndef: false,
  21957. define: define,
  21958. children: [],
  21959. parent: currentNode
  21960. };
  21961. currentNode.children.push(newNode);
  21962. currentNode = newNode;
  21963. continue;
  21964. }
  21965. // #ifndef
  21966. var pos = line.indexOf("#ifndef ");
  21967. if (pos !== -1) {
  21968. var define = line.substr(pos + 8);
  21969. newNode = {
  21970. condition: null,
  21971. define: define,
  21972. ndef: true,
  21973. children: [],
  21974. parent: currentNode
  21975. };
  21976. currentNode.children.push(newNode);
  21977. currentNode = newNode;
  21978. continue;
  21979. }
  21980. // #if
  21981. var pos = line.indexOf("#if ");
  21982. if (pos !== -1) {
  21983. var define = line.substr(pos + 4).trim();
  21984. var conditionPos = define.indexOf(" ");
  21985. newNode = {
  21986. condition: define.substr(conditionPos + 1),
  21987. define: define.substr(0, conditionPos),
  21988. ndef: false,
  21989. children: [],
  21990. parent: currentNode
  21991. };
  21992. currentNode.children.push(newNode);
  21993. currentNode = newNode;
  21994. continue;
  21995. }
  21996. // #endif
  21997. pos = line.indexOf("#endif");
  21998. if (pos !== -1) {
  21999. currentNode = currentNode.parent;
  22000. continue;
  22001. }
  22002. currentNode.children.push(line);
  22003. }
  22004. // Recombine
  22005. return this._recombineShader(root);
  22006. };
  22007. return Effect;
  22008. }());
  22009. Effect._uniqueIdSeed = 0;
  22010. // Statics
  22011. Effect.ShadersStore = {};
  22012. Effect.IncludesShadersStore = {};
  22013. BABYLON.Effect = Effect;
  22014. })(BABYLON || (BABYLON = {}));
  22015. //# sourceMappingURL=babylon.effect.js.map
  22016. var BABYLON;
  22017. (function (BABYLON) {
  22018. var MaterialHelper = (function () {
  22019. function MaterialHelper() {
  22020. }
  22021. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  22022. if (defines._areMiscDirty) {
  22023. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  22024. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  22025. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  22026. }
  22027. };
  22028. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  22029. var changed = false;
  22030. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  22031. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  22032. changed = true;
  22033. }
  22034. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  22035. defines["ALPHATEST"] = !defines["ALPHATEST"];
  22036. changed = true;
  22037. }
  22038. if (defines["INSTANCES"] !== useInstances) {
  22039. defines["INSTANCES"] = useInstances;
  22040. changed = true;
  22041. }
  22042. if (changed) {
  22043. defines.markAsUnprocessed();
  22044. }
  22045. };
  22046. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  22047. if (useMorphTargets === void 0) { useMorphTargets = false; }
  22048. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  22049. return;
  22050. }
  22051. defines._normals = defines._needNormals;
  22052. defines._uvs = defines._needUVs;
  22053. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  22054. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  22055. defines["TANGENT"] = true;
  22056. }
  22057. if (defines._needUVs) {
  22058. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  22059. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  22060. }
  22061. else {
  22062. defines["UV1"] = false;
  22063. defines["UV2"] = false;
  22064. }
  22065. if (useVertexColor) {
  22066. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  22067. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  22068. }
  22069. if (useBones) {
  22070. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22071. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  22072. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  22073. }
  22074. else {
  22075. defines["NUM_BONE_INFLUENCERS"] = 0;
  22076. defines["BonesPerMesh"] = 0;
  22077. }
  22078. }
  22079. if (useMorphTargets) {
  22080. if (mesh.morphTargetManager) {
  22081. var manager = mesh.morphTargetManager;
  22082. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  22083. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  22084. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  22085. }
  22086. else {
  22087. defines["MORPHTARGETS_NORMAL"] = false;
  22088. defines["MORPHTARGETS"] = false;
  22089. defines["NUM_MORPH_INFLUENCERS"] = 0;
  22090. }
  22091. }
  22092. };
  22093. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  22094. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22095. if (disableLighting === void 0) { disableLighting = false; }
  22096. if (!defines._areLightsDirty) {
  22097. return defines._needNormals;
  22098. }
  22099. var lightIndex = 0;
  22100. var needNormals = false;
  22101. var needRebuild = false;
  22102. var lightmapMode = false;
  22103. var shadowEnabled = false;
  22104. var specularEnabled = false;
  22105. if (scene.lightsEnabled && !disableLighting) {
  22106. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22107. var light = _a[_i];
  22108. needNormals = true;
  22109. if (defines["LIGHT" + lightIndex] === undefined) {
  22110. needRebuild = true;
  22111. }
  22112. defines["LIGHT" + lightIndex] = true;
  22113. defines["SPOTLIGHT" + lightIndex] = false;
  22114. defines["HEMILIGHT" + lightIndex] = false;
  22115. defines["POINTLIGHT" + lightIndex] = false;
  22116. defines["DIRLIGHT" + lightIndex] = false;
  22117. var type;
  22118. if (light.getTypeID() === 2) {
  22119. type = "SPOTLIGHT" + lightIndex;
  22120. }
  22121. else if (light.getTypeID() === 3) {
  22122. type = "HEMILIGHT" + lightIndex;
  22123. }
  22124. else if (light.getTypeID() === 0) {
  22125. type = "POINTLIGHT" + lightIndex;
  22126. }
  22127. else {
  22128. type = "DIRLIGHT" + lightIndex;
  22129. }
  22130. defines[type] = true;
  22131. // Specular
  22132. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  22133. specularEnabled = true;
  22134. }
  22135. // Shadows
  22136. defines["SHADOW" + lightIndex] = false;
  22137. if (scene.shadowsEnabled) {
  22138. var shadowGenerator = light.getShadowGenerator();
  22139. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22140. defines["SHADOW" + lightIndex] = true;
  22141. shadowEnabled = true;
  22142. defines["SHADOWPCF" + lightIndex] = false;
  22143. defines["SHADOWESM" + lightIndex] = false;
  22144. if (shadowGenerator.usePoissonSampling) {
  22145. defines["SHADOWPCF" + lightIndex] = true;
  22146. }
  22147. else if (shadowGenerator.useExponentialShadowMap || shadowGenerator.useBlurExponentialShadowMap) {
  22148. defines["SHADOWESM" + lightIndex] = true;
  22149. }
  22150. }
  22151. }
  22152. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  22153. lightmapMode = true;
  22154. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  22155. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  22156. }
  22157. else {
  22158. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  22159. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  22160. }
  22161. lightIndex++;
  22162. if (lightIndex === maxSimultaneousLights)
  22163. break;
  22164. }
  22165. }
  22166. defines["SPECULARTERM"] = specularEnabled;
  22167. defines["SHADOWS"] = shadowEnabled;
  22168. // Resetting all other lights if any
  22169. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  22170. if (defines["LIGHT" + index] !== undefined) {
  22171. defines["LIGHT" + index] = false;
  22172. }
  22173. }
  22174. var caps = scene.getEngine().getCaps();
  22175. if (defines["SHADOWFULLFLOAT"] === undefined) {
  22176. needRebuild = true;
  22177. }
  22178. defines["SHADOWFULLFLOAT"] = (shadowEnabled && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  22179. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  22180. if (needRebuild) {
  22181. defines.rebuild();
  22182. }
  22183. return needNormals;
  22184. };
  22185. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  22186. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22187. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22188. if (!defines["LIGHT" + lightIndex]) {
  22189. break;
  22190. }
  22191. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22192. samplersList.push("shadowSampler" + lightIndex);
  22193. }
  22194. if (defines["NUM_MORPH_INFLUENCERS"]) {
  22195. uniformsList.push("morphTargetInfluences");
  22196. }
  22197. };
  22198. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22199. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22200. if (!defines["SHADOWS"]) {
  22201. return;
  22202. }
  22203. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22204. if (!defines["LIGHT" + lightIndex]) {
  22205. break;
  22206. }
  22207. if (lightIndex > 0) {
  22208. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22209. }
  22210. if (defines["SHADOW" + lightIndex]) {
  22211. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22212. }
  22213. if (defines["SHADOWPCF" + lightIndex]) {
  22214. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22215. }
  22216. if (defines["SHADOWESM" + lightIndex]) {
  22217. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  22218. }
  22219. }
  22220. };
  22221. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  22222. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  22223. if (influencers > 0) {
  22224. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  22225. var manager = mesh.morphTargetManager;
  22226. var normal = manager.supportsNormals && defines["NORMAL"];
  22227. for (var index = 0; index < influencers; index++) {
  22228. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  22229. if (normal) {
  22230. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  22231. }
  22232. if (attribs.length > maxAttributesCount) {
  22233. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  22234. }
  22235. }
  22236. }
  22237. };
  22238. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22239. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22240. fallbacks.addCPUSkinningFallback(0, mesh);
  22241. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22242. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22243. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22244. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22245. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22246. }
  22247. }
  22248. };
  22249. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22250. if (defines["INSTANCES"]) {
  22251. attribs.push("world0");
  22252. attribs.push("world1");
  22253. attribs.push("world2");
  22254. attribs.push("world3");
  22255. }
  22256. };
  22257. // Bindings
  22258. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22259. var shadowGenerator = light.getShadowGenerator();
  22260. if (mesh.receiveShadows && shadowGenerator) {
  22261. if (!light.needCube()) {
  22262. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22263. }
  22264. else {
  22265. if (!depthValuesAlreadySet) {
  22266. depthValuesAlreadySet = true;
  22267. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22268. }
  22269. }
  22270. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22271. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.depthScale);
  22272. }
  22273. return depthValuesAlreadySet;
  22274. };
  22275. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22276. if (light.getTypeID() === 0) {
  22277. // Point Light
  22278. light.transferToEffect(effect, "vLightData" + lightIndex);
  22279. }
  22280. else if (light.getTypeID() === 1) {
  22281. // Directional Light
  22282. light.transferToEffect(effect, "vLightData" + lightIndex);
  22283. }
  22284. else if (light.getTypeID() === 2) {
  22285. // Spot Light
  22286. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  22287. }
  22288. else if (light.getTypeID() === 3) {
  22289. // Hemispheric Light
  22290. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  22291. }
  22292. };
  22293. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  22294. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22295. var lightIndex = 0;
  22296. var depthValuesAlreadySet = false;
  22297. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22298. var light = _a[_i];
  22299. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22300. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22301. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  22302. if (defines["SPECULARTERM"]) {
  22303. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22304. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  22305. }
  22306. // Shadows
  22307. if (scene.shadowsEnabled) {
  22308. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22309. }
  22310. lightIndex++;
  22311. if (lightIndex === maxSimultaneousLights)
  22312. break;
  22313. }
  22314. };
  22315. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22316. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22317. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22318. effect.setColor3("vFogColor", scene.fogColor);
  22319. }
  22320. };
  22321. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22322. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22323. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  22324. if (matrices) {
  22325. effect.setMatrices("mBones", matrices);
  22326. }
  22327. }
  22328. };
  22329. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  22330. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  22331. return;
  22332. }
  22333. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  22334. };
  22335. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22336. if (defines["LOGARITHMICDEPTH"]) {
  22337. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22338. }
  22339. };
  22340. MaterialHelper.BindClipPlane = function (effect, scene) {
  22341. if (scene.clipPlane) {
  22342. var clipPlane = scene.clipPlane;
  22343. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22344. }
  22345. };
  22346. return MaterialHelper;
  22347. }());
  22348. BABYLON.MaterialHelper = MaterialHelper;
  22349. })(BABYLON || (BABYLON = {}));
  22350. //# sourceMappingURL=babylon.materialHelper.js.map
  22351. var BABYLON;
  22352. (function (BABYLON) {
  22353. var MaterialDefines = (function () {
  22354. function MaterialDefines() {
  22355. this._isDirty = true;
  22356. this._areLightsDirty = true;
  22357. this._areAttributesDirty = true;
  22358. this._areTexturesDirty = true;
  22359. this._areFresnelDirty = true;
  22360. this._areMiscDirty = true;
  22361. this._normals = false;
  22362. this._uvs = false;
  22363. this._needNormals = false;
  22364. this._needUVs = false;
  22365. }
  22366. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  22367. get: function () {
  22368. return this._isDirty;
  22369. },
  22370. enumerable: true,
  22371. configurable: true
  22372. });
  22373. MaterialDefines.prototype.markAsProcessed = function () {
  22374. this._isDirty = false;
  22375. this._areAttributesDirty = false;
  22376. this._areTexturesDirty = false;
  22377. this._areFresnelDirty = false;
  22378. this._areLightsDirty = false;
  22379. this._areMiscDirty = false;
  22380. };
  22381. MaterialDefines.prototype.markAsUnprocessed = function () {
  22382. this._isDirty = true;
  22383. };
  22384. MaterialDefines.prototype.markAllAsDirty = function () {
  22385. this._areTexturesDirty = true;
  22386. this._areAttributesDirty = true;
  22387. this._areLightsDirty = true;
  22388. this._areFresnelDirty = true;
  22389. this._areMiscDirty = true;
  22390. this._isDirty = true;
  22391. };
  22392. MaterialDefines.prototype.markAsLightDirty = function () {
  22393. this._areLightsDirty = true;
  22394. this._isDirty = true;
  22395. };
  22396. MaterialDefines.prototype.markAsAttributesDirty = function () {
  22397. this._areAttributesDirty = true;
  22398. this._isDirty = true;
  22399. };
  22400. MaterialDefines.prototype.markAsTexturesDirty = function () {
  22401. this._areTexturesDirty = true;
  22402. this._isDirty = true;
  22403. };
  22404. MaterialDefines.prototype.markAsFresnelDirty = function () {
  22405. this._areFresnelDirty = true;
  22406. this._isDirty = true;
  22407. };
  22408. MaterialDefines.prototype.markAsMiscDirty = function () {
  22409. this._areMiscDirty = true;
  22410. this._isDirty = true;
  22411. };
  22412. MaterialDefines.prototype.rebuild = function () {
  22413. if (this._keys) {
  22414. delete this._keys;
  22415. }
  22416. this._keys = [];
  22417. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  22418. var key = _a[_i];
  22419. if (key[0] === "_") {
  22420. continue;
  22421. }
  22422. this._keys.push(key);
  22423. }
  22424. };
  22425. MaterialDefines.prototype.isEqual = function (other) {
  22426. if (this._keys.length !== other._keys.length) {
  22427. return false;
  22428. }
  22429. for (var index = 0; index < this._keys.length; index++) {
  22430. var prop = this._keys[index];
  22431. if (this[prop] !== other[prop]) {
  22432. return false;
  22433. }
  22434. }
  22435. return true;
  22436. };
  22437. MaterialDefines.prototype.cloneTo = function (other) {
  22438. if (this._keys.length !== other._keys.length) {
  22439. other._keys = this._keys.slice(0);
  22440. }
  22441. for (var index = 0; index < this._keys.length; index++) {
  22442. var prop = this._keys[index];
  22443. other[prop] = this[prop];
  22444. }
  22445. };
  22446. MaterialDefines.prototype.reset = function () {
  22447. for (var index = 0; index < this._keys.length; index++) {
  22448. var prop = this._keys[index];
  22449. if (typeof (this[prop]) === "number") {
  22450. this[prop] = 0;
  22451. }
  22452. else {
  22453. this[prop] = false;
  22454. }
  22455. }
  22456. };
  22457. MaterialDefines.prototype.toString = function () {
  22458. var result = "";
  22459. for (var index = 0; index < this._keys.length; index++) {
  22460. var prop = this._keys[index];
  22461. var value = this[prop];
  22462. if (typeof (value) === "number") {
  22463. result += "#define " + prop + " " + this[prop] + "\n";
  22464. }
  22465. else if (value) {
  22466. result += "#define " + prop + "\n";
  22467. }
  22468. }
  22469. return result;
  22470. };
  22471. return MaterialDefines;
  22472. }());
  22473. BABYLON.MaterialDefines = MaterialDefines;
  22474. var Material = (function () {
  22475. function Material(name, scene, doNotAdd) {
  22476. this.checkReadyOnEveryCall = false;
  22477. this.checkReadyOnlyOnce = false;
  22478. this.state = "";
  22479. this.alpha = 1.0;
  22480. this._backFaceCulling = true;
  22481. this.doNotSerialize = false;
  22482. this.storeEffectOnSubMeshes = false;
  22483. /**
  22484. * An event triggered when the material is disposed.
  22485. * @type {BABYLON.Observable}
  22486. */
  22487. this.onDisposeObservable = new BABYLON.Observable();
  22488. /**
  22489. * An event triggered when the material is bound.
  22490. * @type {BABYLON.Observable}
  22491. */
  22492. this.onBindObservable = new BABYLON.Observable();
  22493. /**
  22494. * An event triggered when the material is unbound.
  22495. * @type {BABYLON.Observable}
  22496. */
  22497. this.onUnBindObservable = new BABYLON.Observable();
  22498. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22499. this.disableDepthWrite = false;
  22500. this._fogEnabled = true;
  22501. this.pointSize = 1.0;
  22502. this.zOffset = 0;
  22503. this._wasPreviouslyReady = false;
  22504. this._fillMode = Material.TriangleFillMode;
  22505. this.name = name;
  22506. this.id = name;
  22507. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22508. if (this._scene.useRightHandedSystem) {
  22509. this.sideOrientation = Material.ClockWiseSideOrientation;
  22510. }
  22511. else {
  22512. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22513. }
  22514. if (!doNotAdd) {
  22515. this._scene.materials.push(this);
  22516. }
  22517. }
  22518. Object.defineProperty(Material, "TriangleFillMode", {
  22519. get: function () {
  22520. return Material._TriangleFillMode;
  22521. },
  22522. enumerable: true,
  22523. configurable: true
  22524. });
  22525. Object.defineProperty(Material, "WireFrameFillMode", {
  22526. get: function () {
  22527. return Material._WireFrameFillMode;
  22528. },
  22529. enumerable: true,
  22530. configurable: true
  22531. });
  22532. Object.defineProperty(Material, "PointFillMode", {
  22533. get: function () {
  22534. return Material._PointFillMode;
  22535. },
  22536. enumerable: true,
  22537. configurable: true
  22538. });
  22539. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22540. get: function () {
  22541. return Material._ClockWiseSideOrientation;
  22542. },
  22543. enumerable: true,
  22544. configurable: true
  22545. });
  22546. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22547. get: function () {
  22548. return Material._CounterClockWiseSideOrientation;
  22549. },
  22550. enumerable: true,
  22551. configurable: true
  22552. });
  22553. Object.defineProperty(Material, "TextureDirtyFlag", {
  22554. get: function () {
  22555. return Material._TextureDirtyFlag;
  22556. },
  22557. enumerable: true,
  22558. configurable: true
  22559. });
  22560. Object.defineProperty(Material, "LightDirtyFlag", {
  22561. get: function () {
  22562. return Material._LightDirtyFlag;
  22563. },
  22564. enumerable: true,
  22565. configurable: true
  22566. });
  22567. Object.defineProperty(Material, "FresnelDirtyFlag", {
  22568. get: function () {
  22569. return Material._FresnelDirtyFlag;
  22570. },
  22571. enumerable: true,
  22572. configurable: true
  22573. });
  22574. Object.defineProperty(Material, "AttributesDirtyFlag", {
  22575. get: function () {
  22576. return Material._AttributesDirtyFlag;
  22577. },
  22578. enumerable: true,
  22579. configurable: true
  22580. });
  22581. Object.defineProperty(Material, "MiscDirtyFlag", {
  22582. get: function () {
  22583. return Material._MiscDirtyFlag;
  22584. },
  22585. enumerable: true,
  22586. configurable: true
  22587. });
  22588. Object.defineProperty(Material.prototype, "backFaceCulling", {
  22589. get: function () {
  22590. return this._backFaceCulling;
  22591. },
  22592. set: function (value) {
  22593. if (this._backFaceCulling === value) {
  22594. return;
  22595. }
  22596. this._backFaceCulling = value;
  22597. this.markAsDirty(Material.TextureDirtyFlag);
  22598. },
  22599. enumerable: true,
  22600. configurable: true
  22601. });
  22602. Object.defineProperty(Material.prototype, "onDispose", {
  22603. set: function (callback) {
  22604. if (this._onDisposeObserver) {
  22605. this.onDisposeObservable.remove(this._onDisposeObserver);
  22606. }
  22607. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22608. },
  22609. enumerable: true,
  22610. configurable: true
  22611. });
  22612. Object.defineProperty(Material.prototype, "onBind", {
  22613. set: function (callback) {
  22614. if (this._onBindObserver) {
  22615. this.onBindObservable.remove(this._onBindObserver);
  22616. }
  22617. this._onBindObserver = this.onBindObservable.add(callback);
  22618. },
  22619. enumerable: true,
  22620. configurable: true
  22621. });
  22622. Object.defineProperty(Material.prototype, "fogEnabled", {
  22623. get: function () {
  22624. return this._fogEnabled;
  22625. },
  22626. set: function (value) {
  22627. if (this._fogEnabled === value) {
  22628. return;
  22629. }
  22630. this._fogEnabled = value;
  22631. this.markAsDirty(Material.MiscDirtyFlag);
  22632. },
  22633. enumerable: true,
  22634. configurable: true
  22635. });
  22636. Object.defineProperty(Material.prototype, "wireframe", {
  22637. get: function () {
  22638. return this._fillMode === Material.WireFrameFillMode;
  22639. },
  22640. set: function (value) {
  22641. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22642. },
  22643. enumerable: true,
  22644. configurable: true
  22645. });
  22646. Object.defineProperty(Material.prototype, "pointsCloud", {
  22647. get: function () {
  22648. return this._fillMode === Material.PointFillMode;
  22649. },
  22650. set: function (value) {
  22651. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22652. },
  22653. enumerable: true,
  22654. configurable: true
  22655. });
  22656. Object.defineProperty(Material.prototype, "fillMode", {
  22657. get: function () {
  22658. return this._fillMode;
  22659. },
  22660. set: function (value) {
  22661. if (this._fillMode === value) {
  22662. return;
  22663. }
  22664. this._fillMode = value;
  22665. this.markAsDirty(Material.MiscDirtyFlag);
  22666. },
  22667. enumerable: true,
  22668. configurable: true
  22669. });
  22670. /**
  22671. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22672. * subclasses should override adding information pertainent to themselves
  22673. */
  22674. Material.prototype.toString = function (fullDetails) {
  22675. var ret = "Name: " + this.name;
  22676. if (fullDetails) {
  22677. }
  22678. return ret;
  22679. };
  22680. /**
  22681. * Child classes can use it to update shaders
  22682. */
  22683. Material.prototype.markAsDirty = function (flag) {
  22684. };
  22685. Material.prototype.getClassName = function () {
  22686. return "Material";
  22687. };
  22688. Object.defineProperty(Material.prototype, "isFrozen", {
  22689. get: function () {
  22690. return this.checkReadyOnlyOnce;
  22691. },
  22692. enumerable: true,
  22693. configurable: true
  22694. });
  22695. Material.prototype.freeze = function () {
  22696. this.checkReadyOnlyOnce = true;
  22697. };
  22698. Material.prototype.unfreeze = function () {
  22699. this.checkReadyOnlyOnce = false;
  22700. };
  22701. Material.prototype.isReady = function (mesh, useInstances) {
  22702. return true;
  22703. };
  22704. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  22705. return false;
  22706. };
  22707. Material.prototype.getEffect = function () {
  22708. return this._effect;
  22709. };
  22710. Material.prototype.getScene = function () {
  22711. return this._scene;
  22712. };
  22713. Material.prototype.needAlphaBlending = function () {
  22714. return (this.alpha < 1.0);
  22715. };
  22716. Material.prototype.needAlphaTesting = function () {
  22717. return false;
  22718. };
  22719. Material.prototype.getAlphaTestTexture = function () {
  22720. return null;
  22721. };
  22722. Material.prototype.markDirty = function () {
  22723. this._wasPreviouslyReady = false;
  22724. };
  22725. Material.prototype._preBind = function (effect) {
  22726. var engine = this._scene.getEngine();
  22727. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  22728. engine.enableEffect(effect ? effect : this._effect);
  22729. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  22730. };
  22731. Material.prototype.bind = function (world, mesh) {
  22732. };
  22733. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  22734. };
  22735. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22736. };
  22737. Material.prototype._afterBind = function (mesh) {
  22738. this._scene._cachedMaterial = this;
  22739. this.onBindObservable.notifyObservers(mesh);
  22740. if (this.disableDepthWrite) {
  22741. var engine = this._scene.getEngine();
  22742. this._cachedDepthWriteState = engine.getDepthWrite();
  22743. engine.setDepthWrite(false);
  22744. }
  22745. };
  22746. Material.prototype.unbind = function () {
  22747. this.onUnBindObservable.notifyObservers(this);
  22748. if (this.disableDepthWrite) {
  22749. var engine = this._scene.getEngine();
  22750. engine.setDepthWrite(this._cachedDepthWriteState);
  22751. }
  22752. };
  22753. Material.prototype.clone = function (name) {
  22754. return null;
  22755. };
  22756. Material.prototype.getBindedMeshes = function () {
  22757. var result = new Array();
  22758. for (var index = 0; index < this._scene.meshes.length; index++) {
  22759. var mesh = this._scene.meshes[index];
  22760. if (mesh.material === this) {
  22761. result.push(mesh);
  22762. }
  22763. }
  22764. return result;
  22765. };
  22766. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  22767. // Animations
  22768. this.getScene().stopAnimation(this);
  22769. // Remove from scene
  22770. var index = this._scene.materials.indexOf(this);
  22771. if (index >= 0) {
  22772. this._scene.materials.splice(index, 1);
  22773. }
  22774. // Remove from meshes
  22775. for (index = 0; index < this._scene.meshes.length; index++) {
  22776. var mesh = this._scene.meshes[index];
  22777. if (mesh.material === this) {
  22778. mesh.material = null;
  22779. if (mesh.geometry) {
  22780. var geometry = mesh.geometry;
  22781. if (this.storeEffectOnSubMeshes) {
  22782. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  22783. var subMesh = _a[_i];
  22784. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  22785. }
  22786. }
  22787. else {
  22788. geometry._releaseVertexArrayObject(this._effect);
  22789. }
  22790. }
  22791. }
  22792. }
  22793. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22794. if (forceDisposeEffect && this._effect) {
  22795. if (this.storeEffectOnSubMeshes) {
  22796. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22797. var subMesh = _c[_b];
  22798. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  22799. }
  22800. }
  22801. else {
  22802. this._scene.getEngine()._releaseEffect(this._effect);
  22803. }
  22804. this._effect = null;
  22805. }
  22806. // Callback
  22807. this.onDisposeObservable.notifyObservers(this);
  22808. this.onDisposeObservable.clear();
  22809. this.onBindObservable.clear();
  22810. this.onUnBindObservable.clear();
  22811. };
  22812. Material.prototype.serialize = function () {
  22813. return BABYLON.SerializationHelper.Serialize(this);
  22814. };
  22815. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22816. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22817. multiMaterial.id = parsedMultiMaterial.id;
  22818. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22819. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22820. var subMatId = parsedMultiMaterial.materials[matIndex];
  22821. if (subMatId) {
  22822. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22823. }
  22824. else {
  22825. multiMaterial.subMaterials.push(null);
  22826. }
  22827. }
  22828. return multiMaterial;
  22829. };
  22830. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  22831. if (!parsedMaterial.customType) {
  22832. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  22833. }
  22834. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  22835. return materialType.Parse(parsedMaterial, scene, rootUrl);
  22836. ;
  22837. };
  22838. return Material;
  22839. }());
  22840. Material._TriangleFillMode = 0;
  22841. Material._WireFrameFillMode = 1;
  22842. Material._PointFillMode = 2;
  22843. Material._ClockWiseSideOrientation = 0;
  22844. Material._CounterClockWiseSideOrientation = 1;
  22845. Material._TextureDirtyFlag = 0;
  22846. Material._LightDirtyFlag = 1;
  22847. Material._FresnelDirtyFlag = 2;
  22848. Material._AttributesDirtyFlag = 4;
  22849. Material._MiscDirtyFlag = 8;
  22850. __decorate([
  22851. BABYLON.serialize()
  22852. ], Material.prototype, "id", void 0);
  22853. __decorate([
  22854. BABYLON.serialize()
  22855. ], Material.prototype, "name", void 0);
  22856. __decorate([
  22857. BABYLON.serialize()
  22858. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  22859. __decorate([
  22860. BABYLON.serialize()
  22861. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  22862. __decorate([
  22863. BABYLON.serialize()
  22864. ], Material.prototype, "state", void 0);
  22865. __decorate([
  22866. BABYLON.serialize()
  22867. ], Material.prototype, "alpha", void 0);
  22868. __decorate([
  22869. BABYLON.serialize("backFaceCulling")
  22870. ], Material.prototype, "_backFaceCulling", void 0);
  22871. __decorate([
  22872. BABYLON.serialize()
  22873. ], Material.prototype, "sideOrientation", void 0);
  22874. __decorate([
  22875. BABYLON.serialize()
  22876. ], Material.prototype, "alphaMode", void 0);
  22877. __decorate([
  22878. BABYLON.serialize()
  22879. ], Material.prototype, "disableDepthWrite", void 0);
  22880. __decorate([
  22881. BABYLON.serialize("fogEnabled")
  22882. ], Material.prototype, "_fogEnabled", void 0);
  22883. __decorate([
  22884. BABYLON.serialize()
  22885. ], Material.prototype, "pointSize", void 0);
  22886. __decorate([
  22887. BABYLON.serialize()
  22888. ], Material.prototype, "zOffset", void 0);
  22889. __decorate([
  22890. BABYLON.serialize()
  22891. ], Material.prototype, "wireframe", null);
  22892. __decorate([
  22893. BABYLON.serialize()
  22894. ], Material.prototype, "pointsCloud", null);
  22895. __decorate([
  22896. BABYLON.serialize()
  22897. ], Material.prototype, "fillMode", null);
  22898. BABYLON.Material = Material;
  22899. })(BABYLON || (BABYLON = {}));
  22900. //# sourceMappingURL=babylon.material.js.map
  22901. var BABYLON;
  22902. (function (BABYLON) {
  22903. var PushMaterial = (function (_super) {
  22904. __extends(PushMaterial, _super);
  22905. function PushMaterial(name, scene) {
  22906. var _this = _super.call(this, name, scene) || this;
  22907. _this.storeEffectOnSubMeshes = true;
  22908. return _this;
  22909. }
  22910. PushMaterial.prototype.getEffect = function () {
  22911. return this._activeEffect;
  22912. };
  22913. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  22914. if (!mesh) {
  22915. return false;
  22916. }
  22917. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22918. return true;
  22919. }
  22920. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  22921. };
  22922. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  22923. this._activeEffect.setMatrix("world", world);
  22924. };
  22925. PushMaterial.prototype.bind = function (world, mesh) {
  22926. if (!mesh) {
  22927. return;
  22928. }
  22929. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  22930. };
  22931. PushMaterial.prototype._afterBind = function (mesh, effect) {
  22932. _super.prototype._afterBind.call(this, mesh);
  22933. this.getScene()._cachedEffect = effect;
  22934. };
  22935. PushMaterial.prototype._mustRebind = function (scene, effect) {
  22936. return scene.getCachedEffect() !== effect || scene.getCachedMaterial() !== this;
  22937. };
  22938. PushMaterial.prototype.markAsDirty = function (flag) {
  22939. if (flag & BABYLON.Material.TextureDirtyFlag) {
  22940. this._markAllSubMeshesAsTexturesDirty();
  22941. }
  22942. if (flag & BABYLON.Material.LightDirtyFlag) {
  22943. this._markAllSubMeshesAsLightsDirty();
  22944. }
  22945. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  22946. this._markAllSubMeshesAsFresnelDirty();
  22947. }
  22948. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  22949. this._markAllSubMeshesAsAttributesDirty();
  22950. }
  22951. if (flag & BABYLON.Material.MiscDirtyFlag) {
  22952. this._markAllSubMeshesAsMiscDirty();
  22953. }
  22954. };
  22955. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  22956. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22957. var mesh = _a[_i];
  22958. if (!mesh.subMeshes) {
  22959. continue;
  22960. }
  22961. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22962. var subMesh = _c[_b];
  22963. if (subMesh.getMaterial() !== this) {
  22964. continue;
  22965. }
  22966. if (!subMesh._materialDefines) {
  22967. return;
  22968. }
  22969. func(subMesh._materialDefines);
  22970. }
  22971. }
  22972. };
  22973. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  22974. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  22975. };
  22976. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  22977. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  22978. };
  22979. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  22980. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  22981. };
  22982. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  22983. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  22984. };
  22985. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  22986. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  22987. };
  22988. return PushMaterial;
  22989. }(BABYLON.Material));
  22990. BABYLON.PushMaterial = PushMaterial;
  22991. })(BABYLON || (BABYLON = {}));
  22992. //# sourceMappingURL=babylon.pushMaterial.js.map
  22993. var BABYLON;
  22994. (function (BABYLON) {
  22995. var VertexData = (function () {
  22996. function VertexData() {
  22997. }
  22998. VertexData.prototype.set = function (data, kind) {
  22999. switch (kind) {
  23000. case BABYLON.VertexBuffer.PositionKind:
  23001. this.positions = data;
  23002. break;
  23003. case BABYLON.VertexBuffer.NormalKind:
  23004. this.normals = data;
  23005. break;
  23006. case BABYLON.VertexBuffer.TangentKind:
  23007. this.tangents = data;
  23008. break;
  23009. case BABYLON.VertexBuffer.UVKind:
  23010. this.uvs = data;
  23011. break;
  23012. case BABYLON.VertexBuffer.UV2Kind:
  23013. this.uvs2 = data;
  23014. break;
  23015. case BABYLON.VertexBuffer.UV3Kind:
  23016. this.uvs3 = data;
  23017. break;
  23018. case BABYLON.VertexBuffer.UV4Kind:
  23019. this.uvs4 = data;
  23020. break;
  23021. case BABYLON.VertexBuffer.UV5Kind:
  23022. this.uvs5 = data;
  23023. break;
  23024. case BABYLON.VertexBuffer.UV6Kind:
  23025. this.uvs6 = data;
  23026. break;
  23027. case BABYLON.VertexBuffer.ColorKind:
  23028. this.colors = data;
  23029. break;
  23030. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23031. this.matricesIndices = data;
  23032. break;
  23033. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23034. this.matricesWeights = data;
  23035. break;
  23036. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23037. this.matricesIndicesExtra = data;
  23038. break;
  23039. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23040. this.matricesWeightsExtra = data;
  23041. break;
  23042. }
  23043. };
  23044. /**
  23045. * Associates the vertexData to the passed Mesh.
  23046. * Sets it as updatable or not (default `false`).
  23047. * Returns the VertexData.
  23048. */
  23049. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23050. this._applyTo(mesh, updatable);
  23051. return this;
  23052. };
  23053. /**
  23054. * Associates the vertexData to the passed Geometry.
  23055. * Sets it as updatable or not (default `false`).
  23056. * Returns the VertexData.
  23057. */
  23058. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23059. this._applyTo(geometry, updatable);
  23060. return this;
  23061. };
  23062. /**
  23063. * Updates the associated mesh.
  23064. * Returns the VertexData.
  23065. */
  23066. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23067. this._update(mesh);
  23068. return this;
  23069. };
  23070. /**
  23071. * Updates the associated geometry.
  23072. * Returns the VertexData.
  23073. */
  23074. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23075. this._update(geometry);
  23076. return this;
  23077. };
  23078. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23079. if (this.positions) {
  23080. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23081. }
  23082. if (this.normals) {
  23083. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23084. }
  23085. if (this.tangents) {
  23086. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  23087. }
  23088. if (this.uvs) {
  23089. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23090. }
  23091. if (this.uvs2) {
  23092. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23093. }
  23094. if (this.uvs3) {
  23095. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23096. }
  23097. if (this.uvs4) {
  23098. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23099. }
  23100. if (this.uvs5) {
  23101. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23102. }
  23103. if (this.uvs6) {
  23104. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23105. }
  23106. if (this.colors) {
  23107. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23108. }
  23109. if (this.matricesIndices) {
  23110. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23111. }
  23112. if (this.matricesWeights) {
  23113. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23114. }
  23115. if (this.matricesIndicesExtra) {
  23116. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23117. }
  23118. if (this.matricesWeightsExtra) {
  23119. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23120. }
  23121. if (this.indices) {
  23122. meshOrGeometry.setIndices(this.indices);
  23123. }
  23124. return this;
  23125. };
  23126. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23127. if (this.positions) {
  23128. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23129. }
  23130. if (this.normals) {
  23131. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23132. }
  23133. if (this.tangents) {
  23134. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  23135. }
  23136. if (this.uvs) {
  23137. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23138. }
  23139. if (this.uvs2) {
  23140. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23141. }
  23142. if (this.uvs3) {
  23143. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23144. }
  23145. if (this.uvs4) {
  23146. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23147. }
  23148. if (this.uvs5) {
  23149. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23150. }
  23151. if (this.uvs6) {
  23152. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23153. }
  23154. if (this.colors) {
  23155. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23156. }
  23157. if (this.matricesIndices) {
  23158. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23159. }
  23160. if (this.matricesWeights) {
  23161. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23162. }
  23163. if (this.matricesIndicesExtra) {
  23164. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23165. }
  23166. if (this.matricesWeightsExtra) {
  23167. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23168. }
  23169. if (this.indices) {
  23170. meshOrGeometry.setIndices(this.indices);
  23171. }
  23172. return this;
  23173. };
  23174. /**
  23175. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  23176. * Returns the VertexData.
  23177. */
  23178. VertexData.prototype.transform = function (matrix) {
  23179. var transformed = BABYLON.Vector3.Zero();
  23180. var index;
  23181. if (this.positions) {
  23182. var position = BABYLON.Vector3.Zero();
  23183. for (index = 0; index < this.positions.length; index += 3) {
  23184. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23185. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23186. this.positions[index] = transformed.x;
  23187. this.positions[index + 1] = transformed.y;
  23188. this.positions[index + 2] = transformed.z;
  23189. }
  23190. }
  23191. if (this.normals) {
  23192. var normal = BABYLON.Vector3.Zero();
  23193. for (index = 0; index < this.normals.length; index += 3) {
  23194. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23195. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23196. this.normals[index] = transformed.x;
  23197. this.normals[index + 1] = transformed.y;
  23198. this.normals[index + 2] = transformed.z;
  23199. }
  23200. }
  23201. if (this.tangents) {
  23202. var tangent = BABYLON.Vector4.Zero();
  23203. var tangentTransformed = BABYLON.Vector4.Zero();
  23204. for (index = 0; index < this.tangents.length; index += 4) {
  23205. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  23206. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  23207. this.tangents[index] = tangentTransformed.x;
  23208. this.tangents[index + 1] = tangentTransformed.y;
  23209. this.tangents[index + 2] = tangentTransformed.z;
  23210. this.tangents[index + 3] = tangentTransformed.w;
  23211. }
  23212. }
  23213. return this;
  23214. };
  23215. /**
  23216. * Merges the passed VertexData into the current one.
  23217. * Returns the modified VertexData.
  23218. */
  23219. VertexData.prototype.merge = function (other) {
  23220. if (other.indices) {
  23221. if (!this.indices) {
  23222. this.indices = [];
  23223. }
  23224. var offset = this.positions ? this.positions.length / 3 : 0;
  23225. for (var index = 0; index < other.indices.length; index++) {
  23226. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  23227. this.indices.push(other.indices[index] + offset);
  23228. }
  23229. }
  23230. this.positions = this._mergeElement(this.positions, other.positions);
  23231. this.normals = this._mergeElement(this.normals, other.normals);
  23232. this.tangents = this._mergeElement(this.tangents, other.tangents);
  23233. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23234. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23235. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23236. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23237. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23238. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23239. this.colors = this._mergeElement(this.colors, other.colors);
  23240. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23241. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23242. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23243. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23244. return this;
  23245. };
  23246. VertexData.prototype._mergeElement = function (source, other) {
  23247. if (!other)
  23248. return source;
  23249. if (!source)
  23250. return other;
  23251. var len = other.length + source.length;
  23252. var isSrcTypedArray = source instanceof Float32Array;
  23253. var isOthTypedArray = other instanceof Float32Array;
  23254. // use non-loop method when the source is Float32Array
  23255. if (isSrcTypedArray) {
  23256. var ret32 = new Float32Array(len);
  23257. ret32.set(source);
  23258. ret32.set(other, source.length);
  23259. return ret32;
  23260. // source is number[], when other is also use concat
  23261. }
  23262. else if (!isOthTypedArray) {
  23263. return source.concat(other);
  23264. // source is a number[], but other is a Float32Array, loop required
  23265. }
  23266. else {
  23267. var ret = source.slice(0); // copy source to a separate array
  23268. for (var i = 0, len = other.length; i < len; i++) {
  23269. ret.push(other[i]);
  23270. }
  23271. return ret;
  23272. }
  23273. };
  23274. /**
  23275. * Serializes the VertexData.
  23276. * Returns a serialized object.
  23277. */
  23278. VertexData.prototype.serialize = function () {
  23279. var serializationObject = this.serialize();
  23280. if (this.positions) {
  23281. serializationObject.positions = this.positions;
  23282. }
  23283. if (this.normals) {
  23284. serializationObject.normals = this.normals;
  23285. }
  23286. if (this.tangents) {
  23287. serializationObject.tangents = this.tangents;
  23288. }
  23289. if (this.uvs) {
  23290. serializationObject.uvs = this.uvs;
  23291. }
  23292. if (this.uvs2) {
  23293. serializationObject.uvs2 = this.uvs2;
  23294. }
  23295. if (this.uvs3) {
  23296. serializationObject.uvs3 = this.uvs3;
  23297. }
  23298. if (this.uvs4) {
  23299. serializationObject.uvs4 = this.uvs4;
  23300. }
  23301. if (this.uvs5) {
  23302. serializationObject.uvs5 = this.uvs5;
  23303. }
  23304. if (this.uvs6) {
  23305. serializationObject.uvs6 = this.uvs6;
  23306. }
  23307. if (this.colors) {
  23308. serializationObject.colors = this.colors;
  23309. }
  23310. if (this.matricesIndices) {
  23311. serializationObject.matricesIndices = this.matricesIndices;
  23312. serializationObject.matricesIndices._isExpanded = true;
  23313. }
  23314. if (this.matricesWeights) {
  23315. serializationObject.matricesWeights = this.matricesWeights;
  23316. }
  23317. if (this.matricesIndicesExtra) {
  23318. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23319. serializationObject.matricesIndicesExtra._isExpanded = true;
  23320. }
  23321. if (this.matricesWeightsExtra) {
  23322. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23323. }
  23324. serializationObject.indices = this.indices;
  23325. return serializationObject;
  23326. };
  23327. // Statics
  23328. /**
  23329. * Returns the object VertexData associated to the passed mesh.
  23330. */
  23331. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23332. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23333. };
  23334. /**
  23335. * Returns the object VertexData associated to the passed geometry.
  23336. */
  23337. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23338. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23339. };
  23340. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23341. var result = new VertexData();
  23342. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23343. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23344. }
  23345. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23346. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23347. }
  23348. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23349. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared);
  23350. }
  23351. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23352. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23353. }
  23354. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23355. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23356. }
  23357. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23358. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23359. }
  23360. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23361. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23362. }
  23363. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23364. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23365. }
  23366. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23367. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23368. }
  23369. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23370. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23371. }
  23372. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23373. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23374. }
  23375. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23376. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23377. }
  23378. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23379. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23380. }
  23381. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23382. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23383. }
  23384. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23385. return result;
  23386. };
  23387. /**
  23388. * Creates the vertexData of the Ribbon.
  23389. */
  23390. VertexData.CreateRibbon = function (options) {
  23391. var pathArray = options.pathArray;
  23392. var closeArray = options.closeArray || false;
  23393. var closePath = options.closePath || false;
  23394. var invertUV = options.invertUV || false;
  23395. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23396. var offset = options.offset || defaultOffset;
  23397. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23398. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23399. var customUV = options.uvs;
  23400. var customColors = options.colors;
  23401. var positions = [];
  23402. var indices = [];
  23403. var normals = [];
  23404. var uvs = [];
  23405. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23406. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23407. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23408. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23409. var minlg; // minimal length among all paths from pathArray
  23410. var lg = []; // array of path lengths : nb of vertex per path
  23411. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23412. var p; // path iterator
  23413. var i; // point iterator
  23414. var j; // point iterator
  23415. // if single path in pathArray
  23416. if (pathArray.length < 2) {
  23417. var ar1 = [];
  23418. var ar2 = [];
  23419. for (i = 0; i < pathArray[0].length - offset; i++) {
  23420. ar1.push(pathArray[0][i]);
  23421. ar2.push(pathArray[0][i + offset]);
  23422. }
  23423. pathArray = [ar1, ar2];
  23424. }
  23425. // positions and horizontal distances (u)
  23426. var idc = 0;
  23427. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  23428. var path;
  23429. var l;
  23430. minlg = pathArray[0].length;
  23431. var vectlg;
  23432. var dist;
  23433. for (p = 0; p < pathArray.length; p++) {
  23434. uTotalDistance[p] = 0;
  23435. us[p] = [0];
  23436. path = pathArray[p];
  23437. l = path.length;
  23438. minlg = (minlg < l) ? minlg : l;
  23439. j = 0;
  23440. while (j < l) {
  23441. positions.push(path[j].x, path[j].y, path[j].z);
  23442. if (j > 0) {
  23443. vectlg = path[j].subtract(path[j - 1]).length();
  23444. dist = vectlg + uTotalDistance[p];
  23445. us[p].push(dist);
  23446. uTotalDistance[p] = dist;
  23447. }
  23448. j++;
  23449. }
  23450. if (closePath) {
  23451. j--;
  23452. positions.push(path[0].x, path[0].y, path[0].z);
  23453. vectlg = path[j].subtract(path[0]).length();
  23454. dist = vectlg + uTotalDistance[p];
  23455. us[p].push(dist);
  23456. uTotalDistance[p] = dist;
  23457. }
  23458. lg[p] = l + closePathCorr;
  23459. idx[p] = idc;
  23460. idc += (l + closePathCorr);
  23461. }
  23462. // vertical distances (v)
  23463. var path1;
  23464. var path2;
  23465. var vertex1;
  23466. var vertex2;
  23467. for (i = 0; i < minlg + closePathCorr; i++) {
  23468. vTotalDistance[i] = 0;
  23469. vs[i] = [0];
  23470. for (p = 0; p < pathArray.length - 1; p++) {
  23471. path1 = pathArray[p];
  23472. path2 = pathArray[p + 1];
  23473. if (i === minlg) {
  23474. vertex1 = path1[0];
  23475. vertex2 = path2[0];
  23476. }
  23477. else {
  23478. vertex1 = path1[i];
  23479. vertex2 = path2[i];
  23480. }
  23481. vectlg = vertex2.subtract(vertex1).length();
  23482. dist = vectlg + vTotalDistance[i];
  23483. vs[i].push(dist);
  23484. vTotalDistance[i] = dist;
  23485. }
  23486. if (closeArray) {
  23487. path1 = pathArray[p];
  23488. path2 = pathArray[0];
  23489. if (i === minlg) {
  23490. vertex2 = path2[0];
  23491. }
  23492. vectlg = vertex2.subtract(vertex1).length();
  23493. dist = vectlg + vTotalDistance[i];
  23494. vTotalDistance[i] = dist;
  23495. }
  23496. }
  23497. // uvs
  23498. var u;
  23499. var v;
  23500. if (customUV) {
  23501. for (p = 0; p < customUV.length; p++) {
  23502. uvs.push(customUV[p].x, customUV[p].y);
  23503. }
  23504. }
  23505. else {
  23506. for (p = 0; p < pathArray.length; p++) {
  23507. for (i = 0; i < minlg + closePathCorr; i++) {
  23508. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  23509. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  23510. if (invertUV) {
  23511. uvs.push(v, u);
  23512. }
  23513. else {
  23514. uvs.push(u, v);
  23515. }
  23516. }
  23517. }
  23518. }
  23519. // indices
  23520. p = 0; // path index
  23521. var pi = 0; // positions array index
  23522. var l1 = lg[p] - 1; // path1 length
  23523. var l2 = lg[p + 1] - 1; // path2 length
  23524. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23525. var shft = idx[1] - idx[0]; // shift
  23526. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23527. while (pi <= min && p < path1nb) {
  23528. // 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
  23529. indices.push(pi, pi + shft, pi + 1);
  23530. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23531. pi += 1;
  23532. if (pi === min) {
  23533. p++;
  23534. if (p === lg.length - 1) {
  23535. shft = idx[0] - idx[p];
  23536. l1 = lg[p] - 1;
  23537. l2 = lg[0] - 1;
  23538. }
  23539. else {
  23540. shft = idx[p + 1] - idx[p];
  23541. l1 = lg[p] - 1;
  23542. l2 = lg[p + 1] - 1;
  23543. }
  23544. pi = idx[p];
  23545. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23546. }
  23547. }
  23548. // normals
  23549. VertexData.ComputeNormals(positions, indices, normals);
  23550. if (closePath) {
  23551. var indexFirst = 0;
  23552. var indexLast = 0;
  23553. for (p = 0; p < pathArray.length; p++) {
  23554. indexFirst = idx[p] * 3;
  23555. if (p + 1 < pathArray.length) {
  23556. indexLast = (idx[p + 1] - 1) * 3;
  23557. }
  23558. else {
  23559. indexLast = normals.length - 3;
  23560. }
  23561. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23562. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23563. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23564. normals[indexLast] = normals[indexFirst];
  23565. normals[indexLast + 1] = normals[indexFirst + 1];
  23566. normals[indexLast + 2] = normals[indexFirst + 2];
  23567. }
  23568. }
  23569. // sides
  23570. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23571. // Colors
  23572. if (customColors) {
  23573. var colors = new Float32Array(customColors.length * 4);
  23574. for (var c = 0; c < customColors.length; c++) {
  23575. colors[c * 4] = customColors[c].r;
  23576. colors[c * 4 + 1] = customColors[c].g;
  23577. colors[c * 4 + 2] = customColors[c].b;
  23578. colors[c * 4 + 3] = customColors[c].a;
  23579. }
  23580. }
  23581. // Result
  23582. var vertexData = new VertexData();
  23583. var positions32 = new Float32Array(positions);
  23584. var normals32 = new Float32Array(normals);
  23585. var uvs32 = new Float32Array(uvs);
  23586. vertexData.indices = indices;
  23587. vertexData.positions = positions32;
  23588. vertexData.normals = normals32;
  23589. vertexData.uvs = uvs32;
  23590. if (customColors) {
  23591. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  23592. }
  23593. if (closePath) {
  23594. vertexData._idx = idx;
  23595. }
  23596. return vertexData;
  23597. };
  23598. /**
  23599. * Creates the VertexData of the Box.
  23600. */
  23601. VertexData.CreateBox = function (options) {
  23602. var normalsSource = [
  23603. new BABYLON.Vector3(0, 0, 1),
  23604. new BABYLON.Vector3(0, 0, -1),
  23605. new BABYLON.Vector3(1, 0, 0),
  23606. new BABYLON.Vector3(-1, 0, 0),
  23607. new BABYLON.Vector3(0, 1, 0),
  23608. new BABYLON.Vector3(0, -1, 0)
  23609. ];
  23610. var indices = [];
  23611. var positions = [];
  23612. var normals = [];
  23613. var uvs = [];
  23614. var width = options.width || options.size || 1;
  23615. var height = options.height || options.size || 1;
  23616. var depth = options.depth || options.size || 1;
  23617. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23618. var faceUV = options.faceUV || new Array(6);
  23619. var faceColors = options.faceColors;
  23620. var colors = [];
  23621. // default face colors and UV if undefined
  23622. for (var f = 0; f < 6; f++) {
  23623. if (faceUV[f] === undefined) {
  23624. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23625. }
  23626. if (faceColors && faceColors[f] === undefined) {
  23627. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23628. }
  23629. }
  23630. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23631. // Create each face in turn.
  23632. for (var index = 0; index < normalsSource.length; index++) {
  23633. var normal = normalsSource[index];
  23634. // Get two vectors perpendicular to the face normal and to each other.
  23635. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23636. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23637. // Six indices (two triangles) per face.
  23638. var verticesLength = positions.length / 3;
  23639. indices.push(verticesLength);
  23640. indices.push(verticesLength + 1);
  23641. indices.push(verticesLength + 2);
  23642. indices.push(verticesLength);
  23643. indices.push(verticesLength + 2);
  23644. indices.push(verticesLength + 3);
  23645. // Four vertices per face.
  23646. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23647. positions.push(vertex.x, vertex.y, vertex.z);
  23648. normals.push(normal.x, normal.y, normal.z);
  23649. uvs.push(faceUV[index].z, faceUV[index].w);
  23650. if (faceColors) {
  23651. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23652. }
  23653. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23654. positions.push(vertex.x, vertex.y, vertex.z);
  23655. normals.push(normal.x, normal.y, normal.z);
  23656. uvs.push(faceUV[index].x, faceUV[index].w);
  23657. if (faceColors) {
  23658. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23659. }
  23660. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23661. positions.push(vertex.x, vertex.y, vertex.z);
  23662. normals.push(normal.x, normal.y, normal.z);
  23663. uvs.push(faceUV[index].x, faceUV[index].y);
  23664. if (faceColors) {
  23665. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23666. }
  23667. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23668. positions.push(vertex.x, vertex.y, vertex.z);
  23669. normals.push(normal.x, normal.y, normal.z);
  23670. uvs.push(faceUV[index].z, faceUV[index].y);
  23671. if (faceColors) {
  23672. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23673. }
  23674. }
  23675. // sides
  23676. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23677. // Result
  23678. var vertexData = new VertexData();
  23679. vertexData.indices = indices;
  23680. vertexData.positions = positions;
  23681. vertexData.normals = normals;
  23682. vertexData.uvs = uvs;
  23683. if (faceColors) {
  23684. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23685. vertexData.colors = totalColors;
  23686. }
  23687. return vertexData;
  23688. };
  23689. /**
  23690. * Creates the VertexData of the Sphere.
  23691. */
  23692. VertexData.CreateSphere = function (options) {
  23693. var segments = options.segments || 32;
  23694. var diameterX = options.diameterX || options.diameter || 1;
  23695. var diameterY = options.diameterY || options.diameter || 1;
  23696. var diameterZ = options.diameterZ || options.diameter || 1;
  23697. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23698. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23699. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23700. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23701. var totalZRotationSteps = 2 + segments;
  23702. var totalYRotationSteps = 2 * totalZRotationSteps;
  23703. var indices = [];
  23704. var positions = [];
  23705. var normals = [];
  23706. var uvs = [];
  23707. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23708. var normalizedZ = zRotationStep / totalZRotationSteps;
  23709. var angleZ = normalizedZ * Math.PI * slice;
  23710. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23711. var normalizedY = yRotationStep / totalYRotationSteps;
  23712. var angleY = normalizedY * Math.PI * 2 * arc;
  23713. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23714. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23715. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23716. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23717. var vertex = complete.multiply(radius);
  23718. var normal = complete.divide(radius).normalize();
  23719. positions.push(vertex.x, vertex.y, vertex.z);
  23720. normals.push(normal.x, normal.y, normal.z);
  23721. uvs.push(normalizedY, normalizedZ);
  23722. }
  23723. if (zRotationStep > 0) {
  23724. var verticesCount = positions.length / 3;
  23725. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23726. indices.push((firstIndex));
  23727. indices.push((firstIndex + 1));
  23728. indices.push(firstIndex + totalYRotationSteps + 1);
  23729. indices.push((firstIndex + totalYRotationSteps + 1));
  23730. indices.push((firstIndex + 1));
  23731. indices.push((firstIndex + totalYRotationSteps + 2));
  23732. }
  23733. }
  23734. }
  23735. // Sides
  23736. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23737. // Result
  23738. var vertexData = new VertexData();
  23739. vertexData.indices = indices;
  23740. vertexData.positions = positions;
  23741. vertexData.normals = normals;
  23742. vertexData.uvs = uvs;
  23743. return vertexData;
  23744. };
  23745. /**
  23746. * Creates the VertexData of the Cylinder or Cone.
  23747. */
  23748. VertexData.CreateCylinder = function (options) {
  23749. var height = options.height || 2;
  23750. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23751. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  23752. var tessellation = options.tessellation || 24;
  23753. var subdivisions = options.subdivisions || 1;
  23754. var hasRings = options.hasRings;
  23755. var enclose = options.enclose;
  23756. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23757. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23758. var faceUV = options.faceUV || new Array(3);
  23759. var faceColors = options.faceColors;
  23760. // default face colors and UV if undefined
  23761. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23762. var ringNb = (hasRings) ? subdivisions : 1;
  23763. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23764. var f;
  23765. for (f = 0; f < surfaceNb; f++) {
  23766. if (faceColors && faceColors[f] === undefined) {
  23767. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23768. }
  23769. }
  23770. for (f = 0; f < surfaceNb; f++) {
  23771. if (faceUV && faceUV[f] === undefined) {
  23772. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23773. }
  23774. }
  23775. var indices = [];
  23776. var positions = [];
  23777. var normals = [];
  23778. var uvs = [];
  23779. var colors = [];
  23780. var angle_step = Math.PI * 2 * arc / tessellation;
  23781. var angle;
  23782. var h;
  23783. var radius;
  23784. var tan = (diameterBottom - diameterTop) / 2 / height;
  23785. var ringVertex = BABYLON.Vector3.Zero();
  23786. var ringNormal = BABYLON.Vector3.Zero();
  23787. var ringFirstVertex = BABYLON.Vector3.Zero();
  23788. var ringFirstNormal = BABYLON.Vector3.Zero();
  23789. var quadNormal = BABYLON.Vector3.Zero();
  23790. var Y = BABYLON.Axis.Y;
  23791. // positions, normals, uvs
  23792. var i;
  23793. var j;
  23794. var r;
  23795. var ringIdx = 1;
  23796. var s = 1; // surface index
  23797. var cs = 0;
  23798. var v = 0;
  23799. for (i = 0; i <= subdivisions; i++) {
  23800. h = i / subdivisions;
  23801. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23802. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23803. for (r = 0; r < ringIdx; r++) {
  23804. if (hasRings) {
  23805. s += r;
  23806. }
  23807. if (enclose) {
  23808. s += 2 * r;
  23809. }
  23810. for (j = 0; j <= tessellation; j++) {
  23811. angle = j * angle_step;
  23812. // position
  23813. ringVertex.x = Math.cos(-angle) * radius;
  23814. ringVertex.y = -height / 2 + h * height;
  23815. ringVertex.z = Math.sin(-angle) * radius;
  23816. // normal
  23817. if (diameterTop === 0 && i === subdivisions) {
  23818. // if no top cap, reuse former normals
  23819. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23820. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23821. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23822. }
  23823. else {
  23824. ringNormal.x = ringVertex.x;
  23825. ringNormal.z = ringVertex.z;
  23826. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23827. ringNormal.normalize();
  23828. }
  23829. // keep first ring vertex values for enclose
  23830. if (j === 0) {
  23831. ringFirstVertex.copyFrom(ringVertex);
  23832. ringFirstNormal.copyFrom(ringNormal);
  23833. }
  23834. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23835. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23836. if (hasRings) {
  23837. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23838. }
  23839. else {
  23840. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23841. }
  23842. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23843. if (faceColors) {
  23844. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23845. }
  23846. }
  23847. // if enclose, add four vertices and their dedicated normals
  23848. if (arc !== 1 && enclose) {
  23849. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23850. positions.push(0, ringVertex.y, 0);
  23851. positions.push(0, ringVertex.y, 0);
  23852. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23853. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23854. quadNormal.normalize();
  23855. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23856. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23857. quadNormal.normalize();
  23858. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23859. if (hasRings) {
  23860. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23861. }
  23862. else {
  23863. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23864. }
  23865. uvs.push(faceUV[s + 1].x, v);
  23866. uvs.push(faceUV[s + 1].z, v);
  23867. if (hasRings) {
  23868. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23869. }
  23870. else {
  23871. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23872. }
  23873. uvs.push(faceUV[s + 2].x, v);
  23874. uvs.push(faceUV[s + 2].z, v);
  23875. if (faceColors) {
  23876. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23877. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23878. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23879. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23880. }
  23881. }
  23882. if (cs !== s) {
  23883. cs = s;
  23884. }
  23885. }
  23886. }
  23887. // indices
  23888. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23889. var s;
  23890. i = 0;
  23891. for (s = 0; s < subdivisions; s++) {
  23892. for (j = 0; j < tessellation; j++) {
  23893. var i0 = i * (e + 1) + j;
  23894. var i1 = (i + 1) * (e + 1) + j;
  23895. var i2 = i * (e + 1) + (j + 1);
  23896. var i3 = (i + 1) * (e + 1) + (j + 1);
  23897. indices.push(i0, i1, i2);
  23898. indices.push(i3, i2, i1);
  23899. }
  23900. if (arc !== 1 && enclose) {
  23901. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23902. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23903. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23904. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23905. }
  23906. i = (hasRings) ? (i + 2) : (i + 1);
  23907. }
  23908. // Caps
  23909. var createCylinderCap = function (isTop) {
  23910. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23911. if (radius === 0) {
  23912. return;
  23913. }
  23914. // Cap positions, normals & uvs
  23915. var angle;
  23916. var circleVector;
  23917. var i;
  23918. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23919. var c;
  23920. if (faceColors) {
  23921. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23922. }
  23923. // cap center
  23924. var vbase = positions.length / 3;
  23925. var offset = isTop ? height / 2 : -height / 2;
  23926. var center = new BABYLON.Vector3(0, offset, 0);
  23927. positions.push(center.x, center.y, center.z);
  23928. normals.push(0, isTop ? 1 : -1, 0);
  23929. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23930. if (faceColors) {
  23931. colors.push(c.r, c.g, c.b, c.a);
  23932. }
  23933. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23934. for (i = 0; i <= tessellation; i++) {
  23935. angle = Math.PI * 2 * i * arc / tessellation;
  23936. var cos = Math.cos(-angle);
  23937. var sin = Math.sin(-angle);
  23938. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23939. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23940. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23941. normals.push(0, isTop ? 1 : -1, 0);
  23942. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23943. if (faceColors) {
  23944. colors.push(c.r, c.g, c.b, c.a);
  23945. }
  23946. }
  23947. // Cap indices
  23948. for (i = 0; i < tessellation; i++) {
  23949. if (!isTop) {
  23950. indices.push(vbase);
  23951. indices.push(vbase + (i + 1));
  23952. indices.push(vbase + (i + 2));
  23953. }
  23954. else {
  23955. indices.push(vbase);
  23956. indices.push(vbase + (i + 2));
  23957. indices.push(vbase + (i + 1));
  23958. }
  23959. }
  23960. };
  23961. // add caps to geometry
  23962. createCylinderCap(false);
  23963. createCylinderCap(true);
  23964. // Sides
  23965. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23966. var vertexData = new VertexData();
  23967. vertexData.indices = indices;
  23968. vertexData.positions = positions;
  23969. vertexData.normals = normals;
  23970. vertexData.uvs = uvs;
  23971. if (faceColors) {
  23972. vertexData.colors = colors;
  23973. }
  23974. return vertexData;
  23975. };
  23976. /**
  23977. * Creates the VertexData of the Torus.
  23978. */
  23979. VertexData.CreateTorus = function (options) {
  23980. var indices = [];
  23981. var positions = [];
  23982. var normals = [];
  23983. var uvs = [];
  23984. var diameter = options.diameter || 1;
  23985. var thickness = options.thickness || 0.5;
  23986. var tessellation = options.tessellation || 16;
  23987. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23988. var stride = tessellation + 1;
  23989. for (var i = 0; i <= tessellation; i++) {
  23990. var u = i / tessellation;
  23991. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23992. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23993. for (var j = 0; j <= tessellation; j++) {
  23994. var v = 1 - j / tessellation;
  23995. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23996. var dx = Math.cos(innerAngle);
  23997. var dy = Math.sin(innerAngle);
  23998. // Create a vertex.
  23999. var normal = new BABYLON.Vector3(dx, dy, 0);
  24000. var position = normal.scale(thickness / 2);
  24001. var textureCoordinate = new BABYLON.Vector2(u, v);
  24002. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24003. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24004. positions.push(position.x, position.y, position.z);
  24005. normals.push(normal.x, normal.y, normal.z);
  24006. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24007. // And create indices for two triangles.
  24008. var nextI = (i + 1) % stride;
  24009. var nextJ = (j + 1) % stride;
  24010. indices.push(i * stride + j);
  24011. indices.push(i * stride + nextJ);
  24012. indices.push(nextI * stride + j);
  24013. indices.push(i * stride + nextJ);
  24014. indices.push(nextI * stride + nextJ);
  24015. indices.push(nextI * stride + j);
  24016. }
  24017. }
  24018. // Sides
  24019. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24020. // Result
  24021. var vertexData = new VertexData();
  24022. vertexData.indices = indices;
  24023. vertexData.positions = positions;
  24024. vertexData.normals = normals;
  24025. vertexData.uvs = uvs;
  24026. return vertexData;
  24027. };
  24028. /**
  24029. * Creates the VertexData of the LineSystem.
  24030. */
  24031. VertexData.CreateLineSystem = function (options) {
  24032. var indices = [];
  24033. var positions = [];
  24034. var lines = options.lines;
  24035. var idx = 0;
  24036. for (var l = 0; l < lines.length; l++) {
  24037. var points = lines[l];
  24038. for (var index = 0; index < points.length; index++) {
  24039. positions.push(points[index].x, points[index].y, points[index].z);
  24040. if (index > 0) {
  24041. indices.push(idx - 1);
  24042. indices.push(idx);
  24043. }
  24044. idx++;
  24045. }
  24046. }
  24047. var vertexData = new VertexData();
  24048. vertexData.indices = indices;
  24049. vertexData.positions = positions;
  24050. return vertexData;
  24051. };
  24052. /**
  24053. * Create the VertexData of the DashedLines.
  24054. */
  24055. VertexData.CreateDashedLines = function (options) {
  24056. var dashSize = options.dashSize || 3;
  24057. var gapSize = options.gapSize || 1;
  24058. var dashNb = options.dashNb || 200;
  24059. var points = options.points;
  24060. var positions = new Array();
  24061. var indices = new Array();
  24062. var curvect = BABYLON.Vector3.Zero();
  24063. var lg = 0;
  24064. var nb = 0;
  24065. var shft = 0;
  24066. var dashshft = 0;
  24067. var curshft = 0;
  24068. var idx = 0;
  24069. var i = 0;
  24070. for (i = 0; i < points.length - 1; i++) {
  24071. points[i + 1].subtractToRef(points[i], curvect);
  24072. lg += curvect.length();
  24073. }
  24074. shft = lg / dashNb;
  24075. dashshft = dashSize * shft / (dashSize + gapSize);
  24076. for (i = 0; i < points.length - 1; i++) {
  24077. points[i + 1].subtractToRef(points[i], curvect);
  24078. nb = Math.floor(curvect.length() / shft);
  24079. curvect.normalize();
  24080. for (var j = 0; j < nb; j++) {
  24081. curshft = shft * j;
  24082. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24083. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24084. indices.push(idx, idx + 1);
  24085. idx += 2;
  24086. }
  24087. }
  24088. // Result
  24089. var vertexData = new VertexData();
  24090. vertexData.positions = positions;
  24091. vertexData.indices = indices;
  24092. return vertexData;
  24093. };
  24094. /**
  24095. * Creates the VertexData of the Ground.
  24096. */
  24097. VertexData.CreateGround = function (options) {
  24098. var indices = [];
  24099. var positions = [];
  24100. var normals = [];
  24101. var uvs = [];
  24102. var row, col;
  24103. var width = options.width || 1;
  24104. var height = options.height || 1;
  24105. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  24106. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  24107. for (row = 0; row <= subdivisionsY; row++) {
  24108. for (col = 0; col <= subdivisionsX; col++) {
  24109. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  24110. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24111. positions.push(position.x, position.y, position.z);
  24112. normals.push(normal.x, normal.y, normal.z);
  24113. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  24114. }
  24115. }
  24116. for (row = 0; row < subdivisionsY; row++) {
  24117. for (col = 0; col < subdivisionsX; col++) {
  24118. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24119. indices.push(col + 1 + row * (subdivisionsX + 1));
  24120. indices.push(col + row * (subdivisionsX + 1));
  24121. indices.push(col + (row + 1) * (subdivisionsX + 1));
  24122. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24123. indices.push(col + row * (subdivisionsX + 1));
  24124. }
  24125. }
  24126. // Result
  24127. var vertexData = new VertexData();
  24128. vertexData.indices = indices;
  24129. vertexData.positions = positions;
  24130. vertexData.normals = normals;
  24131. vertexData.uvs = uvs;
  24132. return vertexData;
  24133. };
  24134. /**
  24135. * Creates the VertexData of the TiledGround.
  24136. */
  24137. VertexData.CreateTiledGround = function (options) {
  24138. var xmin = options.xmin || -1.0;
  24139. var zmin = options.zmin || -1.0;
  24140. var xmax = options.xmax || 1.0;
  24141. var zmax = options.zmax || 1.0;
  24142. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24143. var precision = options.precision || { w: 1, h: 1 };
  24144. var indices = [];
  24145. var positions = [];
  24146. var normals = [];
  24147. var uvs = [];
  24148. var row, col, tileRow, tileCol;
  24149. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  24150. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24151. precision.w = (precision.w < 1) ? 1 : precision.w;
  24152. precision.h = (precision.h < 1) ? 1 : precision.h;
  24153. var tileSize = {
  24154. 'w': (xmax - xmin) / subdivisions.w,
  24155. 'h': (zmax - zmin) / subdivisions.h
  24156. };
  24157. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24158. // Indices
  24159. var base = positions.length / 3;
  24160. var rowLength = precision.w + 1;
  24161. for (row = 0; row < precision.h; row++) {
  24162. for (col = 0; col < precision.w; col++) {
  24163. var square = [
  24164. base + col + row * rowLength,
  24165. base + (col + 1) + row * rowLength,
  24166. base + (col + 1) + (row + 1) * rowLength,
  24167. base + col + (row + 1) * rowLength
  24168. ];
  24169. indices.push(square[1]);
  24170. indices.push(square[2]);
  24171. indices.push(square[3]);
  24172. indices.push(square[0]);
  24173. indices.push(square[1]);
  24174. indices.push(square[3]);
  24175. }
  24176. }
  24177. // Position, normals and uvs
  24178. var position = BABYLON.Vector3.Zero();
  24179. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24180. for (row = 0; row <= precision.h; row++) {
  24181. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24182. for (col = 0; col <= precision.w; col++) {
  24183. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24184. position.y = 0;
  24185. positions.push(position.x, position.y, position.z);
  24186. normals.push(normal.x, normal.y, normal.z);
  24187. uvs.push(col / precision.w, row / precision.h);
  24188. }
  24189. }
  24190. }
  24191. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24192. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24193. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24194. }
  24195. }
  24196. // Result
  24197. var vertexData = new VertexData();
  24198. vertexData.indices = indices;
  24199. vertexData.positions = positions;
  24200. vertexData.normals = normals;
  24201. vertexData.uvs = uvs;
  24202. return vertexData;
  24203. };
  24204. /**
  24205. * Creates the VertexData of the Ground designed from a heightmap.
  24206. */
  24207. VertexData.CreateGroundFromHeightMap = function (options) {
  24208. var indices = [];
  24209. var positions = [];
  24210. var normals = [];
  24211. var uvs = [];
  24212. var row, col;
  24213. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  24214. // Vertices
  24215. for (row = 0; row <= options.subdivisions; row++) {
  24216. for (col = 0; col <= options.subdivisions; col++) {
  24217. 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));
  24218. // Compute height
  24219. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24220. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24221. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24222. var r = options.buffer[pos] / 255.0;
  24223. var g = options.buffer[pos + 1] / 255.0;
  24224. var b = options.buffer[pos + 2] / 255.0;
  24225. var gradient = r * filter.r + g * filter.g + b * filter.b;
  24226. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24227. // Add vertex
  24228. positions.push(position.x, position.y, position.z);
  24229. normals.push(0, 0, 0);
  24230. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24231. }
  24232. }
  24233. // Indices
  24234. for (row = 0; row < options.subdivisions; row++) {
  24235. for (col = 0; col < options.subdivisions; col++) {
  24236. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24237. indices.push(col + 1 + row * (options.subdivisions + 1));
  24238. indices.push(col + row * (options.subdivisions + 1));
  24239. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24240. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24241. indices.push(col + row * (options.subdivisions + 1));
  24242. }
  24243. }
  24244. // Normals
  24245. VertexData.ComputeNormals(positions, indices, normals);
  24246. // Result
  24247. var vertexData = new VertexData();
  24248. vertexData.indices = indices;
  24249. vertexData.positions = positions;
  24250. vertexData.normals = normals;
  24251. vertexData.uvs = uvs;
  24252. return vertexData;
  24253. };
  24254. /**
  24255. * Creates the VertexData of the Plane.
  24256. */
  24257. VertexData.CreatePlane = function (options) {
  24258. var indices = [];
  24259. var positions = [];
  24260. var normals = [];
  24261. var uvs = [];
  24262. var width = options.width || options.size || 1;
  24263. var height = options.height || options.size || 1;
  24264. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24265. // Vertices
  24266. var halfWidth = width / 2.0;
  24267. var halfHeight = height / 2.0;
  24268. positions.push(-halfWidth, -halfHeight, 0);
  24269. normals.push(0, 0, -1.0);
  24270. uvs.push(0.0, 0.0);
  24271. positions.push(halfWidth, -halfHeight, 0);
  24272. normals.push(0, 0, -1.0);
  24273. uvs.push(1.0, 0.0);
  24274. positions.push(halfWidth, halfHeight, 0);
  24275. normals.push(0, 0, -1.0);
  24276. uvs.push(1.0, 1.0);
  24277. positions.push(-halfWidth, halfHeight, 0);
  24278. normals.push(0, 0, -1.0);
  24279. uvs.push(0.0, 1.0);
  24280. // Indices
  24281. indices.push(0);
  24282. indices.push(1);
  24283. indices.push(2);
  24284. indices.push(0);
  24285. indices.push(2);
  24286. indices.push(3);
  24287. // Sides
  24288. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24289. // Result
  24290. var vertexData = new VertexData();
  24291. vertexData.indices = indices;
  24292. vertexData.positions = positions;
  24293. vertexData.normals = normals;
  24294. vertexData.uvs = uvs;
  24295. return vertexData;
  24296. };
  24297. /**
  24298. * Creates the VertexData of the Disc or regular Polygon.
  24299. */
  24300. VertexData.CreateDisc = function (options) {
  24301. var positions = [];
  24302. var indices = [];
  24303. var normals = [];
  24304. var uvs = [];
  24305. var radius = options.radius || 0.5;
  24306. var tessellation = options.tessellation || 64;
  24307. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24308. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24309. // positions and uvs
  24310. positions.push(0, 0, 0); // disc center first
  24311. uvs.push(0.5, 0.5);
  24312. var theta = Math.PI * 2 * arc;
  24313. var step = theta / tessellation;
  24314. for (var a = 0; a < theta; a += step) {
  24315. var x = Math.cos(a);
  24316. var y = Math.sin(a);
  24317. var u = (x + 1) / 2;
  24318. var v = (1 - y) / 2;
  24319. positions.push(radius * x, radius * y, 0);
  24320. uvs.push(u, v);
  24321. }
  24322. if (arc === 1) {
  24323. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24324. uvs.push(uvs[2], uvs[3]);
  24325. }
  24326. //indices
  24327. var vertexNb = positions.length / 3;
  24328. for (var i = 1; i < vertexNb - 1; i++) {
  24329. indices.push(i + 1, 0, i);
  24330. }
  24331. // result
  24332. VertexData.ComputeNormals(positions, indices, normals);
  24333. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24334. var vertexData = new VertexData();
  24335. vertexData.indices = indices;
  24336. vertexData.positions = positions;
  24337. vertexData.normals = normals;
  24338. vertexData.uvs = uvs;
  24339. return vertexData;
  24340. };
  24341. /**
  24342. * Creates the VertexData of the IcoSphere.
  24343. */
  24344. VertexData.CreateIcoSphere = function (options) {
  24345. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24346. var radius = options.radius || 1;
  24347. var flat = (options.flat === undefined) ? true : options.flat;
  24348. var subdivisions = options.subdivisions || 4;
  24349. var radiusX = options.radiusX || radius;
  24350. var radiusY = options.radiusY || radius;
  24351. var radiusZ = options.radiusZ || radius;
  24352. var t = (1 + Math.sqrt(5)) / 2;
  24353. // 12 vertex x,y,z
  24354. var ico_vertices = [
  24355. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24356. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24357. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24358. ];
  24359. // index of 3 vertex makes a face of icopshere
  24360. var ico_indices = [
  24361. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24362. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24363. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24364. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24365. ];
  24366. // vertex for uv have aliased position, not for UV
  24367. var vertices_unalias_id = [
  24368. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24369. // vertex alias
  24370. 0,
  24371. 2,
  24372. 3,
  24373. 3,
  24374. 3,
  24375. 4,
  24376. 7,
  24377. 8,
  24378. 9,
  24379. 9,
  24380. 10,
  24381. 11 // 23: B + 12
  24382. ];
  24383. // uv as integer step (not pixels !)
  24384. var ico_vertexuv = [
  24385. 5, 1, 3, 1, 6, 4, 0, 0,
  24386. 5, 3, 4, 2, 2, 2, 4, 0,
  24387. 2, 0, 1, 1, 6, 0, 6, 2,
  24388. // vertex alias (for same vertex on different faces)
  24389. 0, 4,
  24390. 3, 3,
  24391. 4, 4,
  24392. 3, 1,
  24393. 4, 2,
  24394. 4, 4,
  24395. 0, 2,
  24396. 1, 1,
  24397. 2, 2,
  24398. 3, 3,
  24399. 1, 3,
  24400. 2, 4 // 23: B + 12
  24401. ];
  24402. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24403. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24404. // First island of uv mapping
  24405. // v = 4h 3+ 2
  24406. // v = 3h 9+ 4
  24407. // v = 2h 9+ 5 B
  24408. // v = 1h 9 1 0
  24409. // v = 0h 3 8 7 A
  24410. // u = 0 1 2 3 4 5 6 *a
  24411. // Second island of uv mapping
  24412. // v = 4h 0+ B+ 4+
  24413. // v = 3h A+ 2+
  24414. // v = 2h 7+ 6 3+
  24415. // v = 1h 8+ 3+
  24416. // v = 0h
  24417. // u = 0 1 2 3 4 5 6 *a
  24418. // Face layout on texture UV mapping
  24419. // ============
  24420. // \ 4 /\ 16 / ======
  24421. // \ / \ / /\ 11 /
  24422. // \/ 7 \/ / \ /
  24423. // ======= / 10 \/
  24424. // /\ 17 /\ =======
  24425. // / \ / \ \ 15 /\
  24426. // / 8 \/ 12 \ \ / \
  24427. // ============ \/ 6 \
  24428. // \ 18 /\ ============
  24429. // \ / \ \ 5 /\ 0 /
  24430. // \/ 13 \ \ / \ /
  24431. // ======= \/ 1 \/
  24432. // =============
  24433. // /\ 19 /\ 2 /\
  24434. // / \ / \ / \
  24435. // / 14 \/ 9 \/ 3 \
  24436. // ===================
  24437. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24438. var ustep = 138 / 1024;
  24439. var vstep = 239 / 1024;
  24440. var uoffset = 60 / 1024;
  24441. var voffset = 26 / 1024;
  24442. // Second island should have margin, not to touch the first island
  24443. // avoid any borderline artefact in pixel rounding
  24444. var island_u_offset = -40 / 1024;
  24445. var island_v_offset = +20 / 1024;
  24446. // face is either island 0 or 1 :
  24447. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24448. var island = [
  24449. 0, 0, 0, 0, 1,
  24450. 0, 0, 1, 1, 0,
  24451. 0, 0, 1, 1, 0,
  24452. 0, 1, 1, 1, 0 // 15 - 19
  24453. ];
  24454. var indices = [];
  24455. var positions = [];
  24456. var normals = [];
  24457. var uvs = [];
  24458. var current_indice = 0;
  24459. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24460. var face_vertex_pos = new Array(3);
  24461. var face_vertex_uv = new Array(3);
  24462. var v012;
  24463. for (v012 = 0; v012 < 3; v012++) {
  24464. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24465. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24466. }
  24467. // create all with normals
  24468. for (var face = 0; face < 20; face++) {
  24469. // 3 vertex per face
  24470. for (v012 = 0; v012 < 3; v012++) {
  24471. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  24472. var v_id = ico_indices[3 * face + v012];
  24473. // vertex have 3D position (x,y,z)
  24474. 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]);
  24475. // Normalize to get normal, then scale to radius
  24476. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24477. // uv Coordinates from vertex ID
  24478. 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);
  24479. }
  24480. // Subdivide the face (interpolate pos, norm, uv)
  24481. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24482. // - norm is linear interpolation of vertex corner normal
  24483. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24484. // - uv is linear interpolation
  24485. //
  24486. // Topology is as below for sub-divide by 2
  24487. // vertex shown as v0,v1,v2
  24488. // interp index is i1 to progress in range [v0,v1[
  24489. // interp index is i2 to progress in range [v0,v2[
  24490. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24491. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24492. //
  24493. //
  24494. // i2 v2
  24495. // ^ ^
  24496. // / / \
  24497. // / / \
  24498. // / / \
  24499. // / / (0,1) \
  24500. // / #---------\
  24501. // / / \ (0,0)'/ \
  24502. // / / \ / \
  24503. // / / \ / \
  24504. // / / (0,0) \ / (1,0) \
  24505. // / #---------#---------\
  24506. // v0 v1
  24507. //
  24508. // --------------------> i1
  24509. //
  24510. // interp of (i1,i2):
  24511. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24512. // along i1 : lerp(x0,x1, i1/(S-i2))
  24513. //
  24514. // centroid of triangle is needed to get help normal computation
  24515. // (c1,c2) are used for centroid location
  24516. var interp_vertex = function (i1, i2, c1, c2) {
  24517. // vertex is interpolated from
  24518. // - face_vertex_pos[0..2]
  24519. // - face_vertex_uv[0..2]
  24520. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24521. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24522. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24523. pos_interp.normalize();
  24524. var vertex_normal;
  24525. if (flat) {
  24526. // in flat mode, recalculate normal as face centroid normal
  24527. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24528. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24529. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24530. }
  24531. else {
  24532. // in smooth mode, recalculate normal from each single vertex position
  24533. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  24534. }
  24535. // Vertex normal need correction due to X,Y,Z radius scaling
  24536. vertex_normal.x /= radiusX;
  24537. vertex_normal.y /= radiusY;
  24538. vertex_normal.z /= radiusZ;
  24539. vertex_normal.normalize();
  24540. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24541. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24542. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24543. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  24544. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24545. uvs.push(uv_interp.x, uv_interp.y);
  24546. // push each vertex has member of a face
  24547. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24548. indices.push(current_indice);
  24549. current_indice++;
  24550. };
  24551. for (var i2 = 0; i2 < subdivisions; i2++) {
  24552. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24553. // face : (i1,i2) for /\ :
  24554. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24555. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24556. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24557. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24558. if (i1 + i2 + 1 < subdivisions) {
  24559. // face : (i1,i2)' for \/ :
  24560. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24561. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24562. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24563. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24564. }
  24565. }
  24566. }
  24567. }
  24568. // Sides
  24569. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24570. // Result
  24571. var vertexData = new VertexData();
  24572. vertexData.indices = indices;
  24573. vertexData.positions = positions;
  24574. vertexData.normals = normals;
  24575. vertexData.uvs = uvs;
  24576. return vertexData;
  24577. };
  24578. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24579. /**
  24580. * Creates the VertexData of the Polyhedron.
  24581. */
  24582. VertexData.CreatePolyhedron = function (options) {
  24583. // provided polyhedron types :
  24584. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24585. // 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)
  24586. var polyhedra = [];
  24587. 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]] };
  24588. 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]] };
  24589. polyhedra[2] = {
  24590. 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]],
  24591. 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]]
  24592. };
  24593. polyhedra[3] = {
  24594. 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]],
  24595. 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]]
  24596. };
  24597. polyhedra[4] = {
  24598. 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]],
  24599. 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]]
  24600. };
  24601. 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]] };
  24602. 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]] };
  24603. 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]] };
  24604. 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]] };
  24605. 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]] };
  24606. 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]] };
  24607. 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]] };
  24608. 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]] };
  24609. 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]] };
  24610. polyhedra[14] = {
  24611. 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]],
  24612. 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]]
  24613. };
  24614. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24615. var size = options.size;
  24616. var sizeX = options.sizeX || size || 1;
  24617. var sizeY = options.sizeY || size || 1;
  24618. var sizeZ = options.sizeZ || size || 1;
  24619. var data = options.custom || polyhedra[type];
  24620. var nbfaces = data.face.length;
  24621. var faceUV = options.faceUV || new Array(nbfaces);
  24622. var faceColors = options.faceColors;
  24623. var flat = (options.flat === undefined) ? true : options.flat;
  24624. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24625. var positions = [];
  24626. var indices = [];
  24627. var normals = [];
  24628. var uvs = [];
  24629. var colors = [];
  24630. var index = 0;
  24631. var faceIdx = 0; // face cursor in the array "indexes"
  24632. var indexes = [];
  24633. var i = 0;
  24634. var f = 0;
  24635. var u, v, ang, x, y, tmp;
  24636. // default face colors and UV if undefined
  24637. if (flat) {
  24638. for (f = 0; f < nbfaces; f++) {
  24639. if (faceColors && faceColors[f] === undefined) {
  24640. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24641. }
  24642. if (faceUV && faceUV[f] === undefined) {
  24643. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24644. }
  24645. }
  24646. }
  24647. if (!flat) {
  24648. for (i = 0; i < data.vertex.length; i++) {
  24649. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24650. uvs.push(0, 0);
  24651. }
  24652. for (f = 0; f < nbfaces; f++) {
  24653. for (i = 0; i < data.face[f].length - 2; i++) {
  24654. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24655. }
  24656. }
  24657. }
  24658. else {
  24659. for (f = 0; f < nbfaces; f++) {
  24660. var fl = data.face[f].length; // number of vertices of the current face
  24661. ang = 2 * Math.PI / fl;
  24662. x = 0.5 * Math.tan(ang / 2);
  24663. y = 0.5;
  24664. // positions, uvs, colors
  24665. for (i = 0; i < fl; i++) {
  24666. // positions
  24667. 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);
  24668. indexes.push(index);
  24669. index++;
  24670. // uvs
  24671. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24672. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24673. uvs.push(u, v);
  24674. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24675. y = x * Math.sin(ang) + y * Math.cos(ang);
  24676. x = tmp;
  24677. // colors
  24678. if (faceColors) {
  24679. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24680. }
  24681. }
  24682. // indices from indexes
  24683. for (i = 0; i < fl - 2; i++) {
  24684. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24685. }
  24686. faceIdx += fl;
  24687. }
  24688. }
  24689. VertexData.ComputeNormals(positions, indices, normals);
  24690. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24691. var vertexData = new VertexData();
  24692. vertexData.positions = positions;
  24693. vertexData.indices = indices;
  24694. vertexData.normals = normals;
  24695. vertexData.uvs = uvs;
  24696. if (faceColors && flat) {
  24697. vertexData.colors = colors;
  24698. }
  24699. return vertexData;
  24700. };
  24701. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24702. /**
  24703. * Creates the VertexData of the Torus Knot.
  24704. */
  24705. VertexData.CreateTorusKnot = function (options) {
  24706. var indices = [];
  24707. var positions = [];
  24708. var normals = [];
  24709. var uvs = [];
  24710. var radius = options.radius || 2;
  24711. var tube = options.tube || 0.5;
  24712. var radialSegments = options.radialSegments || 32;
  24713. var tubularSegments = options.tubularSegments || 32;
  24714. var p = options.p || 2;
  24715. var q = options.q || 3;
  24716. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24717. // Helper
  24718. var getPos = function (angle) {
  24719. var cu = Math.cos(angle);
  24720. var su = Math.sin(angle);
  24721. var quOverP = q / p * angle;
  24722. var cs = Math.cos(quOverP);
  24723. var tx = radius * (2 + cs) * 0.5 * cu;
  24724. var ty = radius * (2 + cs) * su * 0.5;
  24725. var tz = radius * Math.sin(quOverP) * 0.5;
  24726. return new BABYLON.Vector3(tx, ty, tz);
  24727. };
  24728. // Vertices
  24729. var i;
  24730. var j;
  24731. for (i = 0; i <= radialSegments; i++) {
  24732. var modI = i % radialSegments;
  24733. var u = modI / radialSegments * 2 * p * Math.PI;
  24734. var p1 = getPos(u);
  24735. var p2 = getPos(u + 0.01);
  24736. var tang = p2.subtract(p1);
  24737. var n = p2.add(p1);
  24738. var bitan = BABYLON.Vector3.Cross(tang, n);
  24739. n = BABYLON.Vector3.Cross(bitan, tang);
  24740. bitan.normalize();
  24741. n.normalize();
  24742. for (j = 0; j < tubularSegments; j++) {
  24743. var modJ = j % tubularSegments;
  24744. var v = modJ / tubularSegments * 2 * Math.PI;
  24745. var cx = -tube * Math.cos(v);
  24746. var cy = tube * Math.sin(v);
  24747. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24748. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24749. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24750. uvs.push(i / radialSegments);
  24751. uvs.push(j / tubularSegments);
  24752. }
  24753. }
  24754. for (i = 0; i < radialSegments; i++) {
  24755. for (j = 0; j < tubularSegments; j++) {
  24756. var jNext = (j + 1) % tubularSegments;
  24757. var a = i * tubularSegments + j;
  24758. var b = (i + 1) * tubularSegments + j;
  24759. var c = (i + 1) * tubularSegments + jNext;
  24760. var d = i * tubularSegments + jNext;
  24761. indices.push(d);
  24762. indices.push(b);
  24763. indices.push(a);
  24764. indices.push(d);
  24765. indices.push(c);
  24766. indices.push(b);
  24767. }
  24768. }
  24769. // Normals
  24770. VertexData.ComputeNormals(positions, indices, normals);
  24771. // Sides
  24772. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24773. // Result
  24774. var vertexData = new VertexData();
  24775. vertexData.indices = indices;
  24776. vertexData.positions = positions;
  24777. vertexData.normals = normals;
  24778. vertexData.uvs = uvs;
  24779. return vertexData;
  24780. };
  24781. // Tools
  24782. /**
  24783. * @param {any} - positions (number[] or Float32Array)
  24784. * @param {any} - indices (number[] or Uint16Array)
  24785. * @param {any} - normals (number[] or Float32Array)
  24786. * options (optional) :
  24787. * facetPositions : optional array of facet positions (vector3)
  24788. * facetNormals : optional array of facet normals (vector3)
  24789. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  24790. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  24791. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  24792. * bbSize : optional bounding box size data, required for facetPartitioning computation
  24793. * bInfo : optional bounding info, required for facetPartitioning computation
  24794. */
  24795. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  24796. // temporary scalar variables
  24797. var index = 0; // facet index
  24798. var p1p2x = 0.0; // p1p2 vector x coordinate
  24799. var p1p2y = 0.0; // p1p2 vector y coordinate
  24800. var p1p2z = 0.0; // p1p2 vector z coordinate
  24801. var p3p2x = 0.0; // p3p2 vector x coordinate
  24802. var p3p2y = 0.0; // p3p2 vector y coordinate
  24803. var p3p2z = 0.0; // p3p2 vector z coordinate
  24804. var faceNormalx = 0.0; // facet normal x coordinate
  24805. var faceNormaly = 0.0; // facet normal y coordinate
  24806. var faceNormalz = 0.0; // facet normal z coordinate
  24807. var length = 0.0; // facet normal length before normalization
  24808. var v1x = 0; // vector1 x index in the positions array
  24809. var v1y = 0; // vector1 y index in the positions array
  24810. var v1z = 0; // vector1 z index in the positions array
  24811. var v2x = 0; // vector2 x index in the positions array
  24812. var v2y = 0; // vector2 y index in the positions array
  24813. var v2z = 0; // vector2 z index in the positions array
  24814. var v3x = 0; // vector3 x index in the positions array
  24815. var v3y = 0; // vector3 y index in the positions array
  24816. var v3z = 0; // vector3 z index in the positions array
  24817. var computeFacetNormals = false;
  24818. var computeFacetPositions = false;
  24819. var computeFacetPartitioning = false;
  24820. if (options) {
  24821. computeFacetNormals = (options.facetNormals) ? true : false;
  24822. computeFacetPositions = (options.facetPositions) ? true : false;
  24823. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  24824. }
  24825. // facetPartitioning reinit if needed
  24826. if (computeFacetPartitioning) {
  24827. var ox = 0; // X partitioning index for facet position
  24828. var oy = 0; // Y partinioning index for facet position
  24829. var oz = 0; // Z partinioning index for facet position
  24830. var b1x = 0; // X partitioning index for facet v1 vertex
  24831. var b1y = 0; // Y partitioning index for facet v1 vertex
  24832. var b1z = 0; // z partitioning index for facet v1 vertex
  24833. var b2x = 0; // X partitioning index for facet v2 vertex
  24834. var b2y = 0; // Y partitioning index for facet v2 vertex
  24835. var b2z = 0; // Z partitioning index for facet v2 vertex
  24836. var b3x = 0; // X partitioning index for facet v3 vertex
  24837. var b3y = 0; // Y partitioning index for facet v3 vertex
  24838. var b3z = 0; // Z partitioning index for facet v3 vertex
  24839. var block_idx_o = 0; // facet barycenter block index
  24840. var block_idx_v1 = 0; // v1 vertex block index
  24841. var block_idx_v2 = 0; // v2 vertex block index
  24842. var block_idx_v3 = 0; // v3 vertex block index
  24843. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  24844. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  24845. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  24846. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  24847. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  24848. var subSq = options.subDiv.max * options.subDiv.max;
  24849. options.facetPartitioning.length = 0;
  24850. }
  24851. // reset the normals
  24852. for (index = 0; index < positions.length; index++) {
  24853. normals[index] = 0.0;
  24854. }
  24855. // Loop : 1 indice triplet = 1 facet
  24856. var nbFaces = indices.length / 3;
  24857. for (index = 0; index < nbFaces; index++) {
  24858. // get the indexes of the coordinates of each vertex of the facet
  24859. v1x = indices[index * 3] * 3;
  24860. v1y = v1x + 1;
  24861. v1z = v1x + 2;
  24862. v2x = indices[index * 3 + 1] * 3;
  24863. v2y = v2x + 1;
  24864. v2z = v2x + 2;
  24865. v3x = indices[index * 3 + 2] * 3;
  24866. v3y = v3x + 1;
  24867. v3z = v3x + 2;
  24868. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  24869. p1p2y = positions[v1y] - positions[v2y];
  24870. p1p2z = positions[v1z] - positions[v2z];
  24871. p3p2x = positions[v3x] - positions[v2x];
  24872. p3p2y = positions[v3y] - positions[v2y];
  24873. p3p2z = positions[v3z] - positions[v2z];
  24874. // compute the face normal with the cross product
  24875. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  24876. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24877. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24878. // normalize this normal and store it in the array facetData
  24879. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24880. length = (length === 0) ? 1.0 : length;
  24881. faceNormalx /= length;
  24882. faceNormaly /= length;
  24883. faceNormalz /= length;
  24884. if (computeFacetNormals) {
  24885. options.facetNormals[index].x = faceNormalx;
  24886. options.facetNormals[index].y = faceNormaly;
  24887. options.facetNormals[index].z = faceNormalz;
  24888. }
  24889. if (computeFacetPositions) {
  24890. // compute and the facet barycenter coordinates in the array facetPositions
  24891. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  24892. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  24893. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  24894. }
  24895. if (computeFacetPartitioning) {
  24896. // store the facet indexes in arrays in the main facetPartitioning array :
  24897. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  24898. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  24899. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  24900. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  24901. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  24902. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  24903. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  24904. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  24905. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  24906. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  24907. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  24908. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  24909. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  24910. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  24911. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  24912. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  24913. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  24914. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  24915. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  24916. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  24917. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  24918. // push each facet index in each block containing the vertex
  24919. options.facetPartitioning[block_idx_v1].push(index);
  24920. if (block_idx_v2 != block_idx_v1) {
  24921. options.facetPartitioning[block_idx_v2].push(index);
  24922. }
  24923. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  24924. options.facetPartitioning[block_idx_v3].push(index);
  24925. }
  24926. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  24927. options.facetPartitioning[block_idx_o].push(index);
  24928. }
  24929. }
  24930. // compute the normals anyway
  24931. normals[v1x] += faceNormalx; // accumulate all the normals per face
  24932. normals[v1y] += faceNormaly;
  24933. normals[v1z] += faceNormalz;
  24934. normals[v2x] += faceNormalx;
  24935. normals[v2y] += faceNormaly;
  24936. normals[v2z] += faceNormalz;
  24937. normals[v3x] += faceNormalx;
  24938. normals[v3y] += faceNormaly;
  24939. normals[v3z] += faceNormalz;
  24940. }
  24941. // last normalization of each normal
  24942. for (index = 0; index < normals.length / 3; index++) {
  24943. faceNormalx = normals[index * 3];
  24944. faceNormaly = normals[index * 3 + 1];
  24945. faceNormalz = normals[index * 3 + 2];
  24946. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24947. length = (length === 0) ? 1.0 : length;
  24948. faceNormalx /= length;
  24949. faceNormaly /= length;
  24950. faceNormalz /= length;
  24951. normals[index * 3] = faceNormalx;
  24952. normals[index * 3 + 1] = faceNormaly;
  24953. normals[index * 3 + 2] = faceNormalz;
  24954. }
  24955. };
  24956. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24957. var li = indices.length;
  24958. var ln = normals.length;
  24959. var i;
  24960. var n;
  24961. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24962. switch (sideOrientation) {
  24963. case BABYLON.Mesh.FRONTSIDE:
  24964. // nothing changed
  24965. break;
  24966. case BABYLON.Mesh.BACKSIDE:
  24967. var tmp;
  24968. // indices
  24969. for (i = 0; i < li; i += 3) {
  24970. tmp = indices[i];
  24971. indices[i] = indices[i + 2];
  24972. indices[i + 2] = tmp;
  24973. }
  24974. // normals
  24975. for (n = 0; n < ln; n++) {
  24976. normals[n] = -normals[n];
  24977. }
  24978. break;
  24979. case BABYLON.Mesh.DOUBLESIDE:
  24980. // positions
  24981. var lp = positions.length;
  24982. var l = lp / 3;
  24983. for (var p = 0; p < lp; p++) {
  24984. positions[lp + p] = positions[p];
  24985. }
  24986. // indices
  24987. for (i = 0; i < li; i += 3) {
  24988. indices[i + li] = indices[i + 2] + l;
  24989. indices[i + 1 + li] = indices[i + 1] + l;
  24990. indices[i + 2 + li] = indices[i] + l;
  24991. }
  24992. // normals
  24993. for (n = 0; n < ln; n++) {
  24994. normals[ln + n] = -normals[n];
  24995. }
  24996. // uvs
  24997. var lu = uvs.length;
  24998. for (var u = 0; u < lu; u++) {
  24999. uvs[u + lu] = uvs[u];
  25000. }
  25001. break;
  25002. }
  25003. };
  25004. /**
  25005. * Creates a new VertexData from the imported parameters.
  25006. */
  25007. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25008. var vertexData = new VertexData();
  25009. // positions
  25010. var positions = parsedVertexData.positions;
  25011. if (positions) {
  25012. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25013. }
  25014. // normals
  25015. var normals = parsedVertexData.normals;
  25016. if (normals) {
  25017. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25018. }
  25019. // tangents
  25020. var tangents = parsedVertexData.tangents;
  25021. if (tangents) {
  25022. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  25023. }
  25024. // uvs
  25025. var uvs = parsedVertexData.uvs;
  25026. if (uvs) {
  25027. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25028. }
  25029. // uv2s
  25030. var uv2s = parsedVertexData.uv2s;
  25031. if (uv2s) {
  25032. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25033. }
  25034. // uv3s
  25035. var uv3s = parsedVertexData.uv3s;
  25036. if (uv3s) {
  25037. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25038. }
  25039. // uv4s
  25040. var uv4s = parsedVertexData.uv4s;
  25041. if (uv4s) {
  25042. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25043. }
  25044. // uv5s
  25045. var uv5s = parsedVertexData.uv5s;
  25046. if (uv5s) {
  25047. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25048. }
  25049. // uv6s
  25050. var uv6s = parsedVertexData.uv6s;
  25051. if (uv6s) {
  25052. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25053. }
  25054. // colors
  25055. var colors = parsedVertexData.colors;
  25056. if (colors) {
  25057. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25058. }
  25059. // matricesIndices
  25060. var matricesIndices = parsedVertexData.matricesIndices;
  25061. if (matricesIndices) {
  25062. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25063. }
  25064. // matricesWeights
  25065. var matricesWeights = parsedVertexData.matricesWeights;
  25066. if (matricesWeights) {
  25067. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25068. }
  25069. // indices
  25070. var indices = parsedVertexData.indices;
  25071. if (indices) {
  25072. vertexData.indices = indices;
  25073. }
  25074. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25075. };
  25076. return VertexData;
  25077. }());
  25078. BABYLON.VertexData = VertexData;
  25079. })(BABYLON || (BABYLON = {}));
  25080. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25081. var BABYLON;
  25082. (function (BABYLON) {
  25083. var Geometry = (function () {
  25084. function Geometry(id, scene, vertexData, updatable, mesh) {
  25085. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25086. this._totalVertices = 0;
  25087. this._isDisposed = false;
  25088. this.id = id;
  25089. this._engine = scene.getEngine();
  25090. this._meshes = [];
  25091. this._scene = scene;
  25092. //Init vertex buffer cache
  25093. this._vertexBuffers = {};
  25094. this._indices = [];
  25095. // vertexData
  25096. if (vertexData) {
  25097. this.setAllVerticesData(vertexData, updatable);
  25098. }
  25099. else {
  25100. this._totalVertices = 0;
  25101. this._indices = [];
  25102. }
  25103. if (this._engine.getCaps().vertexArrayObject) {
  25104. this._vertexArrayObjects = {};
  25105. }
  25106. // applyToMesh
  25107. if (mesh) {
  25108. if (mesh.getClassName() === "LinesMesh") {
  25109. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  25110. this.updateExtend();
  25111. }
  25112. this.applyToMesh(mesh);
  25113. mesh.computeWorldMatrix(true);
  25114. }
  25115. }
  25116. Object.defineProperty(Geometry.prototype, "boundingBias", {
  25117. /**
  25118. * 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
  25119. * @returns The Bias Vector
  25120. */
  25121. get: function () {
  25122. return this._boundingBias;
  25123. },
  25124. set: function (value) {
  25125. if (this._boundingBias && this._boundingBias.equals(value)) {
  25126. return;
  25127. }
  25128. this._boundingBias = value.clone();
  25129. this.updateBoundingInfo(true, null);
  25130. },
  25131. enumerable: true,
  25132. configurable: true
  25133. });
  25134. Object.defineProperty(Geometry.prototype, "extend", {
  25135. get: function () {
  25136. return this._extend;
  25137. },
  25138. enumerable: true,
  25139. configurable: true
  25140. });
  25141. Geometry.prototype.getScene = function () {
  25142. return this._scene;
  25143. };
  25144. Geometry.prototype.getEngine = function () {
  25145. return this._engine;
  25146. };
  25147. Geometry.prototype.isReady = function () {
  25148. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25149. };
  25150. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  25151. get: function () {
  25152. for (var index = 0; index < this._meshes.length; index++) {
  25153. if (!this._meshes[index].doNotSerialize) {
  25154. return false;
  25155. }
  25156. }
  25157. return true;
  25158. },
  25159. enumerable: true,
  25160. configurable: true
  25161. });
  25162. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25163. vertexData.applyToGeometry(this, updatable);
  25164. this.notifyUpdate();
  25165. };
  25166. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25167. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25168. this.setVerticesBuffer(buffer);
  25169. };
  25170. Geometry.prototype.removeVerticesData = function (kind) {
  25171. if (this._vertexBuffers[kind]) {
  25172. this._vertexBuffers[kind].dispose();
  25173. delete this._vertexBuffers[kind];
  25174. }
  25175. };
  25176. Geometry.prototype.setVerticesBuffer = function (buffer) {
  25177. var kind = buffer.getKind();
  25178. if (this._vertexBuffers[kind]) {
  25179. this._vertexBuffers[kind].dispose();
  25180. }
  25181. this._vertexBuffers[kind] = buffer;
  25182. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25183. var data = buffer.getData();
  25184. var stride = buffer.getStrideSize();
  25185. this._totalVertices = data.length / stride;
  25186. this.updateExtend(data, stride);
  25187. var meshes = this._meshes;
  25188. var numOfMeshes = meshes.length;
  25189. for (var index = 0; index < numOfMeshes; index++) {
  25190. var mesh = meshes[index];
  25191. mesh._resetPointsArrayCache();
  25192. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25193. mesh._createGlobalSubMesh();
  25194. mesh.computeWorldMatrix(true);
  25195. }
  25196. }
  25197. this.notifyUpdate(kind);
  25198. if (this._vertexArrayObjects) {
  25199. this._disposeVertexArrayObjects();
  25200. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  25201. }
  25202. };
  25203. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25204. var vertexBuffer = this.getVertexBuffer(kind);
  25205. if (!vertexBuffer) {
  25206. return;
  25207. }
  25208. vertexBuffer.updateDirectly(data, offset);
  25209. this.notifyUpdate(kind);
  25210. };
  25211. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25212. var vertexBuffer = this.getVertexBuffer(kind);
  25213. if (!vertexBuffer) {
  25214. return;
  25215. }
  25216. vertexBuffer.update(data);
  25217. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25218. var stride = vertexBuffer.getStrideSize();
  25219. this._totalVertices = data.length / stride;
  25220. this.updateBoundingInfo(updateExtends, data);
  25221. }
  25222. this.notifyUpdate(kind);
  25223. };
  25224. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  25225. if (updateExtends) {
  25226. this.updateExtend(data);
  25227. }
  25228. var meshes = this._meshes;
  25229. var numOfMeshes = meshes.length;
  25230. for (var index = 0; index < numOfMeshes; index++) {
  25231. var mesh = meshes[index];
  25232. mesh._resetPointsArrayCache();
  25233. if (updateExtends) {
  25234. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25235. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25236. var subMesh = mesh.subMeshes[subIndex];
  25237. subMesh.refreshBoundingInfo();
  25238. }
  25239. }
  25240. }
  25241. };
  25242. Geometry.prototype._bind = function (effect, indexToBind) {
  25243. if (indexToBind === void 0) { indexToBind = undefined; }
  25244. if (indexToBind === undefined) {
  25245. indexToBind = this._indexBuffer;
  25246. }
  25247. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  25248. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  25249. return;
  25250. }
  25251. // Using VAO
  25252. if (!this._vertexArrayObjects[effect.key]) {
  25253. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  25254. }
  25255. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  25256. };
  25257. Geometry.prototype.getTotalVertices = function () {
  25258. if (!this.isReady()) {
  25259. return 0;
  25260. }
  25261. return this._totalVertices;
  25262. };
  25263. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  25264. var vertexBuffer = this.getVertexBuffer(kind);
  25265. if (!vertexBuffer) {
  25266. return null;
  25267. }
  25268. var orig = vertexBuffer.getData();
  25269. if (!copyWhenShared || this._meshes.length === 1) {
  25270. return orig;
  25271. }
  25272. else {
  25273. var len = orig.length;
  25274. var copy = [];
  25275. for (var i = 0; i < len; i++) {
  25276. copy.push(orig[i]);
  25277. }
  25278. return copy;
  25279. }
  25280. };
  25281. Geometry.prototype.getVertexBuffer = function (kind) {
  25282. if (!this.isReady()) {
  25283. return null;
  25284. }
  25285. return this._vertexBuffers[kind];
  25286. };
  25287. Geometry.prototype.getVertexBuffers = function () {
  25288. if (!this.isReady()) {
  25289. return null;
  25290. }
  25291. return this._vertexBuffers;
  25292. };
  25293. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25294. if (!this._vertexBuffers) {
  25295. if (this._delayInfo) {
  25296. return this._delayInfo.indexOf(kind) !== -1;
  25297. }
  25298. return false;
  25299. }
  25300. return this._vertexBuffers[kind] !== undefined;
  25301. };
  25302. Geometry.prototype.getVerticesDataKinds = function () {
  25303. var result = [];
  25304. var kind;
  25305. if (!this._vertexBuffers && this._delayInfo) {
  25306. for (kind in this._delayInfo) {
  25307. result.push(kind);
  25308. }
  25309. }
  25310. else {
  25311. for (kind in this._vertexBuffers) {
  25312. result.push(kind);
  25313. }
  25314. }
  25315. return result;
  25316. };
  25317. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25318. if (this._indexBuffer) {
  25319. this._engine._releaseBuffer(this._indexBuffer);
  25320. }
  25321. this._disposeVertexArrayObjects();
  25322. this._indices = indices;
  25323. if (this._meshes.length !== 0 && this._indices) {
  25324. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25325. }
  25326. if (totalVertices !== undefined) {
  25327. this._totalVertices = totalVertices;
  25328. }
  25329. var meshes = this._meshes;
  25330. var numOfMeshes = meshes.length;
  25331. for (var index = 0; index < numOfMeshes; index++) {
  25332. meshes[index]._createGlobalSubMesh();
  25333. }
  25334. this.notifyUpdate();
  25335. };
  25336. Geometry.prototype.getTotalIndices = function () {
  25337. if (!this.isReady()) {
  25338. return 0;
  25339. }
  25340. return this._indices.length;
  25341. };
  25342. Geometry.prototype.getIndices = function (copyWhenShared) {
  25343. if (!this.isReady()) {
  25344. return null;
  25345. }
  25346. var orig = this._indices;
  25347. if (!copyWhenShared || this._meshes.length === 1) {
  25348. return orig;
  25349. }
  25350. else {
  25351. var len = orig.length;
  25352. var copy = [];
  25353. for (var i = 0; i < len; i++) {
  25354. copy.push(orig[i]);
  25355. }
  25356. return copy;
  25357. }
  25358. };
  25359. Geometry.prototype.getIndexBuffer = function () {
  25360. if (!this.isReady()) {
  25361. return null;
  25362. }
  25363. return this._indexBuffer;
  25364. };
  25365. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  25366. if (!effect) {
  25367. return;
  25368. }
  25369. if (this._vertexArrayObjects[effect.key]) {
  25370. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  25371. delete this._vertexArrayObjects[effect.key];
  25372. }
  25373. };
  25374. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25375. var meshes = this._meshes;
  25376. var index = meshes.indexOf(mesh);
  25377. if (index === -1) {
  25378. return;
  25379. }
  25380. meshes.splice(index, 1);
  25381. mesh._geometry = null;
  25382. if (meshes.length === 0 && shouldDispose) {
  25383. this.dispose();
  25384. }
  25385. };
  25386. Geometry.prototype.applyToMesh = function (mesh) {
  25387. if (mesh._geometry === this) {
  25388. return;
  25389. }
  25390. var previousGeometry = mesh._geometry;
  25391. if (previousGeometry) {
  25392. previousGeometry.releaseForMesh(mesh);
  25393. }
  25394. var meshes = this._meshes;
  25395. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25396. mesh._geometry = this;
  25397. this._scene.pushGeometry(this);
  25398. meshes.push(mesh);
  25399. if (this.isReady()) {
  25400. this._applyToMesh(mesh);
  25401. }
  25402. else {
  25403. mesh._boundingInfo = this._boundingInfo;
  25404. }
  25405. };
  25406. Geometry.prototype.updateExtend = function (data, stride) {
  25407. if (data === void 0) { data = null; }
  25408. if (!data) {
  25409. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  25410. }
  25411. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  25412. };
  25413. Geometry.prototype._applyToMesh = function (mesh) {
  25414. var numOfMeshes = this._meshes.length;
  25415. // vertexBuffers
  25416. for (var kind in this._vertexBuffers) {
  25417. if (numOfMeshes === 1) {
  25418. this._vertexBuffers[kind].create();
  25419. }
  25420. var buffer = this._vertexBuffers[kind].getBuffer();
  25421. if (buffer)
  25422. buffer.references = numOfMeshes;
  25423. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25424. mesh._resetPointsArrayCache();
  25425. if (!this._extend) {
  25426. this.updateExtend(this._vertexBuffers[kind].getData());
  25427. }
  25428. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25429. mesh._createGlobalSubMesh();
  25430. //bounding info was just created again, world matrix should be applied again.
  25431. mesh._updateBoundingInfo();
  25432. }
  25433. }
  25434. // indexBuffer
  25435. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  25436. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25437. }
  25438. if (this._indexBuffer) {
  25439. this._indexBuffer.references = numOfMeshes;
  25440. }
  25441. };
  25442. Geometry.prototype.notifyUpdate = function (kind) {
  25443. if (this.onGeometryUpdated) {
  25444. this.onGeometryUpdated(this, kind);
  25445. }
  25446. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  25447. var mesh = _a[_i];
  25448. mesh._markSubMeshesAsAttributesDirty();
  25449. }
  25450. };
  25451. Geometry.prototype.load = function (scene, onLoaded) {
  25452. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25453. return;
  25454. }
  25455. if (this.isReady()) {
  25456. if (onLoaded) {
  25457. onLoaded();
  25458. }
  25459. return;
  25460. }
  25461. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25462. this._queueLoad(scene, onLoaded);
  25463. };
  25464. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  25465. var _this = this;
  25466. scene._addPendingData(this);
  25467. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25468. _this._delayLoadingFunction(JSON.parse(data), _this);
  25469. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25470. _this._delayInfo = [];
  25471. scene._removePendingData(_this);
  25472. var meshes = _this._meshes;
  25473. var numOfMeshes = meshes.length;
  25474. for (var index = 0; index < numOfMeshes; index++) {
  25475. _this._applyToMesh(meshes[index]);
  25476. }
  25477. if (onLoaded) {
  25478. onLoaded();
  25479. }
  25480. }, function () { }, scene.database);
  25481. };
  25482. /**
  25483. * Invert the geometry to move from a right handed system to a left handed one.
  25484. */
  25485. Geometry.prototype.toLeftHanded = function () {
  25486. // Flip faces
  25487. var tIndices = this.getIndices(false);
  25488. if (tIndices != null && tIndices.length > 0) {
  25489. for (var i = 0; i < tIndices.length; i += 3) {
  25490. var tTemp = tIndices[i + 0];
  25491. tIndices[i + 0] = tIndices[i + 2];
  25492. tIndices[i + 2] = tTemp;
  25493. }
  25494. this.setIndices(tIndices);
  25495. }
  25496. // Negate position.z
  25497. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  25498. if (tPositions != null && tPositions.length > 0) {
  25499. for (var i = 0; i < tPositions.length; i += 3) {
  25500. tPositions[i + 2] = -tPositions[i + 2];
  25501. }
  25502. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  25503. }
  25504. // Negate normal.z
  25505. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  25506. if (tNormals != null && tNormals.length > 0) {
  25507. for (var i = 0; i < tNormals.length; i += 3) {
  25508. tNormals[i + 2] = -tNormals[i + 2];
  25509. }
  25510. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  25511. }
  25512. };
  25513. Geometry.prototype.isDisposed = function () {
  25514. return this._isDisposed;
  25515. };
  25516. Geometry.prototype._disposeVertexArrayObjects = function () {
  25517. if (this._vertexArrayObjects) {
  25518. for (var kind in this._vertexArrayObjects) {
  25519. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  25520. }
  25521. this._vertexArrayObjects = {};
  25522. }
  25523. };
  25524. Geometry.prototype.dispose = function () {
  25525. var meshes = this._meshes;
  25526. var numOfMeshes = meshes.length;
  25527. var index;
  25528. for (index = 0; index < numOfMeshes; index++) {
  25529. this.releaseForMesh(meshes[index]);
  25530. }
  25531. this._meshes = [];
  25532. this._disposeVertexArrayObjects();
  25533. for (var kind in this._vertexBuffers) {
  25534. this._vertexBuffers[kind].dispose();
  25535. }
  25536. this._vertexBuffers = {};
  25537. this._totalVertices = 0;
  25538. if (this._indexBuffer) {
  25539. this._engine._releaseBuffer(this._indexBuffer);
  25540. }
  25541. this._indexBuffer = null;
  25542. this._indices = [];
  25543. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25544. this.delayLoadingFile = null;
  25545. this._delayLoadingFunction = null;
  25546. this._delayInfo = [];
  25547. this._boundingInfo = null;
  25548. this._scene.removeGeometry(this);
  25549. this._isDisposed = true;
  25550. };
  25551. Geometry.prototype.copy = function (id) {
  25552. var vertexData = new BABYLON.VertexData();
  25553. vertexData.indices = [];
  25554. var indices = this.getIndices();
  25555. for (var index = 0; index < indices.length; index++) {
  25556. vertexData.indices.push(indices[index]);
  25557. }
  25558. var updatable = false;
  25559. var stopChecking = false;
  25560. var kind;
  25561. for (kind in this._vertexBuffers) {
  25562. // using slice() to make a copy of the array and not just reference it
  25563. var data = this.getVerticesData(kind);
  25564. if (data instanceof Float32Array) {
  25565. vertexData.set(new Float32Array(data), kind);
  25566. }
  25567. else {
  25568. vertexData.set(data.slice(0), kind);
  25569. }
  25570. if (!stopChecking) {
  25571. updatable = this.getVertexBuffer(kind).isUpdatable();
  25572. stopChecking = !updatable;
  25573. }
  25574. }
  25575. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25576. geometry.delayLoadState = this.delayLoadState;
  25577. geometry.delayLoadingFile = this.delayLoadingFile;
  25578. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25579. for (kind in this._delayInfo) {
  25580. geometry._delayInfo = geometry._delayInfo || [];
  25581. geometry._delayInfo.push(kind);
  25582. }
  25583. // Bounding info
  25584. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25585. return geometry;
  25586. };
  25587. Geometry.prototype.serialize = function () {
  25588. var serializationObject = {};
  25589. serializationObject.id = this.id;
  25590. if (BABYLON.Tags.HasTags(this)) {
  25591. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25592. }
  25593. return serializationObject;
  25594. };
  25595. Geometry.prototype.serializeVerticeData = function () {
  25596. var serializationObject = this.serialize();
  25597. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25598. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25599. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  25600. serializationObject.positions._updatable = true;
  25601. }
  25602. }
  25603. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25604. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25605. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  25606. serializationObject.normals._updatable = true;
  25607. }
  25608. }
  25609. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25610. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25611. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  25612. serializationObject.uvs._updatable = true;
  25613. }
  25614. }
  25615. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25616. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  25617. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  25618. serializationObject.uv2s._updatable = true;
  25619. }
  25620. }
  25621. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25622. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  25623. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  25624. serializationObject.uv3s._updatable = true;
  25625. }
  25626. }
  25627. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25628. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  25629. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  25630. serializationObject.uv4s._updatable = true;
  25631. }
  25632. }
  25633. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25634. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  25635. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  25636. serializationObject.uv5s._updatable = true;
  25637. }
  25638. }
  25639. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25640. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  25641. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  25642. serializationObject.uv6s._updatable = true;
  25643. }
  25644. }
  25645. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25646. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  25647. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  25648. serializationObject.colors._updatable = true;
  25649. }
  25650. }
  25651. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25652. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25653. serializationObject.matricesIndices._isExpanded = true;
  25654. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  25655. serializationObject.matricesIndices._updatable = true;
  25656. }
  25657. }
  25658. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25659. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25660. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  25661. serializationObject.matricesWeights._updatable = true;
  25662. }
  25663. }
  25664. serializationObject.indices = this.getIndices();
  25665. return serializationObject;
  25666. };
  25667. // Statics
  25668. Geometry.ExtractFromMesh = function (mesh, id) {
  25669. var geometry = mesh._geometry;
  25670. if (!geometry) {
  25671. return null;
  25672. }
  25673. return geometry.copy(id);
  25674. };
  25675. /**
  25676. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  25677. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25678. * Be aware Math.random() could cause collisions, but:
  25679. * "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"
  25680. */
  25681. Geometry.RandomId = function () {
  25682. return BABYLON.Tools.RandomId();
  25683. };
  25684. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  25685. var scene = mesh.getScene();
  25686. // Geometry
  25687. var geometryId = parsedGeometry.geometryId;
  25688. if (geometryId) {
  25689. var geometry = scene.getGeometryByID(geometryId);
  25690. if (geometry) {
  25691. geometry.applyToMesh(mesh);
  25692. }
  25693. }
  25694. else if (parsedGeometry instanceof ArrayBuffer) {
  25695. var binaryInfo = mesh._binaryInfo;
  25696. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  25697. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  25698. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  25699. }
  25700. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  25701. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  25702. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  25703. }
  25704. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  25705. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  25706. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  25707. }
  25708. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  25709. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  25710. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  25711. }
  25712. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  25713. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  25714. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  25715. }
  25716. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  25717. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  25718. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  25719. }
  25720. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  25721. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  25722. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  25723. }
  25724. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  25725. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  25726. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  25727. }
  25728. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  25729. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  25730. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  25731. }
  25732. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  25733. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  25734. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  25735. }
  25736. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  25737. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  25738. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  25739. }
  25740. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  25741. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  25742. mesh.setIndices(indicesData);
  25743. }
  25744. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  25745. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  25746. mesh.subMeshes = [];
  25747. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  25748. var materialIndex = subMeshesData[(i * 5) + 0];
  25749. var verticesStart = subMeshesData[(i * 5) + 1];
  25750. var verticesCount = subMeshesData[(i * 5) + 2];
  25751. var indexStart = subMeshesData[(i * 5) + 3];
  25752. var indexCount = subMeshesData[(i * 5) + 4];
  25753. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  25754. }
  25755. }
  25756. }
  25757. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  25758. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  25759. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  25760. if (parsedGeometry.uvs) {
  25761. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  25762. }
  25763. if (parsedGeometry.uvs2) {
  25764. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  25765. }
  25766. if (parsedGeometry.uvs3) {
  25767. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  25768. }
  25769. if (parsedGeometry.uvs4) {
  25770. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  25771. }
  25772. if (parsedGeometry.uvs5) {
  25773. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  25774. }
  25775. if (parsedGeometry.uvs6) {
  25776. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  25777. }
  25778. if (parsedGeometry.colors) {
  25779. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  25780. }
  25781. if (parsedGeometry.matricesIndices) {
  25782. if (!parsedGeometry.matricesIndices._isExpanded) {
  25783. var floatIndices = [];
  25784. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  25785. var matricesIndex = parsedGeometry.matricesIndices[i];
  25786. floatIndices.push(matricesIndex & 0x000000FF);
  25787. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  25788. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  25789. floatIndices.push(matricesIndex >> 24);
  25790. }
  25791. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  25792. }
  25793. else {
  25794. delete parsedGeometry.matricesIndices._isExpanded;
  25795. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  25796. }
  25797. }
  25798. if (parsedGeometry.matricesIndicesExtra) {
  25799. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  25800. var floatIndices = [];
  25801. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  25802. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  25803. floatIndices.push(matricesIndex & 0x000000FF);
  25804. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  25805. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  25806. floatIndices.push(matricesIndex >> 24);
  25807. }
  25808. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  25809. }
  25810. else {
  25811. delete parsedGeometry.matricesIndices._isExpanded;
  25812. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  25813. }
  25814. }
  25815. if (parsedGeometry.matricesWeights) {
  25816. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  25817. }
  25818. if (parsedGeometry.matricesWeightsExtra) {
  25819. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  25820. }
  25821. mesh.setIndices(parsedGeometry.indices);
  25822. }
  25823. // SubMeshes
  25824. if (parsedGeometry.subMeshes) {
  25825. mesh.subMeshes = [];
  25826. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  25827. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  25828. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  25829. }
  25830. }
  25831. // Flat shading
  25832. if (mesh._shouldGenerateFlatShading) {
  25833. mesh.convertToFlatShadedMesh();
  25834. delete mesh._shouldGenerateFlatShading;
  25835. }
  25836. // Update
  25837. mesh.computeWorldMatrix(true);
  25838. // Octree
  25839. if (scene['_selectionOctree']) {
  25840. scene['_selectionOctree'].addMesh(mesh);
  25841. }
  25842. };
  25843. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  25844. if (scene.getGeometryByID(parsedVertexData.id)) {
  25845. return null; // null since geometry could be something else than a box...
  25846. }
  25847. var geometry = new Geometry(parsedVertexData.id, scene);
  25848. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  25849. if (parsedVertexData.delayLoadingFile) {
  25850. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25851. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  25852. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  25853. geometry._delayInfo = [];
  25854. if (parsedVertexData.hasUVs) {
  25855. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25856. }
  25857. if (parsedVertexData.hasUVs2) {
  25858. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25859. }
  25860. if (parsedVertexData.hasUVs3) {
  25861. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25862. }
  25863. if (parsedVertexData.hasUVs4) {
  25864. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25865. }
  25866. if (parsedVertexData.hasUVs5) {
  25867. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25868. }
  25869. if (parsedVertexData.hasUVs6) {
  25870. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25871. }
  25872. if (parsedVertexData.hasColors) {
  25873. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25874. }
  25875. if (parsedVertexData.hasMatricesIndices) {
  25876. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25877. }
  25878. if (parsedVertexData.hasMatricesWeights) {
  25879. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25880. }
  25881. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  25882. }
  25883. else {
  25884. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  25885. }
  25886. scene.pushGeometry(geometry, true);
  25887. return geometry;
  25888. };
  25889. return Geometry;
  25890. }());
  25891. BABYLON.Geometry = Geometry;
  25892. /////// Primitives //////////////////////////////////////////////
  25893. (function (Geometry) {
  25894. var Primitives;
  25895. (function (Primitives) {
  25896. /// Abstract class
  25897. var _Primitive = (function (_super) {
  25898. __extends(_Primitive, _super);
  25899. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  25900. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  25901. _this._canBeRegenerated = _canBeRegenerated;
  25902. _this._beingRegenerated = true;
  25903. _this.regenerate();
  25904. _this._beingRegenerated = false;
  25905. return _this;
  25906. }
  25907. _Primitive.prototype.canBeRegenerated = function () {
  25908. return this._canBeRegenerated;
  25909. };
  25910. _Primitive.prototype.regenerate = function () {
  25911. if (!this._canBeRegenerated) {
  25912. return;
  25913. }
  25914. this._beingRegenerated = true;
  25915. this.setAllVerticesData(this._regenerateVertexData(), false);
  25916. this._beingRegenerated = false;
  25917. };
  25918. _Primitive.prototype.asNewGeometry = function (id) {
  25919. return _super.prototype.copy.call(this, id);
  25920. };
  25921. // overrides
  25922. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25923. if (!this._beingRegenerated) {
  25924. return;
  25925. }
  25926. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25927. };
  25928. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25929. if (!this._beingRegenerated) {
  25930. return;
  25931. }
  25932. _super.prototype.setVerticesData.call(this, kind, data, false);
  25933. };
  25934. // to override
  25935. // protected
  25936. _Primitive.prototype._regenerateVertexData = function () {
  25937. throw new Error("Abstract method");
  25938. };
  25939. _Primitive.prototype.copy = function (id) {
  25940. throw new Error("Must be overriden in sub-classes.");
  25941. };
  25942. _Primitive.prototype.serialize = function () {
  25943. var serializationObject = _super.prototype.serialize.call(this);
  25944. serializationObject.canBeRegenerated = this.canBeRegenerated();
  25945. return serializationObject;
  25946. };
  25947. return _Primitive;
  25948. }(Geometry));
  25949. Primitives._Primitive = _Primitive;
  25950. var Ribbon = (function (_super) {
  25951. __extends(Ribbon, _super);
  25952. // Members
  25953. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25954. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25955. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  25956. _this.pathArray = pathArray;
  25957. _this.closeArray = closeArray;
  25958. _this.closePath = closePath;
  25959. _this.offset = offset;
  25960. _this.side = side;
  25961. return _this;
  25962. }
  25963. Ribbon.prototype._regenerateVertexData = function () {
  25964. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  25965. };
  25966. Ribbon.prototype.copy = function (id) {
  25967. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25968. };
  25969. return Ribbon;
  25970. }(_Primitive));
  25971. Primitives.Ribbon = Ribbon;
  25972. var Box = (function (_super) {
  25973. __extends(Box, _super);
  25974. // Members
  25975. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25976. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25977. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  25978. _this.size = size;
  25979. _this.side = side;
  25980. return _this;
  25981. }
  25982. Box.prototype._regenerateVertexData = function () {
  25983. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  25984. };
  25985. Box.prototype.copy = function (id) {
  25986. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25987. };
  25988. Box.prototype.serialize = function () {
  25989. var serializationObject = _super.prototype.serialize.call(this);
  25990. serializationObject.size = this.size;
  25991. return serializationObject;
  25992. };
  25993. Box.Parse = function (parsedBox, scene) {
  25994. if (scene.getGeometryByID(parsedBox.id)) {
  25995. return null; // null since geometry could be something else than a box...
  25996. }
  25997. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  25998. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  25999. scene.pushGeometry(box, true);
  26000. return box;
  26001. };
  26002. return Box;
  26003. }(_Primitive));
  26004. Primitives.Box = Box;
  26005. var Sphere = (function (_super) {
  26006. __extends(Sphere, _super);
  26007. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26008. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26009. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26010. _this.segments = segments;
  26011. _this.diameter = diameter;
  26012. _this.side = side;
  26013. return _this;
  26014. }
  26015. Sphere.prototype._regenerateVertexData = function () {
  26016. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26017. };
  26018. Sphere.prototype.copy = function (id) {
  26019. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26020. };
  26021. Sphere.prototype.serialize = function () {
  26022. var serializationObject = _super.prototype.serialize.call(this);
  26023. serializationObject.segments = this.segments;
  26024. serializationObject.diameter = this.diameter;
  26025. return serializationObject;
  26026. };
  26027. Sphere.Parse = function (parsedSphere, scene) {
  26028. if (scene.getGeometryByID(parsedSphere.id)) {
  26029. return null; // null since geometry could be something else than a sphere...
  26030. }
  26031. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26032. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26033. scene.pushGeometry(sphere, true);
  26034. return sphere;
  26035. };
  26036. return Sphere;
  26037. }(_Primitive));
  26038. Primitives.Sphere = Sphere;
  26039. var Disc = (function (_super) {
  26040. __extends(Disc, _super);
  26041. // Members
  26042. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26043. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26044. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26045. _this.radius = radius;
  26046. _this.tessellation = tessellation;
  26047. _this.side = side;
  26048. return _this;
  26049. }
  26050. Disc.prototype._regenerateVertexData = function () {
  26051. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26052. };
  26053. Disc.prototype.copy = function (id) {
  26054. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26055. };
  26056. return Disc;
  26057. }(_Primitive));
  26058. Primitives.Disc = Disc;
  26059. var Cylinder = (function (_super) {
  26060. __extends(Cylinder, _super);
  26061. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26062. if (subdivisions === void 0) { subdivisions = 1; }
  26063. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26064. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26065. _this.height = height;
  26066. _this.diameterTop = diameterTop;
  26067. _this.diameterBottom = diameterBottom;
  26068. _this.tessellation = tessellation;
  26069. _this.subdivisions = subdivisions;
  26070. _this.side = side;
  26071. return _this;
  26072. }
  26073. Cylinder.prototype._regenerateVertexData = function () {
  26074. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26075. };
  26076. Cylinder.prototype.copy = function (id) {
  26077. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26078. };
  26079. Cylinder.prototype.serialize = function () {
  26080. var serializationObject = _super.prototype.serialize.call(this);
  26081. serializationObject.height = this.height;
  26082. serializationObject.diameterTop = this.diameterTop;
  26083. serializationObject.diameterBottom = this.diameterBottom;
  26084. serializationObject.tessellation = this.tessellation;
  26085. return serializationObject;
  26086. };
  26087. Cylinder.Parse = function (parsedCylinder, scene) {
  26088. if (scene.getGeometryByID(parsedCylinder.id)) {
  26089. return null; // null since geometry could be something else than a cylinder...
  26090. }
  26091. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  26092. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  26093. scene.pushGeometry(cylinder, true);
  26094. return cylinder;
  26095. };
  26096. return Cylinder;
  26097. }(_Primitive));
  26098. Primitives.Cylinder = Cylinder;
  26099. var Torus = (function (_super) {
  26100. __extends(Torus, _super);
  26101. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26102. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26103. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26104. _this.diameter = diameter;
  26105. _this.thickness = thickness;
  26106. _this.tessellation = tessellation;
  26107. _this.side = side;
  26108. return _this;
  26109. }
  26110. Torus.prototype._regenerateVertexData = function () {
  26111. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26112. };
  26113. Torus.prototype.copy = function (id) {
  26114. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26115. };
  26116. Torus.prototype.serialize = function () {
  26117. var serializationObject = _super.prototype.serialize.call(this);
  26118. serializationObject.diameter = this.diameter;
  26119. serializationObject.thickness = this.thickness;
  26120. serializationObject.tessellation = this.tessellation;
  26121. return serializationObject;
  26122. };
  26123. Torus.Parse = function (parsedTorus, scene) {
  26124. if (scene.getGeometryByID(parsedTorus.id)) {
  26125. return null; // null since geometry could be something else than a torus...
  26126. }
  26127. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  26128. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  26129. scene.pushGeometry(torus, true);
  26130. return torus;
  26131. };
  26132. return Torus;
  26133. }(_Primitive));
  26134. Primitives.Torus = Torus;
  26135. var Ground = (function (_super) {
  26136. __extends(Ground, _super);
  26137. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26138. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26139. _this.width = width;
  26140. _this.height = height;
  26141. _this.subdivisions = subdivisions;
  26142. return _this;
  26143. }
  26144. Ground.prototype._regenerateVertexData = function () {
  26145. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26146. };
  26147. Ground.prototype.copy = function (id) {
  26148. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26149. };
  26150. Ground.prototype.serialize = function () {
  26151. var serializationObject = _super.prototype.serialize.call(this);
  26152. serializationObject.width = this.width;
  26153. serializationObject.height = this.height;
  26154. serializationObject.subdivisions = this.subdivisions;
  26155. return serializationObject;
  26156. };
  26157. Ground.Parse = function (parsedGround, scene) {
  26158. if (scene.getGeometryByID(parsedGround.id)) {
  26159. return null; // null since geometry could be something else than a ground...
  26160. }
  26161. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  26162. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  26163. scene.pushGeometry(ground, true);
  26164. return ground;
  26165. };
  26166. return Ground;
  26167. }(_Primitive));
  26168. Primitives.Ground = Ground;
  26169. var TiledGround = (function (_super) {
  26170. __extends(TiledGround, _super);
  26171. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26172. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26173. _this.xmin = xmin;
  26174. _this.zmin = zmin;
  26175. _this.xmax = xmax;
  26176. _this.zmax = zmax;
  26177. _this.subdivisions = subdivisions;
  26178. _this.precision = precision;
  26179. return _this;
  26180. }
  26181. TiledGround.prototype._regenerateVertexData = function () {
  26182. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26183. };
  26184. TiledGround.prototype.copy = function (id) {
  26185. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26186. };
  26187. return TiledGround;
  26188. }(_Primitive));
  26189. Primitives.TiledGround = TiledGround;
  26190. var Plane = (function (_super) {
  26191. __extends(Plane, _super);
  26192. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26193. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26194. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26195. _this.size = size;
  26196. _this.side = side;
  26197. return _this;
  26198. }
  26199. Plane.prototype._regenerateVertexData = function () {
  26200. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26201. };
  26202. Plane.prototype.copy = function (id) {
  26203. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26204. };
  26205. Plane.prototype.serialize = function () {
  26206. var serializationObject = _super.prototype.serialize.call(this);
  26207. serializationObject.size = this.size;
  26208. return serializationObject;
  26209. };
  26210. Plane.Parse = function (parsedPlane, scene) {
  26211. if (scene.getGeometryByID(parsedPlane.id)) {
  26212. return null; // null since geometry could be something else than a ground...
  26213. }
  26214. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  26215. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  26216. scene.pushGeometry(plane, true);
  26217. return plane;
  26218. };
  26219. return Plane;
  26220. }(_Primitive));
  26221. Primitives.Plane = Plane;
  26222. var TorusKnot = (function (_super) {
  26223. __extends(TorusKnot, _super);
  26224. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26225. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26226. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26227. _this.radius = radius;
  26228. _this.tube = tube;
  26229. _this.radialSegments = radialSegments;
  26230. _this.tubularSegments = tubularSegments;
  26231. _this.p = p;
  26232. _this.q = q;
  26233. _this.side = side;
  26234. return _this;
  26235. }
  26236. TorusKnot.prototype._regenerateVertexData = function () {
  26237. 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 });
  26238. };
  26239. TorusKnot.prototype.copy = function (id) {
  26240. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26241. };
  26242. TorusKnot.prototype.serialize = function () {
  26243. var serializationObject = _super.prototype.serialize.call(this);
  26244. serializationObject.radius = this.radius;
  26245. serializationObject.tube = this.tube;
  26246. serializationObject.radialSegments = this.radialSegments;
  26247. serializationObject.tubularSegments = this.tubularSegments;
  26248. serializationObject.p = this.p;
  26249. serializationObject.q = this.q;
  26250. return serializationObject;
  26251. };
  26252. ;
  26253. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  26254. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  26255. return null; // null since geometry could be something else than a ground...
  26256. }
  26257. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  26258. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  26259. scene.pushGeometry(torusKnot, true);
  26260. return torusKnot;
  26261. };
  26262. return TorusKnot;
  26263. }(_Primitive));
  26264. Primitives.TorusKnot = TorusKnot;
  26265. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26266. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26267. })(BABYLON || (BABYLON = {}));
  26268. //# sourceMappingURL=babylon.geometry.js.map
  26269. var BABYLON;
  26270. (function (BABYLON) {
  26271. var PostProcessManager = (function () {
  26272. function PostProcessManager(scene) {
  26273. this._vertexBuffers = {};
  26274. this._scene = scene;
  26275. }
  26276. PostProcessManager.prototype._prepareBuffers = function () {
  26277. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  26278. return;
  26279. }
  26280. // VBO
  26281. var vertices = [];
  26282. vertices.push(1, 1);
  26283. vertices.push(-1, 1);
  26284. vertices.push(-1, -1);
  26285. vertices.push(1, -1);
  26286. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  26287. // Indices
  26288. var indices = [];
  26289. indices.push(0);
  26290. indices.push(1);
  26291. indices.push(2);
  26292. indices.push(0);
  26293. indices.push(2);
  26294. indices.push(3);
  26295. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26296. };
  26297. // Methods
  26298. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26299. var postProcesses = this._scene.activeCamera._postProcesses;
  26300. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  26301. return false;
  26302. }
  26303. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  26304. return true;
  26305. };
  26306. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26307. var engine = this._scene.getEngine();
  26308. for (var index = 0; index < postProcesses.length; index++) {
  26309. if (index < postProcesses.length - 1) {
  26310. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26311. }
  26312. else {
  26313. if (targetTexture) {
  26314. engine.bindFramebuffer(targetTexture);
  26315. }
  26316. else {
  26317. engine.restoreDefaultFramebuffer();
  26318. }
  26319. }
  26320. var pp = postProcesses[index];
  26321. var effect = pp.apply();
  26322. if (effect) {
  26323. pp.onBeforeRenderObservable.notifyObservers(effect);
  26324. // VBOs
  26325. this._prepareBuffers();
  26326. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26327. // Draw order
  26328. engine.draw(true, 0, 6);
  26329. pp.onAfterRenderObservable.notifyObservers(effect);
  26330. }
  26331. }
  26332. // Restore depth buffer
  26333. engine.setDepthBuffer(true);
  26334. engine.setDepthWrite(true);
  26335. };
  26336. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  26337. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  26338. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  26339. return;
  26340. }
  26341. var engine = this._scene.getEngine();
  26342. for (var index = 0, len = postProcesses.length; index < len; index++) {
  26343. if (index < len - 1) {
  26344. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26345. }
  26346. else {
  26347. if (targetTexture) {
  26348. engine.bindFramebuffer(targetTexture, faceIndex);
  26349. }
  26350. else {
  26351. engine.restoreDefaultFramebuffer();
  26352. }
  26353. }
  26354. if (doNotPresent) {
  26355. break;
  26356. }
  26357. var pp = postProcesses[index];
  26358. var effect = pp.apply();
  26359. if (effect) {
  26360. pp.onBeforeRenderObservable.notifyObservers(effect);
  26361. // VBOs
  26362. this._prepareBuffers();
  26363. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26364. // Draw order
  26365. engine.draw(true, 0, 6);
  26366. pp.onAfterRenderObservable.notifyObservers(effect);
  26367. }
  26368. }
  26369. // Restore depth buffer
  26370. engine.setDepthBuffer(true);
  26371. engine.setDepthWrite(true);
  26372. };
  26373. PostProcessManager.prototype.dispose = function () {
  26374. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  26375. if (buffer) {
  26376. buffer.dispose();
  26377. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  26378. }
  26379. if (this._indexBuffer) {
  26380. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26381. this._indexBuffer = null;
  26382. }
  26383. };
  26384. return PostProcessManager;
  26385. }());
  26386. BABYLON.PostProcessManager = PostProcessManager;
  26387. })(BABYLON || (BABYLON = {}));
  26388. //# sourceMappingURL=babylon.postProcessManager.js.map
  26389. var BABYLON;
  26390. (function (BABYLON) {
  26391. var StandardMaterialDefines = (function (_super) {
  26392. __extends(StandardMaterialDefines, _super);
  26393. function StandardMaterialDefines() {
  26394. var _this = _super.call(this) || this;
  26395. _this.DIFFUSE = false;
  26396. _this.AMBIENT = false;
  26397. _this.OPACITY = false;
  26398. _this.OPACITYRGB = false;
  26399. _this.REFLECTION = false;
  26400. _this.EMISSIVE = false;
  26401. _this.SPECULAR = false;
  26402. _this.BUMP = false;
  26403. _this.PARALLAX = false;
  26404. _this.PARALLAXOCCLUSION = false;
  26405. _this.SPECULAROVERALPHA = false;
  26406. _this.CLIPPLANE = false;
  26407. _this.ALPHATEST = false;
  26408. _this.ALPHAFROMDIFFUSE = false;
  26409. _this.POINTSIZE = false;
  26410. _this.FOG = false;
  26411. _this.SPECULARTERM = false;
  26412. _this.DIFFUSEFRESNEL = false;
  26413. _this.OPACITYFRESNEL = false;
  26414. _this.REFLECTIONFRESNEL = false;
  26415. _this.REFRACTIONFRESNEL = false;
  26416. _this.EMISSIVEFRESNEL = false;
  26417. _this.FRESNEL = false;
  26418. _this.NORMAL = false;
  26419. _this.UV1 = false;
  26420. _this.UV2 = false;
  26421. _this.VERTEXCOLOR = false;
  26422. _this.VERTEXALPHA = false;
  26423. _this.NUM_BONE_INFLUENCERS = 0;
  26424. _this.BonesPerMesh = 0;
  26425. _this.INSTANCES = false;
  26426. _this.GLOSSINESS = false;
  26427. _this.ROUGHNESS = false;
  26428. _this.EMISSIVEASILLUMINATION = false;
  26429. _this.LINKEMISSIVEWITHDIFFUSE = false;
  26430. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  26431. _this.LIGHTMAP = false;
  26432. _this.USELIGHTMAPASSHADOWMAP = false;
  26433. _this.REFLECTIONMAP_3D = false;
  26434. _this.REFLECTIONMAP_SPHERICAL = false;
  26435. _this.REFLECTIONMAP_PLANAR = false;
  26436. _this.REFLECTIONMAP_CUBIC = false;
  26437. _this.REFLECTIONMAP_PROJECTION = false;
  26438. _this.REFLECTIONMAP_SKYBOX = false;
  26439. _this.REFLECTIONMAP_EXPLICIT = false;
  26440. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  26441. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  26442. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  26443. _this.INVERTCUBICMAP = false;
  26444. _this.LOGARITHMICDEPTH = false;
  26445. _this.REFRACTION = false;
  26446. _this.REFRACTIONMAP_3D = false;
  26447. _this.REFLECTIONOVERALPHA = false;
  26448. _this.INVERTNORMALMAPX = false;
  26449. _this.INVERTNORMALMAPY = false;
  26450. _this.TWOSIDEDLIGHTING = false;
  26451. _this.SHADOWFULLFLOAT = false;
  26452. _this.CAMERACOLORGRADING = false;
  26453. _this.CAMERACOLORCURVES = false;
  26454. _this.MORPHTARGETS = false;
  26455. _this.MORPHTARGETS_NORMAL = false;
  26456. _this.NUM_MORPH_INFLUENCERS = 0;
  26457. _this.rebuild();
  26458. return _this;
  26459. }
  26460. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  26461. var modes = [
  26462. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  26463. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  26464. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  26465. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  26466. ];
  26467. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  26468. var mode = modes_1[_i];
  26469. this[mode] = (mode === modeToEnable);
  26470. }
  26471. };
  26472. return StandardMaterialDefines;
  26473. }(BABYLON.MaterialDefines));
  26474. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  26475. var StandardMaterial = (function (_super) {
  26476. __extends(StandardMaterial, _super);
  26477. function StandardMaterial(name, scene) {
  26478. var _this = _super.call(this, name, scene) || this;
  26479. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  26480. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  26481. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  26482. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  26483. _this.specularPower = 64;
  26484. _this._useAlphaFromDiffuseTexture = false;
  26485. _this._useEmissiveAsIllumination = false;
  26486. _this._linkEmissiveWithDiffuse = false;
  26487. _this._useSpecularOverAlpha = false;
  26488. _this._useReflectionOverAlpha = false;
  26489. _this._disableLighting = false;
  26490. _this._useParallax = false;
  26491. _this._useParallaxOcclusion = false;
  26492. _this.parallaxScaleBias = 0.05;
  26493. _this._roughness = 0;
  26494. _this.indexOfRefraction = 0.98;
  26495. _this.invertRefractionY = true;
  26496. _this._useLightmapAsShadowmap = false;
  26497. _this._useReflectionFresnelFromSpecular = false;
  26498. _this._useGlossinessFromSpecularMapAlpha = false;
  26499. _this._maxSimultaneousLights = 4;
  26500. /**
  26501. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  26502. */
  26503. _this._invertNormalMapX = false;
  26504. /**
  26505. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  26506. */
  26507. _this._invertNormalMapY = false;
  26508. /**
  26509. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  26510. */
  26511. _this._twoSidedLighting = false;
  26512. /**
  26513. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  26514. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  26515. * 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;
  26516. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  26517. */
  26518. _this._cameraColorCurves = null;
  26519. _this._renderTargets = new BABYLON.SmartArray(16);
  26520. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  26521. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  26522. _this.getRenderTargetTextures = function () {
  26523. _this._renderTargets.reset();
  26524. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  26525. _this._renderTargets.push(_this._reflectionTexture);
  26526. }
  26527. if (_this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  26528. _this._renderTargets.push(_this._refractionTexture);
  26529. }
  26530. return _this._renderTargets;
  26531. };
  26532. return _this;
  26533. }
  26534. StandardMaterial.prototype.getClassName = function () {
  26535. return "StandardMaterial";
  26536. };
  26537. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  26538. get: function () {
  26539. return this._useLogarithmicDepth;
  26540. },
  26541. set: function (value) {
  26542. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  26543. this._markAllSubMeshesAsMiscDirty();
  26544. },
  26545. enumerable: true,
  26546. configurable: true
  26547. });
  26548. StandardMaterial.prototype.needAlphaBlending = function () {
  26549. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  26550. };
  26551. StandardMaterial.prototype.needAlphaTesting = function () {
  26552. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  26553. };
  26554. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  26555. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  26556. };
  26557. StandardMaterial.prototype.getAlphaTestTexture = function () {
  26558. return this._diffuseTexture;
  26559. };
  26560. /**
  26561. * Child classes can use it to update shaders
  26562. */
  26563. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  26564. if (this.isFrozen) {
  26565. if (this._wasPreviouslyReady && subMesh.effect) {
  26566. return true;
  26567. }
  26568. }
  26569. if (!subMesh._materialDefines) {
  26570. subMesh._materialDefines = new StandardMaterialDefines();
  26571. }
  26572. var scene = this.getScene();
  26573. var defines = subMesh._materialDefines;
  26574. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  26575. if (defines._renderId === scene.getRenderId()) {
  26576. return true;
  26577. }
  26578. }
  26579. var engine = scene.getEngine();
  26580. // Lights
  26581. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  26582. // Textures
  26583. if (defines._areTexturesDirty) {
  26584. defines._needUVs = false;
  26585. if (scene.texturesEnabled) {
  26586. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26587. if (!this._diffuseTexture.isReady()) {
  26588. return false;
  26589. }
  26590. else {
  26591. defines._needUVs = true;
  26592. defines.DIFFUSE = true;
  26593. }
  26594. }
  26595. else {
  26596. defines.DIFFUSE = false;
  26597. }
  26598. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26599. if (!this._ambientTexture.isReady()) {
  26600. return false;
  26601. }
  26602. else {
  26603. defines._needUVs = true;
  26604. defines.AMBIENT = true;
  26605. }
  26606. }
  26607. else {
  26608. defines.AMBIENT = false;
  26609. }
  26610. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26611. if (!this._opacityTexture.isReady()) {
  26612. return false;
  26613. }
  26614. else {
  26615. defines._needUVs = true;
  26616. defines.OPACITY = true;
  26617. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  26618. }
  26619. }
  26620. else {
  26621. defines.OPACITY = false;
  26622. }
  26623. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26624. if (!this._reflectionTexture.isReady()) {
  26625. return false;
  26626. }
  26627. else {
  26628. defines._needNormals = true;
  26629. defines.REFLECTION = true;
  26630. defines.ROUGHNESS = (this._roughness > 0);
  26631. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  26632. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  26633. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  26634. switch (this._reflectionTexture.coordinatesMode) {
  26635. case BABYLON.Texture.CUBIC_MODE:
  26636. case BABYLON.Texture.INVCUBIC_MODE:
  26637. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  26638. break;
  26639. case BABYLON.Texture.EXPLICIT_MODE:
  26640. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  26641. break;
  26642. case BABYLON.Texture.PLANAR_MODE:
  26643. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  26644. break;
  26645. case BABYLON.Texture.PROJECTION_MODE:
  26646. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  26647. break;
  26648. case BABYLON.Texture.SKYBOX_MODE:
  26649. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  26650. break;
  26651. case BABYLON.Texture.SPHERICAL_MODE:
  26652. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  26653. break;
  26654. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  26655. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  26656. break;
  26657. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  26658. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  26659. break;
  26660. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  26661. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  26662. break;
  26663. }
  26664. }
  26665. }
  26666. else {
  26667. defines.REFLECTION = false;
  26668. }
  26669. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26670. if (!this._emissiveTexture.isReady()) {
  26671. return false;
  26672. }
  26673. else {
  26674. defines._needUVs = true;
  26675. defines.EMISSIVE = true;
  26676. }
  26677. }
  26678. else {
  26679. defines.EMISSIVE = false;
  26680. }
  26681. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26682. if (!this._lightmapTexture.isReady()) {
  26683. return false;
  26684. }
  26685. else {
  26686. defines._needUVs = true;
  26687. defines.LIGHTMAP = true;
  26688. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  26689. }
  26690. }
  26691. else {
  26692. defines.LIGHTMAP = false;
  26693. }
  26694. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26695. if (!this._specularTexture.isReady()) {
  26696. return false;
  26697. }
  26698. else {
  26699. defines._needUVs = true;
  26700. defines.SPECULAR = true;
  26701. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  26702. }
  26703. }
  26704. else {
  26705. defines.SPECULAR = false;
  26706. }
  26707. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  26708. if (!this._bumpTexture.isReady()) {
  26709. return false;
  26710. }
  26711. else {
  26712. defines._needUVs = true;
  26713. defines.BUMP = true;
  26714. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  26715. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  26716. defines.PARALLAX = this._useParallax;
  26717. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  26718. }
  26719. }
  26720. else {
  26721. defines.BUMP = false;
  26722. }
  26723. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26724. if (!this._refractionTexture.isReady()) {
  26725. return false;
  26726. }
  26727. else {
  26728. defines._needUVs = true;
  26729. defines.REFRACTION = true;
  26730. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  26731. }
  26732. }
  26733. else {
  26734. defines.REFRACTION = false;
  26735. }
  26736. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26737. if (!this._cameraColorGradingTexture.isReady()) {
  26738. return false;
  26739. }
  26740. else {
  26741. defines.CAMERACOLORGRADING = true;
  26742. }
  26743. }
  26744. else {
  26745. defines.CAMERACOLORGRADING = false;
  26746. }
  26747. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  26748. }
  26749. else {
  26750. defines.DIFFUSE = false;
  26751. defines.AMBIENT = false;
  26752. defines.OPACITY = false;
  26753. defines.REFLECTION = false;
  26754. defines.EMISSIVE = false;
  26755. defines.LIGHTMAP = false;
  26756. defines.BUMP = false;
  26757. defines.REFRACTION = false;
  26758. defines.CAMERACOLORGRADING = false;
  26759. }
  26760. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  26761. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  26762. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  26763. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  26764. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  26765. }
  26766. if (defines._areFresnelDirty) {
  26767. if (StandardMaterial.FresnelEnabled) {
  26768. // Fresnel
  26769. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  26770. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  26771. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  26772. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  26773. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  26774. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  26775. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  26776. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  26777. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  26778. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  26779. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  26780. defines._needNormals = true;
  26781. defines.FRESNEL = true;
  26782. }
  26783. }
  26784. else {
  26785. defines.FRESNEL = false;
  26786. }
  26787. }
  26788. // Misc.
  26789. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  26790. // Attribs
  26791. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  26792. // Values that need to be evaluated on every frame
  26793. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  26794. if (scene._mirroredCameraPosition && defines.BUMP) {
  26795. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  26796. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  26797. defines.markAsUnprocessed();
  26798. }
  26799. // Get correct effect
  26800. if (defines.isDirty) {
  26801. defines.markAsProcessed();
  26802. scene.resetCachedMaterial();
  26803. // Fallbacks
  26804. var fallbacks = new BABYLON.EffectFallbacks();
  26805. if (defines.REFLECTION) {
  26806. fallbacks.addFallback(0, "REFLECTION");
  26807. }
  26808. if (defines.SPECULAR) {
  26809. fallbacks.addFallback(0, "SPECULAR");
  26810. }
  26811. if (defines.BUMP) {
  26812. fallbacks.addFallback(0, "BUMP");
  26813. }
  26814. if (defines.PARALLAX) {
  26815. fallbacks.addFallback(1, "PARALLAX");
  26816. }
  26817. if (defines.PARALLAXOCCLUSION) {
  26818. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26819. }
  26820. if (defines.SPECULAROVERALPHA) {
  26821. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26822. }
  26823. if (defines.FOG) {
  26824. fallbacks.addFallback(1, "FOG");
  26825. }
  26826. if (defines.POINTSIZE) {
  26827. fallbacks.addFallback(0, "POINTSIZE");
  26828. }
  26829. if (defines.LOGARITHMICDEPTH) {
  26830. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26831. }
  26832. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  26833. if (defines.SPECULARTERM) {
  26834. fallbacks.addFallback(0, "SPECULARTERM");
  26835. }
  26836. if (defines.DIFFUSEFRESNEL) {
  26837. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26838. }
  26839. if (defines.OPACITYFRESNEL) {
  26840. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26841. }
  26842. if (defines.REFLECTIONFRESNEL) {
  26843. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26844. }
  26845. if (defines.EMISSIVEFRESNEL) {
  26846. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26847. }
  26848. if (defines.FRESNEL) {
  26849. fallbacks.addFallback(4, "FRESNEL");
  26850. }
  26851. //Attributes
  26852. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26853. if (defines.NORMAL) {
  26854. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26855. }
  26856. if (defines.UV1) {
  26857. attribs.push(BABYLON.VertexBuffer.UVKind);
  26858. }
  26859. if (defines.UV2) {
  26860. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26861. }
  26862. if (defines.VERTEXCOLOR) {
  26863. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26864. }
  26865. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  26866. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  26867. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  26868. var shaderName = "default";
  26869. if (this.customShaderNameResolve) {
  26870. shaderName = this.customShaderNameResolve(shaderName);
  26871. }
  26872. var join = defines.toString();
  26873. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26874. "vFogInfos", "vFogColor", "pointSize",
  26875. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26876. "mBones",
  26877. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26878. "depthValues",
  26879. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26880. "logarithmicDepthConstant"
  26881. ];
  26882. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26883. if (defines.CAMERACOLORCURVES) {
  26884. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26885. }
  26886. if (defines.CAMERACOLORGRADING) {
  26887. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26888. }
  26889. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, defines, this._maxSimultaneousLights);
  26890. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  26891. attributes: attribs,
  26892. uniformsNames: uniforms,
  26893. samplers: samplers,
  26894. defines: join,
  26895. fallbacks: fallbacks,
  26896. onCompiled: this.onCompiled,
  26897. onError: this.onError,
  26898. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  26899. }, engine), defines);
  26900. }
  26901. if (!subMesh.effect.isReady()) {
  26902. return false;
  26903. }
  26904. defines._renderId = scene.getRenderId();
  26905. this._wasPreviouslyReady = true;
  26906. return true;
  26907. };
  26908. StandardMaterial.prototype.unbind = function () {
  26909. if (this._activeEffect) {
  26910. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  26911. this._activeEffect.setTexture("reflection2DSampler", null);
  26912. }
  26913. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  26914. this._activeEffect.setTexture("refraction2DSampler", null);
  26915. }
  26916. }
  26917. _super.prototype.unbind.call(this);
  26918. };
  26919. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  26920. var scene = this.getScene();
  26921. var defines = subMesh._materialDefines;
  26922. if (!defines) {
  26923. return;
  26924. }
  26925. var effect = subMesh.effect;
  26926. this._activeEffect = effect;
  26927. // Matrices
  26928. this.bindOnlyWorldMatrix(world);
  26929. // Bones
  26930. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  26931. if (this._mustRebind(scene, effect)) {
  26932. effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26933. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  26934. // Fresnel
  26935. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26936. effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26937. effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26938. }
  26939. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26940. effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26941. }
  26942. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26943. effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26944. effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26945. }
  26946. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26947. effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26948. effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26949. }
  26950. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26951. effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26952. effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26953. }
  26954. }
  26955. // Textures
  26956. if (scene.texturesEnabled) {
  26957. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26958. effect.setTexture("diffuseSampler", this._diffuseTexture);
  26959. effect.setFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  26960. effect.setMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  26961. }
  26962. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26963. effect.setTexture("ambientSampler", this._ambientTexture);
  26964. effect.setFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  26965. effect.setMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  26966. }
  26967. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26968. effect.setTexture("opacitySampler", this._opacityTexture);
  26969. effect.setFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  26970. effect.setMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  26971. }
  26972. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26973. if (this._reflectionTexture.isCube) {
  26974. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  26975. }
  26976. else {
  26977. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  26978. }
  26979. effect.setMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  26980. effect.setFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  26981. }
  26982. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26983. effect.setTexture("emissiveSampler", this._emissiveTexture);
  26984. effect.setFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  26985. effect.setMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  26986. }
  26987. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26988. effect.setTexture("lightmapSampler", this._lightmapTexture);
  26989. effect.setFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  26990. effect.setMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  26991. }
  26992. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26993. effect.setTexture("specularSampler", this._specularTexture);
  26994. effect.setFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  26995. effect.setMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  26996. }
  26997. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26998. effect.setTexture("bumpSampler", this._bumpTexture);
  26999. effect.setFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  27000. effect.setMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  27001. }
  27002. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27003. var depth = 1.0;
  27004. if (this._refractionTexture.isCube) {
  27005. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  27006. }
  27007. else {
  27008. effect.setTexture("refraction2DSampler", this._refractionTexture);
  27009. effect.setMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  27010. if (this._refractionTexture.depth) {
  27011. depth = this._refractionTexture.depth;
  27012. }
  27013. }
  27014. effect.setFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  27015. }
  27016. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27017. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  27018. }
  27019. }
  27020. // Clip plane
  27021. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  27022. // Point size
  27023. if (this.pointsCloud) {
  27024. effect.setFloat("pointSize", this.pointSize);
  27025. }
  27026. // Colors
  27027. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27028. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27029. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27030. if (defines.SPECULARTERM) {
  27031. effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  27032. }
  27033. effect.setColor3("vEmissiveColor", this.emissiveColor);
  27034. }
  27035. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  27036. // Diffuse
  27037. effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27038. // Lights
  27039. if (scene.lightsEnabled && !this.disableLighting) {
  27040. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  27041. }
  27042. // View
  27043. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  27044. effect.setMatrix("view", scene.getViewMatrix());
  27045. }
  27046. // Fog
  27047. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  27048. // Morph targets
  27049. if (defines.NUM_MORPH_INFLUENCERS) {
  27050. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  27051. }
  27052. // Log. depth
  27053. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  27054. // Color Curves
  27055. if (this.cameraColorCurves) {
  27056. BABYLON.ColorCurves.Bind(this.cameraColorCurves, effect);
  27057. }
  27058. }
  27059. this._afterBind(mesh, this._activeEffect);
  27060. };
  27061. StandardMaterial.prototype.getAnimatables = function () {
  27062. var results = [];
  27063. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  27064. results.push(this._diffuseTexture);
  27065. }
  27066. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  27067. results.push(this._ambientTexture);
  27068. }
  27069. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  27070. results.push(this._opacityTexture);
  27071. }
  27072. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  27073. results.push(this._reflectionTexture);
  27074. }
  27075. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  27076. results.push(this._emissiveTexture);
  27077. }
  27078. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  27079. results.push(this._specularTexture);
  27080. }
  27081. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  27082. results.push(this._bumpTexture);
  27083. }
  27084. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  27085. results.push(this._lightmapTexture);
  27086. }
  27087. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  27088. results.push(this._refractionTexture);
  27089. }
  27090. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  27091. results.push(this._cameraColorGradingTexture);
  27092. }
  27093. return results;
  27094. };
  27095. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27096. if (forceDisposeTextures) {
  27097. if (this._diffuseTexture) {
  27098. this._diffuseTexture.dispose();
  27099. }
  27100. if (this._ambientTexture) {
  27101. this._ambientTexture.dispose();
  27102. }
  27103. if (this._opacityTexture) {
  27104. this._opacityTexture.dispose();
  27105. }
  27106. if (this._reflectionTexture) {
  27107. this._reflectionTexture.dispose();
  27108. }
  27109. if (this._emissiveTexture) {
  27110. this._emissiveTexture.dispose();
  27111. }
  27112. if (this._specularTexture) {
  27113. this._specularTexture.dispose();
  27114. }
  27115. if (this._bumpTexture) {
  27116. this._bumpTexture.dispose();
  27117. }
  27118. if (this._lightmapTexture) {
  27119. this._lightmapTexture.dispose();
  27120. }
  27121. if (this._refractionTexture) {
  27122. this._refractionTexture.dispose();
  27123. }
  27124. if (this._cameraColorGradingTexture) {
  27125. this._cameraColorGradingTexture.dispose();
  27126. }
  27127. }
  27128. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27129. };
  27130. StandardMaterial.prototype.clone = function (name) {
  27131. var _this = this;
  27132. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27133. result.name = name;
  27134. result.id = name;
  27135. return result;
  27136. };
  27137. StandardMaterial.prototype.serialize = function () {
  27138. return BABYLON.SerializationHelper.Serialize(this);
  27139. };
  27140. // Statics
  27141. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27142. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27143. };
  27144. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  27145. get: function () {
  27146. return StandardMaterial._DiffuseTextureEnabled;
  27147. },
  27148. set: function (value) {
  27149. if (StandardMaterial._DiffuseTextureEnabled === value) {
  27150. return;
  27151. }
  27152. StandardMaterial._DiffuseTextureEnabled = value;
  27153. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27154. },
  27155. enumerable: true,
  27156. configurable: true
  27157. });
  27158. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  27159. get: function () {
  27160. return StandardMaterial._AmbientTextureEnabled;
  27161. },
  27162. set: function (value) {
  27163. if (StandardMaterial._AmbientTextureEnabled === value) {
  27164. return;
  27165. }
  27166. StandardMaterial._AmbientTextureEnabled = value;
  27167. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27168. },
  27169. enumerable: true,
  27170. configurable: true
  27171. });
  27172. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  27173. get: function () {
  27174. return StandardMaterial._OpacityTextureEnabled;
  27175. },
  27176. set: function (value) {
  27177. if (StandardMaterial._OpacityTextureEnabled === value) {
  27178. return;
  27179. }
  27180. StandardMaterial._OpacityTextureEnabled = value;
  27181. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27182. },
  27183. enumerable: true,
  27184. configurable: true
  27185. });
  27186. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  27187. get: function () {
  27188. return StandardMaterial._ReflectionTextureEnabled;
  27189. },
  27190. set: function (value) {
  27191. if (StandardMaterial._ReflectionTextureEnabled === value) {
  27192. return;
  27193. }
  27194. StandardMaterial._ReflectionTextureEnabled = value;
  27195. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27196. },
  27197. enumerable: true,
  27198. configurable: true
  27199. });
  27200. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  27201. get: function () {
  27202. return StandardMaterial._EmissiveTextureEnabled;
  27203. },
  27204. set: function (value) {
  27205. if (StandardMaterial._EmissiveTextureEnabled === value) {
  27206. return;
  27207. }
  27208. StandardMaterial._EmissiveTextureEnabled = value;
  27209. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27210. },
  27211. enumerable: true,
  27212. configurable: true
  27213. });
  27214. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  27215. get: function () {
  27216. return StandardMaterial._SpecularTextureEnabled;
  27217. },
  27218. set: function (value) {
  27219. if (StandardMaterial._SpecularTextureEnabled === value) {
  27220. return;
  27221. }
  27222. StandardMaterial._SpecularTextureEnabled = value;
  27223. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27224. },
  27225. enumerable: true,
  27226. configurable: true
  27227. });
  27228. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  27229. get: function () {
  27230. return StandardMaterial._BumpTextureEnabled;
  27231. },
  27232. set: function (value) {
  27233. if (StandardMaterial._BumpTextureEnabled === value) {
  27234. return;
  27235. }
  27236. StandardMaterial._BumpTextureEnabled = value;
  27237. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27238. },
  27239. enumerable: true,
  27240. configurable: true
  27241. });
  27242. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  27243. get: function () {
  27244. return StandardMaterial._LightmapTextureEnabled;
  27245. },
  27246. set: function (value) {
  27247. if (StandardMaterial._LightmapTextureEnabled === value) {
  27248. return;
  27249. }
  27250. StandardMaterial._LightmapTextureEnabled = value;
  27251. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27252. },
  27253. enumerable: true,
  27254. configurable: true
  27255. });
  27256. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  27257. get: function () {
  27258. return StandardMaterial._RefractionTextureEnabled;
  27259. },
  27260. set: function (value) {
  27261. if (StandardMaterial._RefractionTextureEnabled === value) {
  27262. return;
  27263. }
  27264. StandardMaterial._RefractionTextureEnabled = value;
  27265. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27266. },
  27267. enumerable: true,
  27268. configurable: true
  27269. });
  27270. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  27271. get: function () {
  27272. return StandardMaterial._ColorGradingTextureEnabled;
  27273. },
  27274. set: function (value) {
  27275. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  27276. return;
  27277. }
  27278. StandardMaterial._ColorGradingTextureEnabled = value;
  27279. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27280. },
  27281. enumerable: true,
  27282. configurable: true
  27283. });
  27284. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  27285. get: function () {
  27286. return StandardMaterial._FresnelEnabled;
  27287. },
  27288. set: function (value) {
  27289. if (StandardMaterial._FresnelEnabled === value) {
  27290. return;
  27291. }
  27292. StandardMaterial._FresnelEnabled = value;
  27293. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  27294. },
  27295. enumerable: true,
  27296. configurable: true
  27297. });
  27298. return StandardMaterial;
  27299. }(BABYLON.PushMaterial));
  27300. // Flags used to enable or disable a type of texture for all Standard Materials
  27301. StandardMaterial._DiffuseTextureEnabled = true;
  27302. StandardMaterial._AmbientTextureEnabled = true;
  27303. StandardMaterial._OpacityTextureEnabled = true;
  27304. StandardMaterial._ReflectionTextureEnabled = true;
  27305. StandardMaterial._EmissiveTextureEnabled = true;
  27306. StandardMaterial._SpecularTextureEnabled = true;
  27307. StandardMaterial._BumpTextureEnabled = true;
  27308. StandardMaterial._LightmapTextureEnabled = true;
  27309. StandardMaterial._RefractionTextureEnabled = true;
  27310. StandardMaterial._ColorGradingTextureEnabled = true;
  27311. StandardMaterial._FresnelEnabled = true;
  27312. __decorate([
  27313. BABYLON.serializeAsTexture("diffuseTexture")
  27314. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  27315. __decorate([
  27316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27317. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  27318. __decorate([
  27319. BABYLON.serializeAsTexture("ambientTexture")
  27320. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  27321. __decorate([
  27322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27323. ], StandardMaterial.prototype, "ambientTexture", void 0);
  27324. __decorate([
  27325. BABYLON.serializeAsTexture("opacityTexture")
  27326. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  27327. __decorate([
  27328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27329. ], StandardMaterial.prototype, "opacityTexture", void 0);
  27330. __decorate([
  27331. BABYLON.serializeAsTexture("reflectionTexture")
  27332. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  27333. __decorate([
  27334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27335. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  27336. __decorate([
  27337. BABYLON.serializeAsTexture("emissiveTexture")
  27338. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  27339. __decorate([
  27340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27341. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  27342. __decorate([
  27343. BABYLON.serializeAsTexture("specularTexture")
  27344. ], StandardMaterial.prototype, "_specularTexture", void 0);
  27345. __decorate([
  27346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27347. ], StandardMaterial.prototype, "specularTexture", void 0);
  27348. __decorate([
  27349. BABYLON.serializeAsTexture("bumpTexture")
  27350. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  27351. __decorate([
  27352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27353. ], StandardMaterial.prototype, "bumpTexture", void 0);
  27354. __decorate([
  27355. BABYLON.serializeAsTexture("lightmapTexture")
  27356. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  27357. __decorate([
  27358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27359. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  27360. __decorate([
  27361. BABYLON.serializeAsTexture("refractionTexture")
  27362. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  27363. __decorate([
  27364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27365. ], StandardMaterial.prototype, "refractionTexture", void 0);
  27366. __decorate([
  27367. BABYLON.serializeAsColor3("ambient")
  27368. ], StandardMaterial.prototype, "ambientColor", void 0);
  27369. __decorate([
  27370. BABYLON.serializeAsColor3("diffuse")
  27371. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27372. __decorate([
  27373. BABYLON.serializeAsColor3("specular")
  27374. ], StandardMaterial.prototype, "specularColor", void 0);
  27375. __decorate([
  27376. BABYLON.serializeAsColor3("emissive")
  27377. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27378. __decorate([
  27379. BABYLON.serialize()
  27380. ], StandardMaterial.prototype, "specularPower", void 0);
  27381. __decorate([
  27382. BABYLON.serialize("useAlphaFromDiffuseTexture")
  27383. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  27384. __decorate([
  27385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27386. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27387. __decorate([
  27388. BABYLON.serialize("useEmissiveAsIllumination")
  27389. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  27390. __decorate([
  27391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27392. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27393. __decorate([
  27394. BABYLON.serialize("linkEmissiveWithDiffuse")
  27395. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  27396. __decorate([
  27397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27398. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27399. __decorate([
  27400. BABYLON.serialize("useSpecularOverAlpha")
  27401. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  27402. __decorate([
  27403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27404. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27405. __decorate([
  27406. BABYLON.serialize("useReflectionOverAlpha")
  27407. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  27408. __decorate([
  27409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27410. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27411. __decorate([
  27412. BABYLON.serialize("disableLighting")
  27413. ], StandardMaterial.prototype, "_disableLighting", void 0);
  27414. __decorate([
  27415. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  27416. ], StandardMaterial.prototype, "disableLighting", void 0);
  27417. __decorate([
  27418. BABYLON.serialize("useParallax")
  27419. ], StandardMaterial.prototype, "_useParallax", void 0);
  27420. __decorate([
  27421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27422. ], StandardMaterial.prototype, "useParallax", void 0);
  27423. __decorate([
  27424. BABYLON.serialize("useParallaxOcclusion")
  27425. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  27426. __decorate([
  27427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27428. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  27429. __decorate([
  27430. BABYLON.serialize()
  27431. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  27432. __decorate([
  27433. BABYLON.serialize("roughness")
  27434. ], StandardMaterial.prototype, "_roughness", void 0);
  27435. __decorate([
  27436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27437. ], StandardMaterial.prototype, "roughness", void 0);
  27438. __decorate([
  27439. BABYLON.serialize()
  27440. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  27441. __decorate([
  27442. BABYLON.serialize()
  27443. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  27444. __decorate([
  27445. BABYLON.serialize("useLightmapAsShadowmap")
  27446. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  27447. __decorate([
  27448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27449. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  27450. __decorate([
  27451. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  27452. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  27453. __decorate([
  27454. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  27455. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  27456. __decorate([
  27457. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  27458. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  27459. __decorate([
  27460. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  27461. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  27462. __decorate([
  27463. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  27464. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  27465. __decorate([
  27466. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  27467. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  27468. __decorate([
  27469. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  27470. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  27471. __decorate([
  27472. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  27473. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  27474. __decorate([
  27475. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  27476. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  27477. __decorate([
  27478. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  27479. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  27480. __decorate([
  27481. BABYLON.serialize("useReflectionFresnelFromSpecular")
  27482. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  27483. __decorate([
  27484. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  27485. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27486. __decorate([
  27487. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  27488. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  27489. __decorate([
  27490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27491. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  27492. __decorate([
  27493. BABYLON.serialize("maxSimultaneousLights")
  27494. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  27495. __decorate([
  27496. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  27497. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  27498. __decorate([
  27499. BABYLON.serialize("invertNormalMapX")
  27500. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  27501. __decorate([
  27502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27503. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  27504. __decorate([
  27505. BABYLON.serialize("invertNormalMapY")
  27506. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  27507. __decorate([
  27508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27509. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  27510. __decorate([
  27511. BABYLON.serialize("twoSidedLighting")
  27512. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  27513. __decorate([
  27514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27515. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  27516. __decorate([
  27517. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  27518. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  27519. __decorate([
  27520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27521. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  27522. __decorate([
  27523. BABYLON.serializeAsColorCurves("cameraColorCurves")
  27524. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  27525. __decorate([
  27526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  27527. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  27528. __decorate([
  27529. BABYLON.serialize()
  27530. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  27531. BABYLON.StandardMaterial = StandardMaterial;
  27532. })(BABYLON || (BABYLON = {}));
  27533. //# sourceMappingURL=babylon.standardMaterial.js.map
  27534. var BABYLON;
  27535. (function (BABYLON) {
  27536. var PBRMaterialDefines = (function (_super) {
  27537. __extends(PBRMaterialDefines, _super);
  27538. function PBRMaterialDefines() {
  27539. var _this = _super.call(this) || this;
  27540. _this.ALBEDO = false;
  27541. _this.AMBIENT = false;
  27542. _this.AMBIENTINGRAYSCALE = false;
  27543. _this.OPACITY = false;
  27544. _this.OPACITYRGB = false;
  27545. _this.REFLECTION = false;
  27546. _this.EMISSIVE = false;
  27547. _this.REFLECTIVITY = false;
  27548. _this.BUMP = false;
  27549. _this.PARALLAX = false;
  27550. _this.PARALLAXOCCLUSION = false;
  27551. _this.SPECULAROVERALPHA = false;
  27552. _this.CLIPPLANE = false;
  27553. _this.ALPHATEST = false;
  27554. _this.ALPHAFROMALBEDO = false;
  27555. _this.POINTSIZE = false;
  27556. _this.FOG = false;
  27557. _this.SPECULARTERM = false;
  27558. _this.OPACITYFRESNEL = false;
  27559. _this.EMISSIVEFRESNEL = false;
  27560. _this.FRESNEL = false;
  27561. _this.NORMAL = false;
  27562. _this.TANGENT = false;
  27563. _this.UV1 = false;
  27564. _this.UV2 = false;
  27565. _this.VERTEXCOLOR = false;
  27566. _this.VERTEXALPHA = false;
  27567. _this.NUM_BONE_INFLUENCERS = 0;
  27568. _this.BonesPerMesh = 0;
  27569. _this.INSTANCES = false;
  27570. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  27571. _this.MICROSURFACEAUTOMATIC = false;
  27572. _this.EMISSIVEASILLUMINATION = false;
  27573. _this.LINKEMISSIVEWITHALBEDO = false;
  27574. _this.LIGHTMAP = false;
  27575. _this.USELIGHTMAPASSHADOWMAP = false;
  27576. _this.REFLECTIONMAP_3D = false;
  27577. _this.REFLECTIONMAP_SPHERICAL = false;
  27578. _this.REFLECTIONMAP_PLANAR = false;
  27579. _this.REFLECTIONMAP_CUBIC = false;
  27580. _this.REFLECTIONMAP_PROJECTION = false;
  27581. _this.REFLECTIONMAP_SKYBOX = false;
  27582. _this.REFLECTIONMAP_EXPLICIT = false;
  27583. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  27584. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  27585. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  27586. _this.INVERTCUBICMAP = false;
  27587. _this.LOGARITHMICDEPTH = false;
  27588. _this.CAMERATONEMAP = false;
  27589. _this.CAMERACONTRAST = false;
  27590. _this.CAMERACOLORGRADING = false;
  27591. _this.CAMERACOLORCURVES = false;
  27592. _this.OVERLOADEDVALUES = false;
  27593. _this.OVERLOADEDSHADOWVALUES = false;
  27594. _this.USESPHERICALFROMREFLECTIONMAP = false;
  27595. _this.REFRACTION = false;
  27596. _this.REFRACTIONMAP_3D = false;
  27597. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  27598. _this.REFRACTIONMAPINLINEARSPACE = false;
  27599. _this.LODBASEDMICROSFURACE = false;
  27600. _this.USEPHYSICALLIGHTFALLOFF = false;
  27601. _this.RADIANCEOVERALPHA = false;
  27602. _this.USEPMREMREFLECTION = false;
  27603. _this.USEPMREMREFRACTION = false;
  27604. _this.INVERTNORMALMAPX = false;
  27605. _this.INVERTNORMALMAPY = false;
  27606. _this.TWOSIDEDLIGHTING = false;
  27607. _this.SHADOWFULLFLOAT = false;
  27608. _this.METALLICWORKFLOW = false;
  27609. _this.METALLICMAP = false;
  27610. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  27611. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  27612. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  27613. _this.AOSTOREINMETALMAPRED = false;
  27614. _this.MICROSURFACEMAP = false;
  27615. _this.MORPHTARGETS = false;
  27616. _this.MORPHTARGETS_NORMAL = false;
  27617. _this.NUM_MORPH_INFLUENCERS = 0;
  27618. _this.rebuild();
  27619. return _this;
  27620. }
  27621. return PBRMaterialDefines;
  27622. }(BABYLON.MaterialDefines));
  27623. /**
  27624. * The Physically based material of BJS.
  27625. *
  27626. * This offers the main features of a standard PBR material.
  27627. * For more information, please refer to the documentation :
  27628. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  27629. */
  27630. var PBRMaterial = (function (_super) {
  27631. __extends(PBRMaterial, _super);
  27632. /**
  27633. * Instantiates a new PBRMaterial instance.
  27634. *
  27635. * @param name The material name
  27636. * @param scene The scene the material will be use in.
  27637. */
  27638. function PBRMaterial(name, scene) {
  27639. var _this = _super.call(this, name, scene) || this;
  27640. /**
  27641. * Intensity of the direct lights e.g. the four lights available in your scene.
  27642. * This impacts both the direct diffuse and specular highlights.
  27643. */
  27644. _this.directIntensity = 1.0;
  27645. /**
  27646. * Intensity of the emissive part of the material.
  27647. * This helps controlling the emissive effect without modifying the emissive color.
  27648. */
  27649. _this.emissiveIntensity = 1.0;
  27650. /**
  27651. * Intensity of the environment e.g. how much the environment will light the object
  27652. * either through harmonics for rough material or through the refelction for shiny ones.
  27653. */
  27654. _this.environmentIntensity = 1.0;
  27655. /**
  27656. * This is a special control allowing the reduction of the specular highlights coming from the
  27657. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  27658. */
  27659. _this.specularIntensity = 1.0;
  27660. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  27661. /**
  27662. * Debug Control allowing disabling the bump map on this material.
  27663. */
  27664. _this.disableBumpMap = false;
  27665. /**
  27666. * Debug Control helping enforcing or dropping the darkness of shadows.
  27667. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  27668. */
  27669. _this.overloadedShadowIntensity = 1.0;
  27670. /**
  27671. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  27672. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  27673. */
  27674. _this.overloadedShadeIntensity = 1.0;
  27675. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  27676. /**
  27677. * The camera exposure used on this material.
  27678. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  27679. * This corresponds to a photographic exposure.
  27680. */
  27681. _this.cameraExposure = 1.0;
  27682. /**
  27683. * The camera contrast used on this material.
  27684. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  27685. */
  27686. _this.cameraContrast = 1.0;
  27687. /**
  27688. * Color Grading 2D Lookup Texture.
  27689. * This allows special effects like sepia, black and white to sixties rendering style.
  27690. */
  27691. _this.cameraColorGradingTexture = null;
  27692. /**
  27693. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  27694. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  27695. * 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;
  27696. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  27697. */
  27698. _this.cameraColorCurves = null;
  27699. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  27700. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  27701. /**
  27702. * Debug Control allowing to overload the ambient color.
  27703. * This as to be use with the overloadedAmbientIntensity parameter.
  27704. */
  27705. _this.overloadedAmbient = BABYLON.Color3.White();
  27706. /**
  27707. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  27708. */
  27709. _this.overloadedAmbientIntensity = 0.0;
  27710. /**
  27711. * Debug Control allowing to overload the albedo color.
  27712. * This as to be use with the overloadedAlbedoIntensity parameter.
  27713. */
  27714. _this.overloadedAlbedo = BABYLON.Color3.White();
  27715. /**
  27716. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  27717. */
  27718. _this.overloadedAlbedoIntensity = 0.0;
  27719. /**
  27720. * Debug Control allowing to overload the reflectivity color.
  27721. * This as to be use with the overloadedReflectivityIntensity parameter.
  27722. */
  27723. _this.overloadedReflectivity = new BABYLON.Color3(0.0, 0.0, 0.0);
  27724. /**
  27725. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  27726. */
  27727. _this.overloadedReflectivityIntensity = 0.0;
  27728. /**
  27729. * Debug Control allowing to overload the emissive color.
  27730. * This as to be use with the overloadedEmissiveIntensity parameter.
  27731. */
  27732. _this.overloadedEmissive = BABYLON.Color3.White();
  27733. /**
  27734. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  27735. */
  27736. _this.overloadedEmissiveIntensity = 0.0;
  27737. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  27738. /**
  27739. * Debug Control allowing to overload the reflection color.
  27740. * This as to be use with the overloadedReflectionIntensity parameter.
  27741. */
  27742. _this.overloadedReflection = BABYLON.Color3.White();
  27743. /**
  27744. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  27745. */
  27746. _this.overloadedReflectionIntensity = 0.0;
  27747. /**
  27748. * Debug Control allowing to overload the microsurface.
  27749. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  27750. */
  27751. _this.overloadedMicroSurface = 0.0;
  27752. /**
  27753. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  27754. */
  27755. _this.overloadedMicroSurfaceIntensity = 0.0;
  27756. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  27757. /**
  27758. * AKA Occlusion Texture Intensity in other nomenclature.
  27759. */
  27760. _this.ambientTextureStrength = 1.0;
  27761. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  27762. /**
  27763. * AKA Diffuse Color in other nomenclature.
  27764. */
  27765. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  27766. /**
  27767. * AKA Specular Color in other nomenclature.
  27768. */
  27769. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  27770. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  27771. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  27772. /**
  27773. * AKA Glossiness in other nomenclature.
  27774. */
  27775. _this.microSurface = 0.9;
  27776. /**
  27777. * source material index of refraction (IOR)' / 'destination material IOR.
  27778. */
  27779. _this.indexOfRefraction = 0.66;
  27780. /**
  27781. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  27782. */
  27783. _this.invertRefractionY = false;
  27784. /**
  27785. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  27786. * Materials half opaque for instance using refraction could benefit from this control.
  27787. */
  27788. _this.linkRefractionWithTransparency = false;
  27789. /**
  27790. * The emissive and albedo are linked to never be more than one (Energy conservation).
  27791. */
  27792. _this.linkEmissiveWithAlbedo = false;
  27793. _this.useLightmapAsShadowmap = false;
  27794. /**
  27795. * In this mode, the emissive informtaion will always be added to the lighting once.
  27796. * A light for instance can be thought as emissive.
  27797. */
  27798. _this.useEmissiveAsIllumination = false;
  27799. /**
  27800. * Secifies that the alpha is coming form the albedo channel alpha channel.
  27801. */
  27802. _this.useAlphaFromAlbedoTexture = false;
  27803. /**
  27804. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  27805. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  27806. */
  27807. _this.useSpecularOverAlpha = true;
  27808. /**
  27809. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  27810. */
  27811. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  27812. /**
  27813. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  27814. */
  27815. _this.useRoughnessFromMetallicTextureAlpha = true;
  27816. /**
  27817. * Specifies if the metallic texture contains the roughness information in its green channel.
  27818. */
  27819. _this.useRoughnessFromMetallicTextureGreen = false;
  27820. /**
  27821. * Specifies if the metallic texture contains the metallness information in its blue channel.
  27822. */
  27823. _this.useMetallnessFromMetallicTextureBlue = false;
  27824. /**
  27825. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  27826. */
  27827. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  27828. /**
  27829. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  27830. */
  27831. _this.useAmbientInGrayScale = false;
  27832. /**
  27833. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  27834. * The material will try to infer what glossiness each pixel should be.
  27835. */
  27836. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  27837. /**
  27838. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  27839. * the creation of the material.
  27840. */
  27841. _this.useScalarInLinearSpace = false;
  27842. /**
  27843. * BJS is using an harcoded light falloff based on a manually sets up range.
  27844. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  27845. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  27846. */
  27847. _this.usePhysicalLightFalloff = true;
  27848. /**
  27849. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  27850. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  27851. */
  27852. _this.useRadianceOverAlpha = true;
  27853. /**
  27854. * Allows using the bump map in parallax mode.
  27855. */
  27856. _this.useParallax = false;
  27857. /**
  27858. * Allows using the bump map in parallax occlusion mode.
  27859. */
  27860. _this.useParallaxOcclusion = false;
  27861. /**
  27862. * Controls the scale bias of the parallax mode.
  27863. */
  27864. _this.parallaxScaleBias = 0.05;
  27865. /**
  27866. * If sets to true, disables all the lights affecting the material.
  27867. */
  27868. _this.disableLighting = false;
  27869. /**
  27870. * Number of Simultaneous lights allowed on the material.
  27871. */
  27872. _this.maxSimultaneousLights = 4;
  27873. /**
  27874. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  27875. */
  27876. _this.invertNormalMapX = false;
  27877. /**
  27878. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  27879. */
  27880. _this.invertNormalMapY = false;
  27881. /**
  27882. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  27883. */
  27884. _this.twoSidedLighting = false;
  27885. _this._renderTargets = new BABYLON.SmartArray(16);
  27886. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  27887. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  27888. _this._tempColor = new BABYLON.Color3();
  27889. _this._defines = new PBRMaterialDefines();
  27890. _this._cachedDefines = new PBRMaterialDefines();
  27891. _this._myScene = null;
  27892. _this._myShadowGenerator = null;
  27893. _this._cachedDefines.BonesPerMesh = -1;
  27894. _this.getRenderTargetTextures = function () {
  27895. _this._renderTargets.reset();
  27896. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  27897. _this._renderTargets.push(_this.reflectionTexture);
  27898. }
  27899. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  27900. _this._renderTargets.push(_this.refractionTexture);
  27901. }
  27902. return _this._renderTargets;
  27903. };
  27904. return _this;
  27905. }
  27906. PBRMaterial.prototype.getClassName = function () {
  27907. return "PBRMaterial";
  27908. };
  27909. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  27910. get: function () {
  27911. return this._useLogarithmicDepth;
  27912. },
  27913. set: function (value) {
  27914. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  27915. },
  27916. enumerable: true,
  27917. configurable: true
  27918. });
  27919. PBRMaterial.prototype.needAlphaBlending = function () {
  27920. if (this.linkRefractionWithTransparency) {
  27921. return false;
  27922. }
  27923. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  27924. };
  27925. PBRMaterial.prototype.needAlphaTesting = function () {
  27926. if (this.linkRefractionWithTransparency) {
  27927. return false;
  27928. }
  27929. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  27930. };
  27931. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  27932. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  27933. };
  27934. PBRMaterial.prototype.getAlphaTestTexture = function () {
  27935. return this.albedoTexture;
  27936. };
  27937. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  27938. if (!mesh) {
  27939. return true;
  27940. }
  27941. if (this._defines.INSTANCES !== useInstances) {
  27942. return false;
  27943. }
  27944. return false;
  27945. };
  27946. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  27947. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  27948. };
  27949. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  27950. if (!useScalarInLinear) {
  27951. color.toLinearSpaceToRef(ref);
  27952. }
  27953. else {
  27954. ref.r = color.r;
  27955. ref.g = color.g;
  27956. ref.b = color.b;
  27957. }
  27958. };
  27959. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  27960. var lightIndex = 0;
  27961. var depthValuesAlreadySet = false;
  27962. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27963. var light = _a[_i];
  27964. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  27965. // GAMMA CORRECTION.
  27966. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  27967. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  27968. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  27969. if (defines["SPECULARTERM"]) {
  27970. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  27971. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  27972. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  27973. }
  27974. // Shadows
  27975. if (scene.shadowsEnabled) {
  27976. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  27977. }
  27978. lightIndex++;
  27979. if (lightIndex === maxSimultaneousLights)
  27980. break;
  27981. }
  27982. };
  27983. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  27984. if (this.isFrozen) {
  27985. if (this._wasPreviouslyReady) {
  27986. return true;
  27987. }
  27988. }
  27989. var scene = this.getScene();
  27990. var engine = scene.getEngine();
  27991. var needUVs = false;
  27992. this._defines.reset();
  27993. if (scene.lightsEnabled && !this.disableLighting) {
  27994. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this.maxSimultaneousLights);
  27995. }
  27996. if (!this.checkReadyOnEveryCall) {
  27997. if (this._renderId === scene.getRenderId()) {
  27998. if (this._checkCache(scene, mesh, useInstances)) {
  27999. return true;
  28000. }
  28001. }
  28002. }
  28003. if (scene.texturesEnabled) {
  28004. if (scene.getEngine().getCaps().textureLOD) {
  28005. this._defines.LODBASEDMICROSFURACE = true;
  28006. }
  28007. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28008. if (!this.albedoTexture.isReady()) {
  28009. return false;
  28010. }
  28011. needUVs = true;
  28012. this._defines.ALBEDO = true;
  28013. }
  28014. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  28015. if (!this.ambientTexture.isReady()) {
  28016. return false;
  28017. }
  28018. needUVs = true;
  28019. this._defines.AMBIENT = true;
  28020. this._defines.AMBIENTINGRAYSCALE = this.useAmbientInGrayScale;
  28021. }
  28022. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  28023. if (!this.opacityTexture.isReady()) {
  28024. return false;
  28025. }
  28026. needUVs = true;
  28027. this._defines.OPACITY = true;
  28028. if (this.opacityTexture.getAlphaFromRGB) {
  28029. this._defines.OPACITYRGB = true;
  28030. }
  28031. }
  28032. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  28033. if (!this.reflectionTexture.isReady()) {
  28034. return false;
  28035. }
  28036. this._defines.REFLECTION = true;
  28037. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  28038. this._defines.INVERTCUBICMAP = true;
  28039. }
  28040. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  28041. switch (this.reflectionTexture.coordinatesMode) {
  28042. case BABYLON.Texture.CUBIC_MODE:
  28043. case BABYLON.Texture.INVCUBIC_MODE:
  28044. this._defines.REFLECTIONMAP_CUBIC = true;
  28045. break;
  28046. case BABYLON.Texture.EXPLICIT_MODE:
  28047. this._defines.REFLECTIONMAP_EXPLICIT = true;
  28048. break;
  28049. case BABYLON.Texture.PLANAR_MODE:
  28050. this._defines.REFLECTIONMAP_PLANAR = true;
  28051. break;
  28052. case BABYLON.Texture.PROJECTION_MODE:
  28053. this._defines.REFLECTIONMAP_PROJECTION = true;
  28054. break;
  28055. case BABYLON.Texture.SKYBOX_MODE:
  28056. this._defines.REFLECTIONMAP_SKYBOX = true;
  28057. break;
  28058. case BABYLON.Texture.SPHERICAL_MODE:
  28059. this._defines.REFLECTIONMAP_SPHERICAL = true;
  28060. break;
  28061. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28062. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  28063. break;
  28064. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28065. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  28066. break;
  28067. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28068. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  28069. break;
  28070. }
  28071. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  28072. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  28073. if (this.reflectionTexture.isPMREM) {
  28074. this._defines.USEPMREMREFLECTION = true;
  28075. }
  28076. }
  28077. }
  28078. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  28079. if (!this.lightmapTexture.isReady()) {
  28080. return false;
  28081. }
  28082. needUVs = true;
  28083. this._defines.LIGHTMAP = true;
  28084. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  28085. }
  28086. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  28087. if (!this.emissiveTexture.isReady()) {
  28088. return false;
  28089. }
  28090. needUVs = true;
  28091. this._defines.EMISSIVE = true;
  28092. }
  28093. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  28094. if (this.metallicTexture) {
  28095. if (!this.metallicTexture.isReady()) {
  28096. return false;
  28097. }
  28098. needUVs = true;
  28099. this._defines.METALLICWORKFLOW = true;
  28100. this._defines.METALLICMAP = true;
  28101. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this.useRoughnessFromMetallicTextureAlpha;
  28102. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  28103. this._defines.METALLNESSSTOREINMETALMAPBLUE = this.useMetallnessFromMetallicTextureBlue;
  28104. this._defines.AOSTOREINMETALMAPRED = this.useAmbientOcclusionFromMetallicTextureRed;
  28105. }
  28106. else if (this.reflectivityTexture) {
  28107. if (!this.reflectivityTexture.isReady()) {
  28108. return false;
  28109. }
  28110. needUVs = true;
  28111. this._defines.REFLECTIVITY = true;
  28112. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  28113. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  28114. }
  28115. if (this.microSurfaceTexture) {
  28116. if (!this.microSurfaceTexture.isReady()) {
  28117. return false;
  28118. }
  28119. needUVs = true;
  28120. this._defines.MICROSURFACEMAP = true;
  28121. }
  28122. }
  28123. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  28124. if (!this.bumpTexture.isReady()) {
  28125. return false;
  28126. }
  28127. needUVs = true;
  28128. this._defines.BUMP = true;
  28129. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28130. this._defines.PARALLAX = true;
  28131. if (this.useParallaxOcclusion) {
  28132. this._defines.PARALLAXOCCLUSION = true;
  28133. }
  28134. }
  28135. if (this.invertNormalMapX) {
  28136. this._defines.INVERTNORMALMAPX = true;
  28137. }
  28138. if (this.invertNormalMapY) {
  28139. this._defines.INVERTNORMALMAPY = true;
  28140. }
  28141. if (scene._mirroredCameraPosition) {
  28142. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  28143. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  28144. }
  28145. }
  28146. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  28147. if (!this.refractionTexture.isReady()) {
  28148. return false;
  28149. }
  28150. needUVs = true;
  28151. this._defines.REFRACTION = true;
  28152. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  28153. if (this.linkRefractionWithTransparency) {
  28154. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  28155. }
  28156. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  28157. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  28158. if (this.refractionTexture.isPMREM) {
  28159. this._defines.USEPMREMREFRACTION = true;
  28160. }
  28161. }
  28162. }
  28163. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  28164. if (!this.cameraColorGradingTexture.isReady()) {
  28165. return false;
  28166. }
  28167. this._defines.CAMERACOLORGRADING = true;
  28168. }
  28169. if (!this.backFaceCulling && this.twoSidedLighting) {
  28170. this._defines.TWOSIDEDLIGHTING = true;
  28171. }
  28172. }
  28173. // Effect
  28174. if (scene.clipPlane) {
  28175. this._defines.CLIPPLANE = true;
  28176. }
  28177. if (engine.getAlphaTesting()) {
  28178. this._defines.ALPHATEST = true;
  28179. }
  28180. if (this._shouldUseAlphaFromAlbedoTexture()) {
  28181. this._defines.ALPHAFROMALBEDO = true;
  28182. }
  28183. if (this.useEmissiveAsIllumination) {
  28184. this._defines.EMISSIVEASILLUMINATION = true;
  28185. }
  28186. if (this.linkEmissiveWithAlbedo) {
  28187. this._defines.LINKEMISSIVEWITHALBEDO = true;
  28188. }
  28189. if (this.useLogarithmicDepth) {
  28190. this._defines.LOGARITHMICDEPTH = true;
  28191. }
  28192. if (this.cameraContrast != 1) {
  28193. this._defines.CAMERACONTRAST = true;
  28194. }
  28195. if (this.cameraExposure != 1) {
  28196. this._defines.CAMERATONEMAP = true;
  28197. }
  28198. if (this.cameraColorCurves) {
  28199. this._defines.CAMERACOLORCURVES = true;
  28200. }
  28201. if (this.overloadedShadeIntensity != 1 ||
  28202. this.overloadedShadowIntensity != 1) {
  28203. this._defines.OVERLOADEDSHADOWVALUES = true;
  28204. }
  28205. if (this.overloadedMicroSurfaceIntensity > 0 ||
  28206. this.overloadedEmissiveIntensity > 0 ||
  28207. this.overloadedReflectivityIntensity > 0 ||
  28208. this.overloadedAlbedoIntensity > 0 ||
  28209. this.overloadedAmbientIntensity > 0 ||
  28210. this.overloadedReflectionIntensity > 0) {
  28211. this._defines.OVERLOADEDVALUES = true;
  28212. }
  28213. // Point size
  28214. if (this.pointsCloud || scene.forcePointsCloud) {
  28215. this._defines.POINTSIZE = true;
  28216. }
  28217. // Fog
  28218. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28219. this._defines.FOG = true;
  28220. }
  28221. if (BABYLON.StandardMaterial.FresnelEnabled) {
  28222. // Fresnel
  28223. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  28224. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28225. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  28226. this._defines.OPACITYFRESNEL = true;
  28227. }
  28228. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28229. this._defines.EMISSIVEFRESNEL = true;
  28230. }
  28231. this._defines.FRESNEL = true;
  28232. }
  28233. }
  28234. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  28235. this._defines.SPECULAROVERALPHA = true;
  28236. }
  28237. if (this.usePhysicalLightFalloff) {
  28238. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  28239. }
  28240. if (this.useRadianceOverAlpha) {
  28241. this._defines.RADIANCEOVERALPHA = true;
  28242. }
  28243. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  28244. this._defines.METALLICWORKFLOW = true;
  28245. }
  28246. // Attribs
  28247. if (mesh) {
  28248. if (!mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28249. mesh.createNormals(true);
  28250. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  28251. }
  28252. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28253. this._defines.NORMAL = true;
  28254. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28255. this._defines.TANGENT = true;
  28256. }
  28257. }
  28258. if (needUVs) {
  28259. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28260. this._defines.UV1 = true;
  28261. }
  28262. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28263. this._defines.UV2 = true;
  28264. }
  28265. }
  28266. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28267. this._defines.VERTEXCOLOR = true;
  28268. if (mesh.hasVertexAlpha) {
  28269. this._defines.VERTEXALPHA = true;
  28270. }
  28271. }
  28272. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  28273. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  28274. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  28275. }
  28276. // Instances
  28277. if (useInstances) {
  28278. this._defines.INSTANCES = true;
  28279. }
  28280. if (mesh.morphTargetManager) {
  28281. var manager = mesh.morphTargetManager;
  28282. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  28283. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  28284. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  28285. }
  28286. }
  28287. // Get correct effect
  28288. if (!this._defines.isEqual(this._cachedDefines)) {
  28289. this._defines.cloneTo(this._cachedDefines);
  28290. scene.resetCachedMaterial();
  28291. // Fallbacks
  28292. var fallbacks = new BABYLON.EffectFallbacks();
  28293. if (this._defines.REFLECTION) {
  28294. fallbacks.addFallback(0, "REFLECTION");
  28295. }
  28296. if (this._defines.REFRACTION) {
  28297. fallbacks.addFallback(0, "REFRACTION");
  28298. }
  28299. if (this._defines.REFLECTIVITY) {
  28300. fallbacks.addFallback(0, "REFLECTIVITY");
  28301. }
  28302. if (this._defines.BUMP) {
  28303. fallbacks.addFallback(0, "BUMP");
  28304. }
  28305. if (this._defines.PARALLAX) {
  28306. fallbacks.addFallback(1, "PARALLAX");
  28307. }
  28308. if (this._defines.PARALLAXOCCLUSION) {
  28309. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  28310. }
  28311. if (this._defines.SPECULAROVERALPHA) {
  28312. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  28313. }
  28314. if (this._defines.FOG) {
  28315. fallbacks.addFallback(1, "FOG");
  28316. }
  28317. if (this._defines.POINTSIZE) {
  28318. fallbacks.addFallback(0, "POINTSIZE");
  28319. }
  28320. if (this._defines.LOGARITHMICDEPTH) {
  28321. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  28322. }
  28323. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  28324. if (this._defines.SPECULARTERM) {
  28325. fallbacks.addFallback(0, "SPECULARTERM");
  28326. }
  28327. if (this._defines.OPACITYFRESNEL) {
  28328. fallbacks.addFallback(1, "OPACITYFRESNEL");
  28329. }
  28330. if (this._defines.EMISSIVEFRESNEL) {
  28331. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  28332. }
  28333. if (this._defines.FRESNEL) {
  28334. fallbacks.addFallback(3, "FRESNEL");
  28335. }
  28336. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  28337. fallbacks.addCPUSkinningFallback(0, mesh);
  28338. }
  28339. //Attributes
  28340. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28341. if (this._defines.NORMAL) {
  28342. attribs.push(BABYLON.VertexBuffer.NormalKind);
  28343. }
  28344. if (this._defines.TANGENT) {
  28345. attribs.push(BABYLON.VertexBuffer.TangentKind);
  28346. }
  28347. if (this._defines.UV1) {
  28348. attribs.push(BABYLON.VertexBuffer.UVKind);
  28349. }
  28350. if (this._defines.UV2) {
  28351. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28352. }
  28353. if (this._defines.VERTEXCOLOR) {
  28354. attribs.push(BABYLON.VertexBuffer.ColorKind);
  28355. }
  28356. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  28357. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  28358. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  28359. // Legacy browser patch
  28360. var join = this._defines.toString();
  28361. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  28362. "vFogInfos", "vFogColor", "pointSize",
  28363. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  28364. "mBones",
  28365. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  28366. "depthValues",
  28367. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  28368. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  28369. "logarithmicDepthConstant",
  28370. "vSphericalX", "vSphericalY", "vSphericalZ",
  28371. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  28372. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  28373. "vMicrosurfaceTextureLods",
  28374. "vCameraInfos"
  28375. ];
  28376. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  28377. if (this._defines.CAMERACOLORCURVES) {
  28378. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  28379. }
  28380. if (this._defines.CAMERACOLORGRADING) {
  28381. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  28382. }
  28383. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  28384. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS });
  28385. }
  28386. if (!this._effect.isReady()) {
  28387. return false;
  28388. }
  28389. this._renderId = scene.getRenderId();
  28390. this._wasPreviouslyReady = true;
  28391. return true;
  28392. };
  28393. PBRMaterial.prototype.unbind = function () {
  28394. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  28395. this._effect.setTexture("reflection2DSampler", null);
  28396. }
  28397. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  28398. this._effect.setTexture("refraction2DSampler", null);
  28399. }
  28400. _super.prototype.unbind.call(this);
  28401. };
  28402. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28403. this._effect.setMatrix("world", world);
  28404. };
  28405. PBRMaterial.prototype.bind = function (world, mesh) {
  28406. this._myScene = this.getScene();
  28407. // Matrices
  28408. this.bindOnlyWorldMatrix(world);
  28409. // Bones
  28410. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  28411. if (this._myScene.getCachedMaterial() !== this) {
  28412. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  28413. if (BABYLON.StandardMaterial.FresnelEnabled) {
  28414. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  28415. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  28416. }
  28417. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28418. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  28419. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  28420. }
  28421. }
  28422. // Textures
  28423. if (this._myScene.texturesEnabled) {
  28424. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28425. this._effect.setTexture("albedoSampler", this.albedoTexture);
  28426. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  28427. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  28428. }
  28429. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  28430. this._effect.setTexture("ambientSampler", this.ambientTexture);
  28431. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  28432. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  28433. }
  28434. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  28435. this._effect.setTexture("opacitySampler", this.opacityTexture);
  28436. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  28437. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  28438. }
  28439. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  28440. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  28441. if (this.reflectionTexture.isCube) {
  28442. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  28443. }
  28444. else {
  28445. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  28446. }
  28447. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  28448. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  28449. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  28450. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  28451. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  28452. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  28453. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  28454. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  28455. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  28456. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  28457. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  28458. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  28459. }
  28460. }
  28461. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  28462. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  28463. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  28464. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  28465. }
  28466. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  28467. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  28468. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  28469. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  28470. }
  28471. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  28472. if (this.metallicTexture) {
  28473. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  28474. this._effect.setFloat3("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level, this.ambientTextureStrength);
  28475. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  28476. }
  28477. else if (this.reflectivityTexture) {
  28478. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  28479. this._effect.setFloat3("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level, 1.0);
  28480. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  28481. }
  28482. if (this.microSurfaceTexture) {
  28483. this._effect.setTexture("microSurfaceSampler", this.microSurfaceTexture);
  28484. this._effect.setFloat2("vMicroSurfaceSamplerInfos", this.microSurfaceTexture.coordinatesIndex, this.microSurfaceTexture.level);
  28485. this._effect.setMatrix("microSurfaceSamplerMatrix", this.microSurfaceTexture.getTextureMatrix());
  28486. }
  28487. }
  28488. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  28489. this._effect.setTexture("bumpSampler", this.bumpTexture);
  28490. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  28491. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  28492. }
  28493. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  28494. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  28495. var depth = 1.0;
  28496. if (this.refractionTexture.isCube) {
  28497. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  28498. }
  28499. else {
  28500. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  28501. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  28502. if (this.refractionTexture.depth) {
  28503. depth = this.refractionTexture.depth;
  28504. }
  28505. }
  28506. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  28507. }
  28508. if ((this.reflectionTexture || this.refractionTexture)) {
  28509. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  28510. }
  28511. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  28512. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  28513. }
  28514. }
  28515. // Clip plane
  28516. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  28517. // Point size
  28518. if (this.pointsCloud) {
  28519. this._effect.setFloat("pointSize", this.pointSize);
  28520. }
  28521. // Colors
  28522. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  28523. if (this._defines.METALLICWORKFLOW) {
  28524. PBRMaterial._scaledReflectivity.r = (this.metallic === undefined || this.metallic === null) ? 1 : this.metallic;
  28525. PBRMaterial._scaledReflectivity.g = (this.roughness === undefined || this.roughness === null) ? 1 : this.roughness;
  28526. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  28527. }
  28528. else {
  28529. // GAMMA CORRECTION.
  28530. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  28531. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  28532. }
  28533. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  28534. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  28535. // GAMMA CORRECTION.
  28536. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  28537. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  28538. // GAMMA CORRECTION.
  28539. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  28540. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  28541. }
  28542. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  28543. // GAMMA CORRECTION.
  28544. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  28545. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  28546. // Lights
  28547. if (this._myScene.lightsEnabled && !this.disableLighting) {
  28548. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  28549. }
  28550. // View
  28551. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  28552. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  28553. }
  28554. // Fog
  28555. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  28556. // Morph targets
  28557. if (this._defines.NUM_MORPH_INFLUENCERS) {
  28558. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  28559. }
  28560. this._lightingInfos.x = this.directIntensity;
  28561. this._lightingInfos.y = this.emissiveIntensity;
  28562. this._lightingInfos.z = this.environmentIntensity;
  28563. this._lightingInfos.w = this.specularIntensity;
  28564. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  28565. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  28566. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  28567. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  28568. this._cameraInfos.x = this.cameraExposure;
  28569. this._cameraInfos.y = this.cameraContrast;
  28570. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  28571. if (this.cameraColorCurves) {
  28572. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  28573. }
  28574. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  28575. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  28576. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  28577. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  28578. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  28579. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  28580. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  28581. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  28582. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  28583. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  28584. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  28585. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  28586. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  28587. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  28588. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  28589. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  28590. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  28591. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  28592. // Log. depth
  28593. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  28594. }
  28595. this._afterBind(mesh);
  28596. this._myScene = null;
  28597. };
  28598. PBRMaterial.prototype.getAnimatables = function () {
  28599. var results = [];
  28600. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  28601. results.push(this.albedoTexture);
  28602. }
  28603. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  28604. results.push(this.ambientTexture);
  28605. }
  28606. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  28607. results.push(this.opacityTexture);
  28608. }
  28609. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  28610. results.push(this.reflectionTexture);
  28611. }
  28612. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  28613. results.push(this.emissiveTexture);
  28614. }
  28615. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  28616. results.push(this.metallicTexture);
  28617. }
  28618. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  28619. results.push(this.reflectivityTexture);
  28620. }
  28621. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  28622. results.push(this.bumpTexture);
  28623. }
  28624. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  28625. results.push(this.lightmapTexture);
  28626. }
  28627. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  28628. results.push(this.refractionTexture);
  28629. }
  28630. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  28631. results.push(this.cameraColorGradingTexture);
  28632. }
  28633. return results;
  28634. };
  28635. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28636. if (forceDisposeTextures) {
  28637. if (this.albedoTexture) {
  28638. this.albedoTexture.dispose();
  28639. }
  28640. if (this.ambientTexture) {
  28641. this.ambientTexture.dispose();
  28642. }
  28643. if (this.opacityTexture) {
  28644. this.opacityTexture.dispose();
  28645. }
  28646. if (this.reflectionTexture) {
  28647. this.reflectionTexture.dispose();
  28648. }
  28649. if (this.emissiveTexture) {
  28650. this.emissiveTexture.dispose();
  28651. }
  28652. if (this.metallicTexture) {
  28653. this.metallicTexture.dispose();
  28654. }
  28655. if (this.reflectivityTexture) {
  28656. this.reflectivityTexture.dispose();
  28657. }
  28658. if (this.bumpTexture) {
  28659. this.bumpTexture.dispose();
  28660. }
  28661. if (this.lightmapTexture) {
  28662. this.lightmapTexture.dispose();
  28663. }
  28664. if (this.refractionTexture) {
  28665. this.refractionTexture.dispose();
  28666. }
  28667. if (this.cameraColorGradingTexture) {
  28668. this.cameraColorGradingTexture.dispose();
  28669. }
  28670. }
  28671. this._renderTargets.dispose();
  28672. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  28673. };
  28674. PBRMaterial.prototype.clone = function (name) {
  28675. var _this = this;
  28676. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  28677. };
  28678. PBRMaterial.prototype.serialize = function () {
  28679. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  28680. serializationObject.customType = "BABYLON.PBRMaterial";
  28681. return serializationObject;
  28682. };
  28683. // Statics
  28684. PBRMaterial.Parse = function (source, scene, rootUrl) {
  28685. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  28686. };
  28687. return PBRMaterial;
  28688. }(BABYLON.Material));
  28689. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  28690. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  28691. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  28692. PBRMaterial._scaledReflection = new BABYLON.Color3();
  28693. __decorate([
  28694. BABYLON.serialize()
  28695. ], PBRMaterial.prototype, "directIntensity", void 0);
  28696. __decorate([
  28697. BABYLON.serialize()
  28698. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  28699. __decorate([
  28700. BABYLON.serialize()
  28701. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  28702. __decorate([
  28703. BABYLON.serialize()
  28704. ], PBRMaterial.prototype, "specularIntensity", void 0);
  28705. __decorate([
  28706. BABYLON.serialize()
  28707. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  28708. __decorate([
  28709. BABYLON.serialize()
  28710. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  28711. __decorate([
  28712. BABYLON.serialize()
  28713. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  28714. __decorate([
  28715. BABYLON.serialize()
  28716. ], PBRMaterial.prototype, "cameraExposure", void 0);
  28717. __decorate([
  28718. BABYLON.serialize()
  28719. ], PBRMaterial.prototype, "cameraContrast", void 0);
  28720. __decorate([
  28721. BABYLON.serializeAsTexture()
  28722. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  28723. __decorate([
  28724. BABYLON.serializeAsColorCurves()
  28725. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  28726. __decorate([
  28727. BABYLON.serializeAsColor3()
  28728. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  28729. __decorate([
  28730. BABYLON.serialize()
  28731. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  28732. __decorate([
  28733. BABYLON.serializeAsColor3()
  28734. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  28735. __decorate([
  28736. BABYLON.serialize()
  28737. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  28738. __decorate([
  28739. BABYLON.serializeAsColor3()
  28740. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  28741. __decorate([
  28742. BABYLON.serialize()
  28743. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  28744. __decorate([
  28745. BABYLON.serializeAsColor3()
  28746. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  28747. __decorate([
  28748. BABYLON.serialize()
  28749. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  28750. __decorate([
  28751. BABYLON.serializeAsColor3()
  28752. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  28753. __decorate([
  28754. BABYLON.serialize()
  28755. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  28756. __decorate([
  28757. BABYLON.serialize()
  28758. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  28759. __decorate([
  28760. BABYLON.serialize()
  28761. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  28762. __decorate([
  28763. BABYLON.serializeAsTexture()
  28764. ], PBRMaterial.prototype, "albedoTexture", void 0);
  28765. __decorate([
  28766. BABYLON.serializeAsTexture()
  28767. ], PBRMaterial.prototype, "ambientTexture", void 0);
  28768. __decorate([
  28769. BABYLON.serialize()
  28770. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  28771. __decorate([
  28772. BABYLON.serializeAsTexture()
  28773. ], PBRMaterial.prototype, "opacityTexture", void 0);
  28774. __decorate([
  28775. BABYLON.serializeAsTexture()
  28776. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  28777. __decorate([
  28778. BABYLON.serializeAsTexture()
  28779. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  28780. __decorate([
  28781. BABYLON.serializeAsTexture()
  28782. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  28783. __decorate([
  28784. BABYLON.serializeAsTexture()
  28785. ], PBRMaterial.prototype, "metallicTexture", void 0);
  28786. __decorate([
  28787. BABYLON.serialize()
  28788. ], PBRMaterial.prototype, "metallic", void 0);
  28789. __decorate([
  28790. BABYLON.serialize()
  28791. ], PBRMaterial.prototype, "roughness", void 0);
  28792. __decorate([
  28793. BABYLON.serializeAsTexture()
  28794. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  28795. __decorate([
  28796. BABYLON.serializeAsTexture()
  28797. ], PBRMaterial.prototype, "bumpTexture", void 0);
  28798. __decorate([
  28799. BABYLON.serializeAsTexture()
  28800. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  28801. __decorate([
  28802. BABYLON.serializeAsTexture()
  28803. ], PBRMaterial.prototype, "refractionTexture", void 0);
  28804. __decorate([
  28805. BABYLON.serializeAsColor3("ambient")
  28806. ], PBRMaterial.prototype, "ambientColor", void 0);
  28807. __decorate([
  28808. BABYLON.serializeAsColor3("albedo")
  28809. ], PBRMaterial.prototype, "albedoColor", void 0);
  28810. __decorate([
  28811. BABYLON.serializeAsColor3("reflectivity")
  28812. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  28813. __decorate([
  28814. BABYLON.serializeAsColor3("reflection")
  28815. ], PBRMaterial.prototype, "reflectionColor", void 0);
  28816. __decorate([
  28817. BABYLON.serializeAsColor3("emissive")
  28818. ], PBRMaterial.prototype, "emissiveColor", void 0);
  28819. __decorate([
  28820. BABYLON.serialize()
  28821. ], PBRMaterial.prototype, "microSurface", void 0);
  28822. __decorate([
  28823. BABYLON.serialize()
  28824. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  28825. __decorate([
  28826. BABYLON.serialize()
  28827. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  28828. __decorate([
  28829. BABYLON.serializeAsFresnelParameters()
  28830. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  28831. __decorate([
  28832. BABYLON.serializeAsFresnelParameters()
  28833. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  28834. __decorate([
  28835. BABYLON.serialize()
  28836. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  28837. __decorate([
  28838. BABYLON.serialize()
  28839. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  28840. __decorate([
  28841. BABYLON.serialize()
  28842. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  28843. __decorate([
  28844. BABYLON.serialize()
  28845. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  28846. __decorate([
  28847. BABYLON.serialize()
  28848. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  28849. __decorate([
  28850. BABYLON.serialize()
  28851. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  28852. __decorate([
  28853. BABYLON.serialize()
  28854. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  28855. __decorate([
  28856. BABYLON.serialize()
  28857. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  28858. __decorate([
  28859. BABYLON.serialize()
  28860. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  28861. __decorate([
  28862. BABYLON.serialize()
  28863. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  28864. __decorate([
  28865. BABYLON.serialize()
  28866. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  28867. __decorate([
  28868. BABYLON.serialize()
  28869. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  28870. __decorate([
  28871. BABYLON.serialize()
  28872. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  28873. __decorate([
  28874. BABYLON.serialize()
  28875. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  28876. __decorate([
  28877. BABYLON.serialize()
  28878. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  28879. __decorate([
  28880. BABYLON.serialize()
  28881. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  28882. __decorate([
  28883. BABYLON.serialize()
  28884. ], PBRMaterial.prototype, "useParallax", void 0);
  28885. __decorate([
  28886. BABYLON.serialize()
  28887. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  28888. __decorate([
  28889. BABYLON.serialize()
  28890. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  28891. __decorate([
  28892. BABYLON.serialize()
  28893. ], PBRMaterial.prototype, "disableLighting", void 0);
  28894. __decorate([
  28895. BABYLON.serialize()
  28896. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  28897. __decorate([
  28898. BABYLON.serialize()
  28899. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  28900. __decorate([
  28901. BABYLON.serialize()
  28902. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  28903. __decorate([
  28904. BABYLON.serialize()
  28905. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  28906. __decorate([
  28907. BABYLON.serialize()
  28908. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  28909. BABYLON.PBRMaterial = PBRMaterial;
  28910. })(BABYLON || (BABYLON = {}));
  28911. //# sourceMappingURL=babylon.pbrMaterial.js.map
  28912. var BABYLON;
  28913. (function (BABYLON) {
  28914. BABYLON.CameraInputTypes = {};
  28915. var CameraInputsManager = (function () {
  28916. function CameraInputsManager(camera) {
  28917. this.attached = {};
  28918. this.camera = camera;
  28919. this.checkInputs = function () { };
  28920. }
  28921. CameraInputsManager.prototype.add = function (input) {
  28922. var type = input.getSimpleName();
  28923. if (this.attached[type]) {
  28924. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  28925. return;
  28926. }
  28927. this.attached[type] = input;
  28928. input.camera = this.camera;
  28929. //for checkInputs, we are dynamically creating a function
  28930. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  28931. if (input.checkInputs) {
  28932. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  28933. }
  28934. if (this.attachedElement) {
  28935. input.attachControl(this.attachedElement);
  28936. }
  28937. };
  28938. CameraInputsManager.prototype.remove = function (inputToRemove) {
  28939. for (var cam in this.attached) {
  28940. var input = this.attached[cam];
  28941. if (input === inputToRemove) {
  28942. input.detachControl(this.attachedElement);
  28943. delete this.attached[cam];
  28944. this.rebuildInputCheck();
  28945. }
  28946. }
  28947. };
  28948. CameraInputsManager.prototype.removeByType = function (inputType) {
  28949. for (var cam in this.attached) {
  28950. var input = this.attached[cam];
  28951. if (input.getTypeName() === inputType) {
  28952. input.detachControl(this.attachedElement);
  28953. delete this.attached[cam];
  28954. this.rebuildInputCheck();
  28955. }
  28956. }
  28957. };
  28958. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  28959. var current = this.checkInputs;
  28960. return function () {
  28961. current();
  28962. fn();
  28963. };
  28964. };
  28965. CameraInputsManager.prototype.attachInput = function (input) {
  28966. input.attachControl(this.attachedElement, this.noPreventDefault);
  28967. };
  28968. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  28969. if (this.attachedElement) {
  28970. return;
  28971. }
  28972. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  28973. this.attachedElement = element;
  28974. this.noPreventDefault = noPreventDefault;
  28975. for (var cam in this.attached) {
  28976. var input = this.attached[cam];
  28977. this.attached[cam].attachControl(element, noPreventDefault);
  28978. }
  28979. };
  28980. CameraInputsManager.prototype.detachElement = function (element) {
  28981. if (this.attachedElement !== element) {
  28982. return;
  28983. }
  28984. for (var cam in this.attached) {
  28985. var input = this.attached[cam];
  28986. this.attached[cam].detachControl(element);
  28987. }
  28988. this.attachedElement = null;
  28989. };
  28990. CameraInputsManager.prototype.rebuildInputCheck = function () {
  28991. this.checkInputs = function () { };
  28992. for (var cam in this.attached) {
  28993. var input = this.attached[cam];
  28994. if (input.checkInputs) {
  28995. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  28996. }
  28997. }
  28998. };
  28999. CameraInputsManager.prototype.clear = function () {
  29000. if (this.attachedElement) {
  29001. this.detachElement(this.attachedElement);
  29002. }
  29003. this.attached = {};
  29004. this.attachedElement = null;
  29005. this.checkInputs = function () { };
  29006. };
  29007. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  29008. var inputs = {};
  29009. for (var cam in this.attached) {
  29010. var input = this.attached[cam];
  29011. var res = BABYLON.SerializationHelper.Serialize(input);
  29012. inputs[input.getTypeName()] = res;
  29013. }
  29014. serializedCamera.inputsmgr = inputs;
  29015. };
  29016. CameraInputsManager.prototype.parse = function (parsedCamera) {
  29017. var parsedInputs = parsedCamera.inputsmgr;
  29018. if (parsedInputs) {
  29019. this.clear();
  29020. for (var n in parsedInputs) {
  29021. var construct = BABYLON.CameraInputTypes[n];
  29022. if (construct) {
  29023. var parsedinput = parsedInputs[n];
  29024. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  29025. this.add(input);
  29026. }
  29027. }
  29028. }
  29029. else {
  29030. //2016-03-08 this part is for managing backward compatibility
  29031. for (var n in this.attached) {
  29032. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  29033. if (construct) {
  29034. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  29035. this.remove(this.attached[n]);
  29036. this.add(input);
  29037. }
  29038. }
  29039. }
  29040. };
  29041. return CameraInputsManager;
  29042. }());
  29043. BABYLON.CameraInputsManager = CameraInputsManager;
  29044. })(BABYLON || (BABYLON = {}));
  29045. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  29046. var BABYLON;
  29047. (function (BABYLON) {
  29048. var FreeCameraMouseInput = (function () {
  29049. function FreeCameraMouseInput(touchEnabled) {
  29050. if (touchEnabled === void 0) { touchEnabled = true; }
  29051. this.touchEnabled = touchEnabled;
  29052. this.buttons = [0, 1, 2];
  29053. this.angularSensibility = 2000.0;
  29054. }
  29055. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  29056. var _this = this;
  29057. var engine = this.camera.getEngine();
  29058. if (!this._pointerInput) {
  29059. this._pointerInput = function (p, s) {
  29060. var evt = p.event;
  29061. if (!_this.touchEnabled && evt.pointerType === "touch") {
  29062. return;
  29063. }
  29064. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  29065. return;
  29066. }
  29067. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  29068. try {
  29069. evt.srcElement.setPointerCapture(evt.pointerId);
  29070. }
  29071. catch (e) {
  29072. //Nothing to do with the error. Execution will continue.
  29073. }
  29074. _this.previousPosition = {
  29075. x: evt.clientX,
  29076. y: evt.clientY
  29077. };
  29078. if (!noPreventDefault) {
  29079. evt.preventDefault();
  29080. element.focus();
  29081. }
  29082. }
  29083. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  29084. try {
  29085. evt.srcElement.releasePointerCapture(evt.pointerId);
  29086. }
  29087. catch (e) {
  29088. //Nothing to do with the error.
  29089. }
  29090. _this.previousPosition = null;
  29091. if (!noPreventDefault) {
  29092. evt.preventDefault();
  29093. }
  29094. }
  29095. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  29096. if (!_this.previousPosition || engine.isPointerLock) {
  29097. return;
  29098. }
  29099. var offsetX = evt.clientX - _this.previousPosition.x;
  29100. var offsetY = evt.clientY - _this.previousPosition.y;
  29101. if (_this.camera.getScene().useRightHandedSystem) {
  29102. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  29103. }
  29104. else {
  29105. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  29106. }
  29107. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  29108. _this.previousPosition = {
  29109. x: evt.clientX,
  29110. y: evt.clientY
  29111. };
  29112. if (!noPreventDefault) {
  29113. evt.preventDefault();
  29114. }
  29115. }
  29116. };
  29117. }
  29118. this._onMouseMove = function (evt) {
  29119. if (!engine.isPointerLock) {
  29120. return;
  29121. }
  29122. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  29123. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  29124. if (_this.camera.getScene().useRightHandedSystem) {
  29125. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  29126. }
  29127. else {
  29128. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  29129. }
  29130. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  29131. _this.previousPosition = null;
  29132. if (!noPreventDefault) {
  29133. evt.preventDefault();
  29134. }
  29135. };
  29136. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  29137. element.addEventListener("mousemove", this._onMouseMove, false);
  29138. };
  29139. FreeCameraMouseInput.prototype.detachControl = function (element) {
  29140. if (this._observer && element) {
  29141. this.camera.getScene().onPointerObservable.remove(this._observer);
  29142. element.removeEventListener("mousemove", this._onMouseMove);
  29143. this._observer = null;
  29144. this._onMouseMove = null;
  29145. this.previousPosition = null;
  29146. }
  29147. };
  29148. FreeCameraMouseInput.prototype.getTypeName = function () {
  29149. return "FreeCameraMouseInput";
  29150. };
  29151. FreeCameraMouseInput.prototype.getSimpleName = function () {
  29152. return "mouse";
  29153. };
  29154. return FreeCameraMouseInput;
  29155. }());
  29156. __decorate([
  29157. BABYLON.serialize()
  29158. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  29159. __decorate([
  29160. BABYLON.serialize()
  29161. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  29162. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  29163. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  29164. })(BABYLON || (BABYLON = {}));
  29165. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  29166. var BABYLON;
  29167. (function (BABYLON) {
  29168. var FreeCameraKeyboardMoveInput = (function () {
  29169. function FreeCameraKeyboardMoveInput() {
  29170. this._keys = [];
  29171. this.keysUp = [38];
  29172. this.keysDown = [40];
  29173. this.keysLeft = [37];
  29174. this.keysRight = [39];
  29175. }
  29176. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  29177. var _this = this;
  29178. if (!this._onKeyDown) {
  29179. element.tabIndex = 1;
  29180. this._onKeyDown = function (evt) {
  29181. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29182. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29183. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  29184. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  29185. var index = _this._keys.indexOf(evt.keyCode);
  29186. if (index === -1) {
  29187. _this._keys.push(evt.keyCode);
  29188. }
  29189. if (!noPreventDefault) {
  29190. evt.preventDefault();
  29191. }
  29192. }
  29193. };
  29194. this._onKeyUp = function (evt) {
  29195. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29196. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29197. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  29198. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  29199. var index = _this._keys.indexOf(evt.keyCode);
  29200. if (index >= 0) {
  29201. _this._keys.splice(index, 1);
  29202. }
  29203. if (!noPreventDefault) {
  29204. evt.preventDefault();
  29205. }
  29206. }
  29207. };
  29208. element.addEventListener("keydown", this._onKeyDown, false);
  29209. element.addEventListener("keyup", this._onKeyUp, false);
  29210. BABYLON.Tools.RegisterTopRootEvents([
  29211. { name: "blur", handler: this._onLostFocus }
  29212. ]);
  29213. }
  29214. };
  29215. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  29216. if (this._onKeyDown) {
  29217. element.removeEventListener("keydown", this._onKeyDown);
  29218. element.removeEventListener("keyup", this._onKeyUp);
  29219. BABYLON.Tools.UnregisterTopRootEvents([
  29220. { name: "blur", handler: this._onLostFocus }
  29221. ]);
  29222. this._keys = [];
  29223. this._onKeyDown = null;
  29224. this._onKeyUp = null;
  29225. }
  29226. };
  29227. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  29228. if (this._onKeyDown) {
  29229. var camera = this.camera;
  29230. // Keyboard
  29231. for (var index = 0; index < this._keys.length; index++) {
  29232. var keyCode = this._keys[index];
  29233. var speed = camera._computeLocalCameraSpeed();
  29234. if (this.keysLeft.indexOf(keyCode) !== -1) {
  29235. camera._localDirection.copyFromFloats(-speed, 0, 0);
  29236. }
  29237. else if (this.keysUp.indexOf(keyCode) !== -1) {
  29238. camera._localDirection.copyFromFloats(0, 0, speed);
  29239. }
  29240. else if (this.keysRight.indexOf(keyCode) !== -1) {
  29241. camera._localDirection.copyFromFloats(speed, 0, 0);
  29242. }
  29243. else if (this.keysDown.indexOf(keyCode) !== -1) {
  29244. camera._localDirection.copyFromFloats(0, 0, -speed);
  29245. }
  29246. if (camera.getScene().useRightHandedSystem) {
  29247. camera._localDirection.z *= -1;
  29248. }
  29249. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  29250. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  29251. camera.cameraDirection.addInPlace(camera._transformedDirection);
  29252. }
  29253. }
  29254. };
  29255. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  29256. return "FreeCameraKeyboardMoveInput";
  29257. };
  29258. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  29259. this._keys = [];
  29260. };
  29261. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  29262. return "keyboard";
  29263. };
  29264. return FreeCameraKeyboardMoveInput;
  29265. }());
  29266. __decorate([
  29267. BABYLON.serialize()
  29268. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  29269. __decorate([
  29270. BABYLON.serialize()
  29271. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  29272. __decorate([
  29273. BABYLON.serialize()
  29274. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  29275. __decorate([
  29276. BABYLON.serialize()
  29277. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  29278. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  29279. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  29280. })(BABYLON || (BABYLON = {}));
  29281. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  29282. var BABYLON;
  29283. (function (BABYLON) {
  29284. var FreeCameraInputsManager = (function (_super) {
  29285. __extends(FreeCameraInputsManager, _super);
  29286. function FreeCameraInputsManager(camera) {
  29287. return _super.call(this, camera) || this;
  29288. }
  29289. FreeCameraInputsManager.prototype.addKeyboard = function () {
  29290. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  29291. return this;
  29292. };
  29293. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  29294. if (touchEnabled === void 0) { touchEnabled = true; }
  29295. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  29296. return this;
  29297. };
  29298. FreeCameraInputsManager.prototype.addGamepad = function () {
  29299. this.add(new BABYLON.FreeCameraGamepadInput());
  29300. return this;
  29301. };
  29302. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  29303. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  29304. return this;
  29305. };
  29306. FreeCameraInputsManager.prototype.addTouch = function () {
  29307. this.add(new BABYLON.FreeCameraTouchInput());
  29308. return this;
  29309. };
  29310. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  29311. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  29312. return this;
  29313. };
  29314. return FreeCameraInputsManager;
  29315. }(BABYLON.CameraInputsManager));
  29316. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  29317. })(BABYLON || (BABYLON = {}));
  29318. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  29319. /// <reference path="babylon.camera.ts" />
  29320. var BABYLON;
  29321. (function (BABYLON) {
  29322. var TargetCamera = (function (_super) {
  29323. __extends(TargetCamera, _super);
  29324. function TargetCamera(name, position, scene) {
  29325. var _this = _super.call(this, name, position, scene) || this;
  29326. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  29327. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  29328. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  29329. _this.speed = 2.0;
  29330. _this.noRotationConstraint = false;
  29331. _this.lockedTarget = null;
  29332. _this._currentTarget = BABYLON.Vector3.Zero();
  29333. _this._viewMatrix = BABYLON.Matrix.Zero();
  29334. _this._camMatrix = BABYLON.Matrix.Zero();
  29335. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  29336. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  29337. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  29338. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  29339. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  29340. _this._lookAtTemp = BABYLON.Matrix.Zero();
  29341. _this._tempMatrix = BABYLON.Matrix.Zero();
  29342. return _this;
  29343. }
  29344. TargetCamera.prototype.getFrontPosition = function (distance) {
  29345. var direction = this.getTarget().subtract(this.position);
  29346. direction.normalize();
  29347. direction.scaleInPlace(distance);
  29348. return this.globalPosition.add(direction);
  29349. };
  29350. TargetCamera.prototype._getLockedTargetPosition = function () {
  29351. if (!this.lockedTarget) {
  29352. return null;
  29353. }
  29354. if (this.lockedTarget.absolutePosition) {
  29355. this.lockedTarget.computeWorldMatrix();
  29356. }
  29357. return this.lockedTarget.absolutePosition || this.lockedTarget;
  29358. };
  29359. // Cache
  29360. TargetCamera.prototype._initCache = function () {
  29361. _super.prototype._initCache.call(this);
  29362. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29363. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29364. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29365. };
  29366. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  29367. if (!ignoreParentClass) {
  29368. _super.prototype._updateCache.call(this);
  29369. }
  29370. var lockedTargetPosition = this._getLockedTargetPosition();
  29371. if (!lockedTargetPosition) {
  29372. this._cache.lockedTarget = null;
  29373. }
  29374. else {
  29375. if (!this._cache.lockedTarget) {
  29376. this._cache.lockedTarget = lockedTargetPosition.clone();
  29377. }
  29378. else {
  29379. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  29380. }
  29381. }
  29382. this._cache.rotation.copyFrom(this.rotation);
  29383. if (this.rotationQuaternion)
  29384. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29385. };
  29386. // Synchronized
  29387. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  29388. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  29389. return false;
  29390. }
  29391. var lockedTargetPosition = this._getLockedTargetPosition();
  29392. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  29393. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  29394. };
  29395. // Methods
  29396. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  29397. var engine = this.getEngine();
  29398. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  29399. };
  29400. // Target
  29401. TargetCamera.prototype.setTarget = function (target) {
  29402. this.upVector.normalize();
  29403. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  29404. this._camMatrix.invert();
  29405. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  29406. var vDir = target.subtract(this.position);
  29407. if (vDir.x >= 0.0) {
  29408. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  29409. }
  29410. else {
  29411. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  29412. }
  29413. this.rotation.z = 0;
  29414. if (isNaN(this.rotation.x)) {
  29415. this.rotation.x = 0;
  29416. }
  29417. if (isNaN(this.rotation.y)) {
  29418. this.rotation.y = 0;
  29419. }
  29420. if (isNaN(this.rotation.z)) {
  29421. this.rotation.z = 0;
  29422. }
  29423. if (this.rotationQuaternion) {
  29424. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29425. }
  29426. };
  29427. /**
  29428. * Return the current target position of the camera. This value is expressed in local space.
  29429. */
  29430. TargetCamera.prototype.getTarget = function () {
  29431. return this._currentTarget;
  29432. };
  29433. TargetCamera.prototype._decideIfNeedsToMove = function () {
  29434. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  29435. };
  29436. TargetCamera.prototype._updatePosition = function () {
  29437. if (this.parent) {
  29438. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  29439. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  29440. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  29441. return;
  29442. }
  29443. this.position.addInPlace(this.cameraDirection);
  29444. };
  29445. TargetCamera.prototype._checkInputs = function () {
  29446. var needToMove = this._decideIfNeedsToMove();
  29447. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  29448. // Move
  29449. if (needToMove) {
  29450. this._updatePosition();
  29451. }
  29452. // Rotate
  29453. if (needToRotate) {
  29454. this.rotation.x += this.cameraRotation.x;
  29455. this.rotation.y += this.cameraRotation.y;
  29456. //rotate, if quaternion is set and rotation was used
  29457. if (this.rotationQuaternion) {
  29458. var len = this.rotation.lengthSquared();
  29459. if (len) {
  29460. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29461. }
  29462. }
  29463. if (!this.noRotationConstraint) {
  29464. var limit = (Math.PI / 2) * 0.95;
  29465. if (this.rotation.x > limit)
  29466. this.rotation.x = limit;
  29467. if (this.rotation.x < -limit)
  29468. this.rotation.x = -limit;
  29469. }
  29470. }
  29471. // Inertia
  29472. if (needToMove) {
  29473. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  29474. this.cameraDirection.x = 0;
  29475. }
  29476. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  29477. this.cameraDirection.y = 0;
  29478. }
  29479. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  29480. this.cameraDirection.z = 0;
  29481. }
  29482. this.cameraDirection.scaleInPlace(this.inertia);
  29483. }
  29484. if (needToRotate) {
  29485. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  29486. this.cameraRotation.x = 0;
  29487. }
  29488. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  29489. this.cameraRotation.y = 0;
  29490. }
  29491. this.cameraRotation.scaleInPlace(this.inertia);
  29492. }
  29493. _super.prototype._checkInputs.call(this);
  29494. };
  29495. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  29496. if (this.rotationQuaternion) {
  29497. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  29498. //update the up vector!
  29499. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  29500. }
  29501. else {
  29502. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  29503. }
  29504. };
  29505. TargetCamera.prototype._getViewMatrix = function () {
  29506. if (!this.lockedTarget) {
  29507. // Compute
  29508. this._updateCameraRotationMatrix();
  29509. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  29510. // Computing target and final matrix
  29511. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  29512. }
  29513. else {
  29514. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  29515. }
  29516. if (this.getScene().useRightHandedSystem) {
  29517. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29518. }
  29519. else {
  29520. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29521. }
  29522. return this._viewMatrix;
  29523. };
  29524. /**
  29525. * @override
  29526. * Override Camera.createRigCamera
  29527. */
  29528. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  29529. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29530. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  29531. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  29532. if (!this.rotationQuaternion) {
  29533. this.rotationQuaternion = new BABYLON.Quaternion();
  29534. }
  29535. rigCamera._cameraRigParams = {};
  29536. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  29537. }
  29538. return rigCamera;
  29539. }
  29540. return null;
  29541. };
  29542. /**
  29543. * @override
  29544. * Override Camera._updateRigCameras
  29545. */
  29546. TargetCamera.prototype._updateRigCameras = function () {
  29547. var camLeft = this._rigCameras[0];
  29548. var camRight = this._rigCameras[1];
  29549. switch (this.cameraRigMode) {
  29550. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  29551. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  29552. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  29553. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  29554. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  29555. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  29556. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  29557. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  29558. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  29559. camLeft.setTarget(this.getTarget());
  29560. camRight.setTarget(this.getTarget());
  29561. break;
  29562. case BABYLON.Camera.RIG_MODE_VR:
  29563. if (camLeft.rotationQuaternion) {
  29564. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29565. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29566. }
  29567. else {
  29568. camLeft.rotation.copyFrom(this.rotation);
  29569. camRight.rotation.copyFrom(this.rotation);
  29570. }
  29571. camLeft.position.copyFrom(this.position);
  29572. camRight.position.copyFrom(this.position);
  29573. break;
  29574. }
  29575. _super.prototype._updateRigCameras.call(this);
  29576. };
  29577. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  29578. if (!this._rigCamTransformMatrix) {
  29579. this._rigCamTransformMatrix = new BABYLON.Matrix();
  29580. }
  29581. var target = this.getTarget();
  29582. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  29583. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  29584. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  29585. };
  29586. TargetCamera.prototype.getClassName = function () {
  29587. return "TargetCamera";
  29588. };
  29589. return TargetCamera;
  29590. }(BABYLON.Camera));
  29591. __decorate([
  29592. BABYLON.serializeAsVector3()
  29593. ], TargetCamera.prototype, "rotation", void 0);
  29594. __decorate([
  29595. BABYLON.serialize()
  29596. ], TargetCamera.prototype, "speed", void 0);
  29597. __decorate([
  29598. BABYLON.serializeAsMeshReference("lockedTargetId")
  29599. ], TargetCamera.prototype, "lockedTarget", void 0);
  29600. BABYLON.TargetCamera = TargetCamera;
  29601. })(BABYLON || (BABYLON = {}));
  29602. //# sourceMappingURL=babylon.targetCamera.js.map
  29603. var BABYLON;
  29604. (function (BABYLON) {
  29605. var FreeCamera = (function (_super) {
  29606. __extends(FreeCamera, _super);
  29607. function FreeCamera(name, position, scene) {
  29608. var _this = _super.call(this, name, position, scene) || this;
  29609. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  29610. _this.checkCollisions = false;
  29611. _this.applyGravity = false;
  29612. _this._needMoveForGravity = false;
  29613. _this._oldPosition = BABYLON.Vector3.Zero();
  29614. _this._diffPosition = BABYLON.Vector3.Zero();
  29615. _this._newPosition = BABYLON.Vector3.Zero();
  29616. // Collisions
  29617. _this._collisionMask = -1;
  29618. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  29619. if (collidedMesh === void 0) { collidedMesh = null; }
  29620. //TODO move this to the collision coordinator!
  29621. if (_this.getScene().workerCollisions)
  29622. newPosition.multiplyInPlace(_this._collider.radius);
  29623. var updatePosition = function (newPos) {
  29624. _this._newPosition.copyFrom(newPos);
  29625. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  29626. var oldPosition = _this.position.clone();
  29627. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  29628. _this.position.addInPlace(_this._diffPosition);
  29629. if (_this.onCollide && collidedMesh) {
  29630. _this.onCollide(collidedMesh);
  29631. }
  29632. }
  29633. };
  29634. updatePosition(newPosition);
  29635. };
  29636. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  29637. _this.inputs.addKeyboard().addMouse();
  29638. return _this;
  29639. }
  29640. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  29641. //-- begin properties for backward compatibility for inputs
  29642. get: function () {
  29643. var mouse = this.inputs.attached["mouse"];
  29644. if (mouse)
  29645. return mouse.angularSensibility;
  29646. },
  29647. set: function (value) {
  29648. var mouse = this.inputs.attached["mouse"];
  29649. if (mouse)
  29650. mouse.angularSensibility = value;
  29651. },
  29652. enumerable: true,
  29653. configurable: true
  29654. });
  29655. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  29656. get: function () {
  29657. var keyboard = this.inputs.attached["keyboard"];
  29658. if (keyboard)
  29659. return keyboard.keysUp;
  29660. },
  29661. set: function (value) {
  29662. var keyboard = this.inputs.attached["keyboard"];
  29663. if (keyboard)
  29664. keyboard.keysUp = value;
  29665. },
  29666. enumerable: true,
  29667. configurable: true
  29668. });
  29669. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  29670. get: function () {
  29671. var keyboard = this.inputs.attached["keyboard"];
  29672. if (keyboard)
  29673. return keyboard.keysDown;
  29674. },
  29675. set: function (value) {
  29676. var keyboard = this.inputs.attached["keyboard"];
  29677. if (keyboard)
  29678. keyboard.keysDown = value;
  29679. },
  29680. enumerable: true,
  29681. configurable: true
  29682. });
  29683. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  29684. get: function () {
  29685. var keyboard = this.inputs.attached["keyboard"];
  29686. if (keyboard)
  29687. return keyboard.keysLeft;
  29688. },
  29689. set: function (value) {
  29690. var keyboard = this.inputs.attached["keyboard"];
  29691. if (keyboard)
  29692. keyboard.keysLeft = value;
  29693. },
  29694. enumerable: true,
  29695. configurable: true
  29696. });
  29697. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  29698. get: function () {
  29699. var keyboard = this.inputs.attached["keyboard"];
  29700. if (keyboard)
  29701. return keyboard.keysRight;
  29702. },
  29703. set: function (value) {
  29704. var keyboard = this.inputs.attached["keyboard"];
  29705. if (keyboard)
  29706. keyboard.keysRight = value;
  29707. },
  29708. enumerable: true,
  29709. configurable: true
  29710. });
  29711. // Controls
  29712. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29713. this.inputs.attachElement(element, noPreventDefault);
  29714. };
  29715. FreeCamera.prototype.detachControl = function (element) {
  29716. this.inputs.detachElement(element);
  29717. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  29718. this.cameraRotation = new BABYLON.Vector2(0, 0);
  29719. };
  29720. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  29721. get: function () {
  29722. return this._collisionMask;
  29723. },
  29724. set: function (mask) {
  29725. this._collisionMask = !isNaN(mask) ? mask : -1;
  29726. },
  29727. enumerable: true,
  29728. configurable: true
  29729. });
  29730. FreeCamera.prototype._collideWithWorld = function (velocity) {
  29731. var globalPosition;
  29732. if (this.parent) {
  29733. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  29734. }
  29735. else {
  29736. globalPosition = this.position;
  29737. }
  29738. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  29739. if (!this._collider) {
  29740. this._collider = new BABYLON.Collider();
  29741. }
  29742. this._collider.radius = this.ellipsoid;
  29743. this._collider.collisionMask = this._collisionMask;
  29744. //no need for clone, as long as gravity is not on.
  29745. var actualVelocity = velocity;
  29746. //add gravity to the velocity to prevent the dual-collision checking
  29747. if (this.applyGravity) {
  29748. //this prevents mending with cameraDirection, a global variable of the free camera class.
  29749. actualVelocity = velocity.add(this.getScene().gravity);
  29750. }
  29751. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  29752. };
  29753. FreeCamera.prototype._checkInputs = function () {
  29754. if (!this._localDirection) {
  29755. this._localDirection = BABYLON.Vector3.Zero();
  29756. this._transformedDirection = BABYLON.Vector3.Zero();
  29757. }
  29758. this.inputs.checkInputs();
  29759. _super.prototype._checkInputs.call(this);
  29760. };
  29761. FreeCamera.prototype._decideIfNeedsToMove = function () {
  29762. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  29763. };
  29764. FreeCamera.prototype._updatePosition = function () {
  29765. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  29766. this._collideWithWorld(this.cameraDirection);
  29767. }
  29768. else {
  29769. _super.prototype._updatePosition.call(this);
  29770. }
  29771. };
  29772. FreeCamera.prototype.dispose = function () {
  29773. this.inputs.clear();
  29774. _super.prototype.dispose.call(this);
  29775. };
  29776. FreeCamera.prototype.getClassName = function () {
  29777. return "FreeCamera";
  29778. };
  29779. return FreeCamera;
  29780. }(BABYLON.TargetCamera));
  29781. __decorate([
  29782. BABYLON.serializeAsVector3()
  29783. ], FreeCamera.prototype, "ellipsoid", void 0);
  29784. __decorate([
  29785. BABYLON.serialize()
  29786. ], FreeCamera.prototype, "checkCollisions", void 0);
  29787. __decorate([
  29788. BABYLON.serialize()
  29789. ], FreeCamera.prototype, "applyGravity", void 0);
  29790. BABYLON.FreeCamera = FreeCamera;
  29791. })(BABYLON || (BABYLON = {}));
  29792. //# sourceMappingURL=babylon.freeCamera.js.map
  29793. var BABYLON;
  29794. (function (BABYLON) {
  29795. var ArcRotateCameraKeyboardMoveInput = (function () {
  29796. function ArcRotateCameraKeyboardMoveInput() {
  29797. this._keys = [];
  29798. this.keysUp = [38];
  29799. this.keysDown = [40];
  29800. this.keysLeft = [37];
  29801. this.keysRight = [39];
  29802. }
  29803. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  29804. var _this = this;
  29805. element.tabIndex = 1;
  29806. this._onKeyDown = function (evt) {
  29807. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29808. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29809. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  29810. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  29811. var index = _this._keys.indexOf(evt.keyCode);
  29812. if (index === -1) {
  29813. _this._keys.push(evt.keyCode);
  29814. }
  29815. if (evt.preventDefault) {
  29816. if (!noPreventDefault) {
  29817. evt.preventDefault();
  29818. }
  29819. }
  29820. }
  29821. };
  29822. this._onKeyUp = function (evt) {
  29823. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29824. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29825. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  29826. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  29827. var index = _this._keys.indexOf(evt.keyCode);
  29828. if (index >= 0) {
  29829. _this._keys.splice(index, 1);
  29830. }
  29831. if (evt.preventDefault) {
  29832. if (!noPreventDefault) {
  29833. evt.preventDefault();
  29834. }
  29835. }
  29836. }
  29837. };
  29838. this._onLostFocus = function () {
  29839. _this._keys = [];
  29840. };
  29841. element.addEventListener("keydown", this._onKeyDown, false);
  29842. element.addEventListener("keyup", this._onKeyUp, false);
  29843. BABYLON.Tools.RegisterTopRootEvents([
  29844. { name: "blur", handler: this._onLostFocus }
  29845. ]);
  29846. };
  29847. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  29848. if (element) {
  29849. element.removeEventListener("keydown", this._onKeyDown);
  29850. element.removeEventListener("keyup", this._onKeyUp);
  29851. }
  29852. BABYLON.Tools.UnregisterTopRootEvents([
  29853. { name: "blur", handler: this._onLostFocus }
  29854. ]);
  29855. this._keys = [];
  29856. this._onKeyDown = null;
  29857. this._onKeyUp = null;
  29858. this._onLostFocus = null;
  29859. };
  29860. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  29861. if (this._onKeyDown) {
  29862. var camera = this.camera;
  29863. for (var index = 0; index < this._keys.length; index++) {
  29864. var keyCode = this._keys[index];
  29865. if (this.keysLeft.indexOf(keyCode) !== -1) {
  29866. camera.inertialAlphaOffset -= 0.01;
  29867. }
  29868. else if (this.keysUp.indexOf(keyCode) !== -1) {
  29869. camera.inertialBetaOffset -= 0.01;
  29870. }
  29871. else if (this.keysRight.indexOf(keyCode) !== -1) {
  29872. camera.inertialAlphaOffset += 0.01;
  29873. }
  29874. else if (this.keysDown.indexOf(keyCode) !== -1) {
  29875. camera.inertialBetaOffset += 0.01;
  29876. }
  29877. }
  29878. }
  29879. };
  29880. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  29881. return "ArcRotateCameraKeyboardMoveInput";
  29882. };
  29883. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  29884. return "keyboard";
  29885. };
  29886. return ArcRotateCameraKeyboardMoveInput;
  29887. }());
  29888. __decorate([
  29889. BABYLON.serialize()
  29890. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  29891. __decorate([
  29892. BABYLON.serialize()
  29893. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  29894. __decorate([
  29895. BABYLON.serialize()
  29896. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  29897. __decorate([
  29898. BABYLON.serialize()
  29899. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  29900. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  29901. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  29902. })(BABYLON || (BABYLON = {}));
  29903. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  29904. var BABYLON;
  29905. (function (BABYLON) {
  29906. var ArcRotateCameraMouseWheelInput = (function () {
  29907. function ArcRotateCameraMouseWheelInput() {
  29908. this.wheelPrecision = 3.0;
  29909. }
  29910. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  29911. var _this = this;
  29912. this._wheel = function (p, s) {
  29913. //sanity check - this should be a PointerWheel event.
  29914. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  29915. return;
  29916. var event = p.event;
  29917. var delta = 0;
  29918. if (event.wheelDelta) {
  29919. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  29920. }
  29921. else if (event.detail) {
  29922. delta = -event.detail / _this.wheelPrecision;
  29923. }
  29924. if (delta)
  29925. _this.camera.inertialRadiusOffset += delta;
  29926. if (event.preventDefault) {
  29927. if (!noPreventDefault) {
  29928. event.preventDefault();
  29929. }
  29930. }
  29931. };
  29932. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  29933. };
  29934. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  29935. if (this._observer && element) {
  29936. this.camera.getScene().onPointerObservable.remove(this._observer);
  29937. this._observer = null;
  29938. this._wheel = null;
  29939. }
  29940. };
  29941. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  29942. return "ArcRotateCameraMouseWheelInput";
  29943. };
  29944. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  29945. return "mousewheel";
  29946. };
  29947. return ArcRotateCameraMouseWheelInput;
  29948. }());
  29949. __decorate([
  29950. BABYLON.serialize()
  29951. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  29952. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  29953. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  29954. })(BABYLON || (BABYLON = {}));
  29955. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  29956. var BABYLON;
  29957. (function (BABYLON) {
  29958. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  29959. var ArcRotateCameraPointersInput = (function () {
  29960. function ArcRotateCameraPointersInput() {
  29961. this.buttons = [0, 1, 2];
  29962. this.angularSensibilityX = 1000.0;
  29963. this.angularSensibilityY = 1000.0;
  29964. this.pinchPrecision = 6.0;
  29965. this.panningSensibility = 50.0;
  29966. this._isPanClick = false;
  29967. this.pinchInwards = true;
  29968. }
  29969. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  29970. var _this = this;
  29971. var engine = this.camera.getEngine();
  29972. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  29973. var pointA, pointB;
  29974. var previousPinchDistance = 0;
  29975. this._pointerInput = function (p, s) {
  29976. var evt = p.event;
  29977. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  29978. return;
  29979. }
  29980. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  29981. try {
  29982. evt.srcElement.setPointerCapture(evt.pointerId);
  29983. }
  29984. catch (e) {
  29985. //Nothing to do with the error. Execution will continue.
  29986. }
  29987. // Manage panning with pan button click
  29988. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  29989. // manage pointers
  29990. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  29991. if (pointA === undefined) {
  29992. pointA = cacheSoloPointer;
  29993. }
  29994. else if (pointB === undefined) {
  29995. pointB = cacheSoloPointer;
  29996. }
  29997. if (!noPreventDefault) {
  29998. evt.preventDefault();
  29999. element.focus();
  30000. }
  30001. }
  30002. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30003. try {
  30004. evt.srcElement.releasePointerCapture(evt.pointerId);
  30005. }
  30006. catch (e) {
  30007. //Nothing to do with the error.
  30008. }
  30009. cacheSoloPointer = null;
  30010. previousPinchDistance = 0;
  30011. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  30012. //but emptying completly pointers collection is required to fix a bug on iPhone :
  30013. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  30014. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  30015. pointA = pointB = undefined;
  30016. if (!noPreventDefault) {
  30017. evt.preventDefault();
  30018. }
  30019. }
  30020. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30021. if (!noPreventDefault) {
  30022. evt.preventDefault();
  30023. }
  30024. // One button down
  30025. if (pointA && pointB === undefined) {
  30026. if (_this.panningSensibility !== 0 &&
  30027. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  30028. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  30029. _this.camera
  30030. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  30031. _this.camera
  30032. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  30033. }
  30034. else {
  30035. var offsetX = evt.clientX - cacheSoloPointer.x;
  30036. var offsetY = evt.clientY - cacheSoloPointer.y;
  30037. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30038. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30039. }
  30040. cacheSoloPointer.x = evt.clientX;
  30041. cacheSoloPointer.y = evt.clientY;
  30042. }
  30043. else if (pointA && pointB) {
  30044. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  30045. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  30046. ed.x = evt.clientX;
  30047. ed.y = evt.clientY;
  30048. var direction = _this.pinchInwards ? 1 : -1;
  30049. var distX = pointA.x - pointB.x;
  30050. var distY = pointA.y - pointB.y;
  30051. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  30052. if (previousPinchDistance === 0) {
  30053. previousPinchDistance = pinchSquaredDistance;
  30054. return;
  30055. }
  30056. if (pinchSquaredDistance !== previousPinchDistance) {
  30057. _this.camera
  30058. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  30059. (_this.pinchPrecision *
  30060. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  30061. direction);
  30062. previousPinchDistance = pinchSquaredDistance;
  30063. }
  30064. }
  30065. }
  30066. };
  30067. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30068. this._onContextMenu = function (evt) {
  30069. evt.preventDefault();
  30070. };
  30071. if (!this.camera._useCtrlForPanning) {
  30072. element.addEventListener("contextmenu", this._onContextMenu, false);
  30073. }
  30074. this._onLostFocus = function () {
  30075. //this._keys = [];
  30076. pointA = pointB = undefined;
  30077. previousPinchDistance = 0;
  30078. cacheSoloPointer = null;
  30079. };
  30080. this._onMouseMove = function (evt) {
  30081. if (!engine.isPointerLock) {
  30082. return;
  30083. }
  30084. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30085. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30086. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30087. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30088. if (!noPreventDefault) {
  30089. evt.preventDefault();
  30090. }
  30091. };
  30092. this._onGestureStart = function (e) {
  30093. if (window.MSGesture === undefined) {
  30094. return;
  30095. }
  30096. if (!_this._MSGestureHandler) {
  30097. _this._MSGestureHandler = new MSGesture();
  30098. _this._MSGestureHandler.target = element;
  30099. }
  30100. _this._MSGestureHandler.addPointer(e.pointerId);
  30101. };
  30102. this._onGesture = function (e) {
  30103. _this.camera.radius *= e.scale;
  30104. if (e.preventDefault) {
  30105. if (!noPreventDefault) {
  30106. e.stopPropagation();
  30107. e.preventDefault();
  30108. }
  30109. }
  30110. };
  30111. element.addEventListener("mousemove", this._onMouseMove, false);
  30112. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  30113. element.addEventListener("MSGestureChange", this._onGesture, false);
  30114. element.addEventListener("keydown", this._onKeyDown, false);
  30115. element.addEventListener("keyup", this._onKeyUp, false);
  30116. BABYLON.Tools.RegisterTopRootEvents([
  30117. { name: "blur", handler: this._onLostFocus }
  30118. ]);
  30119. };
  30120. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  30121. if (element && this._observer) {
  30122. this.camera.getScene().onPointerObservable.remove(this._observer);
  30123. this._observer = null;
  30124. element.removeEventListener("contextmenu", this._onContextMenu);
  30125. element.removeEventListener("mousemove", this._onMouseMove);
  30126. element.removeEventListener("MSPointerDown", this._onGestureStart);
  30127. element.removeEventListener("MSGestureChange", this._onGesture);
  30128. element.removeEventListener("keydown", this._onKeyDown);
  30129. element.removeEventListener("keyup", this._onKeyUp);
  30130. this._isPanClick = false;
  30131. this.pinchInwards = true;
  30132. this._onKeyDown = null;
  30133. this._onKeyUp = null;
  30134. this._onMouseMove = null;
  30135. this._onGestureStart = null;
  30136. this._onGesture = null;
  30137. this._MSGestureHandler = null;
  30138. this._onLostFocus = null;
  30139. this._onContextMenu = null;
  30140. }
  30141. BABYLON.Tools.UnregisterTopRootEvents([
  30142. { name: "blur", handler: this._onLostFocus }
  30143. ]);
  30144. };
  30145. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  30146. return "ArcRotateCameraPointersInput";
  30147. };
  30148. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  30149. return "pointers";
  30150. };
  30151. return ArcRotateCameraPointersInput;
  30152. }());
  30153. __decorate([
  30154. BABYLON.serialize()
  30155. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  30156. __decorate([
  30157. BABYLON.serialize()
  30158. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  30159. __decorate([
  30160. BABYLON.serialize()
  30161. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  30162. __decorate([
  30163. BABYLON.serialize()
  30164. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  30165. __decorate([
  30166. BABYLON.serialize()
  30167. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  30168. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  30169. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  30170. })(BABYLON || (BABYLON = {}));
  30171. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  30172. /// <reference path="babylon.targetCamera.ts" />
  30173. /// <reference path="..\Tools\babylon.tools.ts" />
  30174. var BABYLON;
  30175. (function (BABYLON) {
  30176. var ArcRotateCamera = (function (_super) {
  30177. __extends(ArcRotateCamera, _super);
  30178. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  30179. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  30180. _this.inertialAlphaOffset = 0;
  30181. _this.inertialBetaOffset = 0;
  30182. _this.inertialRadiusOffset = 0;
  30183. _this.lowerAlphaLimit = null;
  30184. _this.upperAlphaLimit = null;
  30185. _this.lowerBetaLimit = 0.01;
  30186. _this.upperBetaLimit = Math.PI;
  30187. _this.lowerRadiusLimit = null;
  30188. _this.upperRadiusLimit = null;
  30189. _this.inertialPanningX = 0;
  30190. _this.inertialPanningY = 0;
  30191. //-- end properties for backward compatibility for inputs
  30192. _this.zoomOnFactor = 1;
  30193. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  30194. _this.allowUpsideDown = true;
  30195. _this._viewMatrix = new BABYLON.Matrix();
  30196. // Panning
  30197. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  30198. _this.checkCollisions = false;
  30199. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  30200. _this._previousPosition = BABYLON.Vector3.Zero();
  30201. _this._collisionVelocity = BABYLON.Vector3.Zero();
  30202. _this._newPosition = BABYLON.Vector3.Zero();
  30203. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  30204. if (collidedMesh === void 0) { collidedMesh = null; }
  30205. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  30206. newPosition.multiplyInPlace(_this._collider.radius);
  30207. }
  30208. if (!collidedMesh) {
  30209. _this._previousPosition.copyFrom(_this.position);
  30210. }
  30211. else {
  30212. _this.setPosition(newPosition);
  30213. if (_this.onCollide) {
  30214. _this.onCollide(collidedMesh);
  30215. }
  30216. }
  30217. // Recompute because of constraints
  30218. var cosa = Math.cos(_this.alpha);
  30219. var sina = Math.sin(_this.alpha);
  30220. var cosb = Math.cos(_this.beta);
  30221. var sinb = Math.sin(_this.beta);
  30222. if (sinb === 0) {
  30223. sinb = 0.0001;
  30224. }
  30225. var target = _this._getTargetPosition();
  30226. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  30227. _this.position.copyFrom(_this._newPosition);
  30228. var up = _this.upVector;
  30229. if (_this.allowUpsideDown && _this.beta < 0) {
  30230. up = up.clone();
  30231. up = up.negate();
  30232. }
  30233. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  30234. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  30235. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  30236. _this._collisionTriggered = false;
  30237. };
  30238. if (!target) {
  30239. _this.target = BABYLON.Vector3.Zero();
  30240. }
  30241. else {
  30242. _this.target = target;
  30243. }
  30244. _this.alpha = alpha;
  30245. _this.beta = beta;
  30246. _this.radius = radius;
  30247. _this.getViewMatrix();
  30248. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  30249. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  30250. return _this;
  30251. }
  30252. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  30253. //-- begin properties for backward compatibility for inputs
  30254. get: function () {
  30255. var pointers = this.inputs.attached["pointers"];
  30256. if (pointers)
  30257. return pointers.angularSensibilityX;
  30258. },
  30259. set: function (value) {
  30260. var pointers = this.inputs.attached["pointers"];
  30261. if (pointers) {
  30262. pointers.angularSensibilityX = value;
  30263. }
  30264. },
  30265. enumerable: true,
  30266. configurable: true
  30267. });
  30268. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  30269. get: function () {
  30270. var pointers = this.inputs.attached["pointers"];
  30271. if (pointers)
  30272. return pointers.angularSensibilityY;
  30273. },
  30274. set: function (value) {
  30275. var pointers = this.inputs.attached["pointers"];
  30276. if (pointers) {
  30277. pointers.angularSensibilityY = value;
  30278. }
  30279. },
  30280. enumerable: true,
  30281. configurable: true
  30282. });
  30283. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  30284. get: function () {
  30285. var pointers = this.inputs.attached["pointers"];
  30286. if (pointers)
  30287. return pointers.pinchPrecision;
  30288. },
  30289. set: function (value) {
  30290. var pointers = this.inputs.attached["pointers"];
  30291. if (pointers) {
  30292. pointers.pinchPrecision = value;
  30293. }
  30294. },
  30295. enumerable: true,
  30296. configurable: true
  30297. });
  30298. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  30299. get: function () {
  30300. var pointers = this.inputs.attached["pointers"];
  30301. if (pointers)
  30302. return pointers.panningSensibility;
  30303. },
  30304. set: function (value) {
  30305. var pointers = this.inputs.attached["pointers"];
  30306. if (pointers) {
  30307. pointers.panningSensibility = value;
  30308. }
  30309. },
  30310. enumerable: true,
  30311. configurable: true
  30312. });
  30313. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  30314. get: function () {
  30315. var keyboard = this.inputs.attached["keyboard"];
  30316. if (keyboard)
  30317. return keyboard.keysUp;
  30318. },
  30319. set: function (value) {
  30320. var keyboard = this.inputs.attached["keyboard"];
  30321. if (keyboard)
  30322. keyboard.keysUp = value;
  30323. },
  30324. enumerable: true,
  30325. configurable: true
  30326. });
  30327. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  30328. get: function () {
  30329. var keyboard = this.inputs.attached["keyboard"];
  30330. if (keyboard)
  30331. return keyboard.keysDown;
  30332. },
  30333. set: function (value) {
  30334. var keyboard = this.inputs.attached["keyboard"];
  30335. if (keyboard)
  30336. keyboard.keysDown = value;
  30337. },
  30338. enumerable: true,
  30339. configurable: true
  30340. });
  30341. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  30342. get: function () {
  30343. var keyboard = this.inputs.attached["keyboard"];
  30344. if (keyboard)
  30345. return keyboard.keysLeft;
  30346. },
  30347. set: function (value) {
  30348. var keyboard = this.inputs.attached["keyboard"];
  30349. if (keyboard)
  30350. keyboard.keysLeft = value;
  30351. },
  30352. enumerable: true,
  30353. configurable: true
  30354. });
  30355. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  30356. get: function () {
  30357. var keyboard = this.inputs.attached["keyboard"];
  30358. if (keyboard)
  30359. return keyboard.keysRight;
  30360. },
  30361. set: function (value) {
  30362. var keyboard = this.inputs.attached["keyboard"];
  30363. if (keyboard)
  30364. keyboard.keysRight = value;
  30365. },
  30366. enumerable: true,
  30367. configurable: true
  30368. });
  30369. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  30370. get: function () {
  30371. var mousewheel = this.inputs.attached["mousewheel"];
  30372. if (mousewheel)
  30373. return mousewheel.wheelPrecision;
  30374. },
  30375. set: function (value) {
  30376. var mousewheel = this.inputs.attached["mousewheel"];
  30377. if (mousewheel)
  30378. mousewheel.wheelPrecision = value;
  30379. },
  30380. enumerable: true,
  30381. configurable: true
  30382. });
  30383. // Cache
  30384. ArcRotateCamera.prototype._initCache = function () {
  30385. _super.prototype._initCache.call(this);
  30386. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30387. this._cache.alpha = undefined;
  30388. this._cache.beta = undefined;
  30389. this._cache.radius = undefined;
  30390. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  30391. };
  30392. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  30393. if (!ignoreParentClass) {
  30394. _super.prototype._updateCache.call(this);
  30395. }
  30396. this._cache.target.copyFrom(this._getTargetPosition());
  30397. this._cache.alpha = this.alpha;
  30398. this._cache.beta = this.beta;
  30399. this._cache.radius = this.radius;
  30400. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  30401. };
  30402. ArcRotateCamera.prototype._getTargetPosition = function () {
  30403. if (this.target.getAbsolutePosition) {
  30404. var pos = this.target.getAbsolutePosition();
  30405. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  30406. }
  30407. return this.target;
  30408. };
  30409. // Synchronized
  30410. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  30411. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  30412. return false;
  30413. return this._cache.target.equals(this.target)
  30414. && this._cache.alpha === this.alpha
  30415. && this._cache.beta === this.beta
  30416. && this._cache.radius === this.radius
  30417. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  30418. };
  30419. // Methods
  30420. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  30421. var _this = this;
  30422. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  30423. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  30424. this._useCtrlForPanning = useCtrlForPanning;
  30425. this._panningMouseButton = panningMouseButton;
  30426. this.inputs.attachElement(element, noPreventDefault);
  30427. this._reset = function () {
  30428. _this.inertialAlphaOffset = 0;
  30429. _this.inertialBetaOffset = 0;
  30430. _this.inertialRadiusOffset = 0;
  30431. };
  30432. };
  30433. ArcRotateCamera.prototype.detachControl = function (element) {
  30434. this.inputs.detachElement(element);
  30435. if (this._reset) {
  30436. this._reset();
  30437. }
  30438. };
  30439. ArcRotateCamera.prototype._checkInputs = function () {
  30440. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  30441. if (this._collisionTriggered) {
  30442. return;
  30443. }
  30444. this.inputs.checkInputs();
  30445. // Inertia
  30446. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  30447. if (this.getScene().useRightHandedSystem) {
  30448. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30449. }
  30450. else {
  30451. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30452. }
  30453. this.beta += this.inertialBetaOffset;
  30454. this.radius -= this.inertialRadiusOffset;
  30455. this.inertialAlphaOffset *= this.inertia;
  30456. this.inertialBetaOffset *= this.inertia;
  30457. this.inertialRadiusOffset *= this.inertia;
  30458. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  30459. this.inertialAlphaOffset = 0;
  30460. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  30461. this.inertialBetaOffset = 0;
  30462. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  30463. this.inertialRadiusOffset = 0;
  30464. }
  30465. // Panning inertia
  30466. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  30467. if (!this._localDirection) {
  30468. this._localDirection = BABYLON.Vector3.Zero();
  30469. this._transformedDirection = BABYLON.Vector3.Zero();
  30470. }
  30471. this.inertialPanningX *= this.inertia;
  30472. this.inertialPanningY *= this.inertia;
  30473. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  30474. this.inertialPanningX = 0;
  30475. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  30476. this.inertialPanningY = 0;
  30477. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  30478. this._localDirection.multiplyInPlace(this.panningAxis);
  30479. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  30480. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  30481. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  30482. if (!this.panningAxis.y) {
  30483. this._transformedDirection.y = 0;
  30484. }
  30485. if (!this.target.getAbsolutePosition) {
  30486. this.target.addInPlace(this._transformedDirection);
  30487. }
  30488. }
  30489. // Limits
  30490. this._checkLimits();
  30491. _super.prototype._checkInputs.call(this);
  30492. };
  30493. ArcRotateCamera.prototype._checkLimits = function () {
  30494. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  30495. if (this.allowUpsideDown && this.beta > Math.PI) {
  30496. this.beta = this.beta - (2 * Math.PI);
  30497. }
  30498. }
  30499. else {
  30500. if (this.beta < this.lowerBetaLimit) {
  30501. this.beta = this.lowerBetaLimit;
  30502. }
  30503. }
  30504. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  30505. if (this.allowUpsideDown && this.beta < -Math.PI) {
  30506. this.beta = this.beta + (2 * Math.PI);
  30507. }
  30508. }
  30509. else {
  30510. if (this.beta > this.upperBetaLimit) {
  30511. this.beta = this.upperBetaLimit;
  30512. }
  30513. }
  30514. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  30515. this.alpha = this.lowerAlphaLimit;
  30516. }
  30517. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  30518. this.alpha = this.upperAlphaLimit;
  30519. }
  30520. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  30521. this.radius = this.lowerRadiusLimit;
  30522. }
  30523. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  30524. this.radius = this.upperRadiusLimit;
  30525. }
  30526. };
  30527. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  30528. var radiusv3 = this.position.subtract(this._getTargetPosition());
  30529. this.radius = radiusv3.length();
  30530. // Alpha
  30531. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  30532. if (radiusv3.z < 0) {
  30533. this.alpha = 2 * Math.PI - this.alpha;
  30534. }
  30535. // Beta
  30536. this.beta = Math.acos(radiusv3.y / this.radius);
  30537. this._checkLimits();
  30538. };
  30539. ArcRotateCamera.prototype.setPosition = function (position) {
  30540. if (this.position.equals(position)) {
  30541. return;
  30542. }
  30543. this.position.copyFrom(position);
  30544. this.rebuildAnglesAndRadius();
  30545. };
  30546. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  30547. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  30548. if (allowSamePosition === void 0) { allowSamePosition = false; }
  30549. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  30550. return;
  30551. }
  30552. if (toBoundingCenter && target.getBoundingInfo) {
  30553. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  30554. }
  30555. else {
  30556. this._targetBoundingCenter = null;
  30557. }
  30558. this.target = target;
  30559. this.rebuildAnglesAndRadius();
  30560. };
  30561. ArcRotateCamera.prototype._getViewMatrix = function () {
  30562. // Compute
  30563. var cosa = Math.cos(this.alpha);
  30564. var sina = Math.sin(this.alpha);
  30565. var cosb = Math.cos(this.beta);
  30566. var sinb = Math.sin(this.beta);
  30567. if (sinb === 0) {
  30568. sinb = 0.0001;
  30569. }
  30570. var target = this._getTargetPosition();
  30571. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  30572. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  30573. if (!this._collider) {
  30574. this._collider = new BABYLON.Collider();
  30575. }
  30576. this._collider.radius = this.collisionRadius;
  30577. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  30578. this._collisionTriggered = true;
  30579. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  30580. }
  30581. else {
  30582. this.position.copyFrom(this._newPosition);
  30583. var up = this.upVector;
  30584. if (this.allowUpsideDown && sinb < 0) {
  30585. up = up.clone();
  30586. up = up.negate();
  30587. }
  30588. if (this.getScene().useRightHandedSystem) {
  30589. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  30590. }
  30591. else {
  30592. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  30593. }
  30594. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  30595. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  30596. }
  30597. this._currentTarget = target;
  30598. return this._viewMatrix;
  30599. };
  30600. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  30601. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30602. meshes = meshes || this.getScene().meshes;
  30603. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  30604. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  30605. this.radius = distance * this.zoomOnFactor;
  30606. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  30607. };
  30608. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  30609. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30610. var meshesOrMinMaxVector;
  30611. var distance;
  30612. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  30613. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  30614. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  30615. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  30616. }
  30617. else {
  30618. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  30619. distance = meshesOrMinMaxVectorAndDistance.distance;
  30620. }
  30621. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  30622. if (!doNotUpdateMaxZ) {
  30623. this.maxZ = distance * 2;
  30624. }
  30625. };
  30626. /**
  30627. * @override
  30628. * Override Camera.createRigCamera
  30629. */
  30630. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  30631. var alphaShift;
  30632. switch (this.cameraRigMode) {
  30633. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30634. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30635. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30636. case BABYLON.Camera.RIG_MODE_VR:
  30637. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  30638. break;
  30639. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30640. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  30641. break;
  30642. }
  30643. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  30644. rigCam._cameraRigParams = {};
  30645. return rigCam;
  30646. };
  30647. /**
  30648. * @override
  30649. * Override Camera._updateRigCameras
  30650. */
  30651. ArcRotateCamera.prototype._updateRigCameras = function () {
  30652. var camLeft = this._rigCameras[0];
  30653. var camRight = this._rigCameras[1];
  30654. camLeft.beta = camRight.beta = this.beta;
  30655. camLeft.radius = camRight.radius = this.radius;
  30656. switch (this.cameraRigMode) {
  30657. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30658. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30659. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30660. case BABYLON.Camera.RIG_MODE_VR:
  30661. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30662. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30663. break;
  30664. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30665. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30666. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30667. break;
  30668. }
  30669. _super.prototype._updateRigCameras.call(this);
  30670. };
  30671. ArcRotateCamera.prototype.dispose = function () {
  30672. this.inputs.clear();
  30673. _super.prototype.dispose.call(this);
  30674. };
  30675. ArcRotateCamera.prototype.getClassName = function () {
  30676. return "ArcRotateCamera";
  30677. };
  30678. return ArcRotateCamera;
  30679. }(BABYLON.TargetCamera));
  30680. __decorate([
  30681. BABYLON.serialize()
  30682. ], ArcRotateCamera.prototype, "alpha", void 0);
  30683. __decorate([
  30684. BABYLON.serialize()
  30685. ], ArcRotateCamera.prototype, "beta", void 0);
  30686. __decorate([
  30687. BABYLON.serialize()
  30688. ], ArcRotateCamera.prototype, "radius", void 0);
  30689. __decorate([
  30690. BABYLON.serializeAsVector3()
  30691. ], ArcRotateCamera.prototype, "target", void 0);
  30692. __decorate([
  30693. BABYLON.serialize()
  30694. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  30695. __decorate([
  30696. BABYLON.serialize()
  30697. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  30698. __decorate([
  30699. BABYLON.serialize()
  30700. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  30701. __decorate([
  30702. BABYLON.serialize()
  30703. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  30704. __decorate([
  30705. BABYLON.serialize()
  30706. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  30707. __decorate([
  30708. BABYLON.serialize()
  30709. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  30710. __decorate([
  30711. BABYLON.serialize()
  30712. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  30713. __decorate([
  30714. BABYLON.serialize()
  30715. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  30716. __decorate([
  30717. BABYLON.serialize()
  30718. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  30719. __decorate([
  30720. BABYLON.serialize()
  30721. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  30722. __decorate([
  30723. BABYLON.serialize()
  30724. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  30725. __decorate([
  30726. BABYLON.serialize()
  30727. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  30728. __decorate([
  30729. BABYLON.serialize()
  30730. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  30731. BABYLON.ArcRotateCamera = ArcRotateCamera;
  30732. })(BABYLON || (BABYLON = {}));
  30733. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  30734. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  30735. var BABYLON;
  30736. (function (BABYLON) {
  30737. var ArcRotateCameraInputsManager = (function (_super) {
  30738. __extends(ArcRotateCameraInputsManager, _super);
  30739. function ArcRotateCameraInputsManager(camera) {
  30740. return _super.call(this, camera) || this;
  30741. }
  30742. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  30743. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  30744. return this;
  30745. };
  30746. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  30747. this.add(new BABYLON.ArcRotateCameraPointersInput());
  30748. return this;
  30749. };
  30750. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  30751. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  30752. return this;
  30753. };
  30754. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  30755. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  30756. return this;
  30757. };
  30758. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  30759. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  30760. return this;
  30761. };
  30762. return ArcRotateCameraInputsManager;
  30763. }(BABYLON.CameraInputsManager));
  30764. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  30765. })(BABYLON || (BABYLON = {}));
  30766. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  30767. var BABYLON;
  30768. (function (BABYLON) {
  30769. var HemisphericLight = (function (_super) {
  30770. __extends(HemisphericLight, _super);
  30771. /**
  30772. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  30773. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  30774. * The HemisphericLight can't cast shadows.
  30775. * Documentation : http://doc.babylonjs.com/tutorials/lights
  30776. */
  30777. function HemisphericLight(name, direction, scene) {
  30778. var _this = _super.call(this, name, scene) || this;
  30779. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  30780. _this.direction = direction;
  30781. return _this;
  30782. }
  30783. /**
  30784. * Returns the string "HemisphericLight".
  30785. */
  30786. HemisphericLight.prototype.getClassName = function () {
  30787. return "HemisphericLight";
  30788. };
  30789. /**
  30790. * Sets the HemisphericLight direction towards the passed target (Vector3).
  30791. * Returns the updated direction.
  30792. */
  30793. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  30794. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  30795. return this.direction;
  30796. };
  30797. HemisphericLight.prototype.getShadowGenerator = function () {
  30798. return null;
  30799. };
  30800. /**
  30801. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  30802. * Returns the HemisphericLight.
  30803. */
  30804. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  30805. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  30806. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  30807. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  30808. return this;
  30809. };
  30810. HemisphericLight.prototype._getWorldMatrix = function () {
  30811. if (!this._worldMatrix) {
  30812. this._worldMatrix = BABYLON.Matrix.Identity();
  30813. }
  30814. return this._worldMatrix;
  30815. };
  30816. /**
  30817. * Returns the integer 3.
  30818. */
  30819. HemisphericLight.prototype.getTypeID = function () {
  30820. return 3;
  30821. };
  30822. return HemisphericLight;
  30823. }(BABYLON.Light));
  30824. __decorate([
  30825. BABYLON.serializeAsColor3()
  30826. ], HemisphericLight.prototype, "groundColor", void 0);
  30827. __decorate([
  30828. BABYLON.serializeAsVector3()
  30829. ], HemisphericLight.prototype, "direction", void 0);
  30830. BABYLON.HemisphericLight = HemisphericLight;
  30831. })(BABYLON || (BABYLON = {}));
  30832. //# sourceMappingURL=babylon.hemisphericLight.js.map
  30833. var BABYLON;
  30834. (function (BABYLON) {
  30835. var PointLight = (function (_super) {
  30836. __extends(PointLight, _super);
  30837. /**
  30838. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  30839. * A PointLight emits the light in every direction.
  30840. * It can cast shadows.
  30841. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  30842. * ```javascript
  30843. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  30844. * ```
  30845. * Documentation : http://doc.babylonjs.com/tutorials/lights
  30846. */
  30847. function PointLight(name, position, scene) {
  30848. var _this = _super.call(this, name, scene) || this;
  30849. _this.position = position;
  30850. return _this;
  30851. }
  30852. /**
  30853. * Returns the string "PointLight"
  30854. */
  30855. PointLight.prototype.getClassName = function () {
  30856. return "PointLight";
  30857. };
  30858. /**
  30859. * Returns a Vector3, the PointLight absolute position in the World.
  30860. */
  30861. PointLight.prototype.getAbsolutePosition = function () {
  30862. return this.transformedPosition ? this.transformedPosition : this.position;
  30863. };
  30864. /**
  30865. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  30866. */
  30867. PointLight.prototype.computeTransformedPosition = function () {
  30868. if (this.parent && this.parent.getWorldMatrix) {
  30869. if (!this.transformedPosition) {
  30870. this.transformedPosition = BABYLON.Vector3.Zero();
  30871. }
  30872. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  30873. return true;
  30874. }
  30875. return false;
  30876. };
  30877. /**
  30878. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  30879. * Returns the PointLight.
  30880. */
  30881. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  30882. if (this.parent && this.parent.getWorldMatrix) {
  30883. this.computeTransformedPosition();
  30884. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  30885. return this;
  30886. }
  30887. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  30888. return this;
  30889. };
  30890. /**
  30891. * Boolean : returns true by default.
  30892. */
  30893. PointLight.prototype.needCube = function () {
  30894. return true;
  30895. };
  30896. /**
  30897. * Boolean : returns false by default.
  30898. */
  30899. PointLight.prototype.needRefreshPerFrame = function () {
  30900. return false;
  30901. };
  30902. /**
  30903. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  30904. */
  30905. PointLight.prototype.getShadowDirection = function (faceIndex) {
  30906. switch (faceIndex) {
  30907. case 0:
  30908. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  30909. case 1:
  30910. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  30911. case 2:
  30912. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  30913. case 3:
  30914. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  30915. case 4:
  30916. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  30917. case 5:
  30918. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  30919. }
  30920. return BABYLON.Vector3.Zero();
  30921. };
  30922. /**
  30923. * Return the depth scale used for the shadow map.
  30924. */
  30925. PointLight.prototype.getDepthScale = function () {
  30926. return 30.0;
  30927. };
  30928. /**
  30929. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  30930. * - fov = PI / 2
  30931. * - aspect ratio : 1.0
  30932. * - z-near and far equal to the active camera minZ and maxZ.
  30933. * Returns the PointLight.
  30934. */
  30935. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  30936. if (this.customProjectionMatrixBuilder) {
  30937. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  30938. }
  30939. else {
  30940. var activeCamera = this.getScene().activeCamera;
  30941. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  30942. }
  30943. return this;
  30944. };
  30945. PointLight.prototype._getWorldMatrix = function () {
  30946. if (!this._worldMatrix) {
  30947. this._worldMatrix = BABYLON.Matrix.Identity();
  30948. }
  30949. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  30950. return this._worldMatrix;
  30951. };
  30952. /**
  30953. * Returns the integer 0.
  30954. */
  30955. PointLight.prototype.getTypeID = function () {
  30956. return 0;
  30957. };
  30958. return PointLight;
  30959. }(BABYLON.Light));
  30960. __decorate([
  30961. BABYLON.serializeAsVector3()
  30962. ], PointLight.prototype, "position", void 0);
  30963. __decorate([
  30964. BABYLON.serialize()
  30965. ], PointLight.prototype, "shadowMinZ", void 0);
  30966. __decorate([
  30967. BABYLON.serialize()
  30968. ], PointLight.prototype, "shadowMaxZ", void 0);
  30969. BABYLON.PointLight = PointLight;
  30970. })(BABYLON || (BABYLON = {}));
  30971. //# sourceMappingURL=babylon.pointLight.js.map
  30972. /// <reference path="babylon.light.ts" />
  30973. var BABYLON;
  30974. (function (BABYLON) {
  30975. var DirectionalLight = (function (_super) {
  30976. __extends(DirectionalLight, _super);
  30977. /**
  30978. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  30979. * The directional light is emitted from everywhere in the given direction.
  30980. * It can cast shawdows.
  30981. * Documentation : http://doc.babylonjs.com/tutorials/lights
  30982. */
  30983. function DirectionalLight(name, direction, scene) {
  30984. var _this = _super.call(this, name, scene) || this;
  30985. _this.shadowOrthoScale = 0.5;
  30986. _this.autoUpdateExtends = true;
  30987. // Cache
  30988. _this._orthoLeft = Number.MAX_VALUE;
  30989. _this._orthoRight = Number.MIN_VALUE;
  30990. _this._orthoTop = Number.MIN_VALUE;
  30991. _this._orthoBottom = Number.MAX_VALUE;
  30992. _this.position = direction.scale(-1.0);
  30993. _this.direction = direction;
  30994. return _this;
  30995. }
  30996. /**
  30997. * Returns the string "DirectionalLight".
  30998. */
  30999. DirectionalLight.prototype.getClassName = function () {
  31000. return "DirectionalLight";
  31001. };
  31002. /**
  31003. * Returns the DirectionalLight absolute position in the World.
  31004. */
  31005. DirectionalLight.prototype.getAbsolutePosition = function () {
  31006. return this.transformedPosition ? this.transformedPosition : this.position;
  31007. };
  31008. /**
  31009. * Sets the DirectionalLight direction toward the passed target (Vector3).
  31010. * Returns the updated DirectionalLight direction (Vector3).
  31011. */
  31012. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  31013. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  31014. return this.direction;
  31015. };
  31016. /**
  31017. * Return the depth scale used for the shadow map.
  31018. */
  31019. DirectionalLight.prototype.getDepthScale = function () {
  31020. return 30.0;
  31021. };
  31022. /**
  31023. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  31024. * Returns the DirectionalLight.
  31025. */
  31026. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  31027. if (this.customProjectionMatrixBuilder) {
  31028. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  31029. }
  31030. else {
  31031. var activeCamera = this.getScene().activeCamera;
  31032. // Check extends
  31033. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  31034. var tempVector3 = BABYLON.Vector3.Zero();
  31035. this._orthoLeft = Number.MAX_VALUE;
  31036. this._orthoRight = Number.MIN_VALUE;
  31037. this._orthoTop = Number.MIN_VALUE;
  31038. this._orthoBottom = Number.MAX_VALUE;
  31039. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  31040. var mesh = renderList[meshIndex];
  31041. if (!mesh) {
  31042. continue;
  31043. }
  31044. var boundingInfo = mesh.getBoundingInfo();
  31045. if (!boundingInfo) {
  31046. continue;
  31047. }
  31048. var boundingBox = boundingInfo.boundingBox;
  31049. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  31050. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  31051. if (tempVector3.x < this._orthoLeft)
  31052. this._orthoLeft = tempVector3.x;
  31053. if (tempVector3.y < this._orthoBottom)
  31054. this._orthoBottom = tempVector3.y;
  31055. if (tempVector3.x > this._orthoRight)
  31056. this._orthoRight = tempVector3.x;
  31057. if (tempVector3.y > this._orthoTop)
  31058. this._orthoTop = tempVector3.y;
  31059. }
  31060. }
  31061. }
  31062. var xOffset = this._orthoRight - this._orthoLeft;
  31063. var yOffset = this._orthoTop - this._orthoBottom;
  31064. 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);
  31065. }
  31066. return this;
  31067. };
  31068. /**
  31069. * Boolean : true by default.
  31070. */
  31071. DirectionalLight.prototype.needRefreshPerFrame = function () {
  31072. return true;
  31073. };
  31074. /**
  31075. * Boolean : false by default.
  31076. */
  31077. DirectionalLight.prototype.needCube = function () {
  31078. return false;
  31079. };
  31080. /**
  31081. * Returns the light direction (Vector3) for any passed face index.
  31082. */
  31083. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  31084. return this.direction;
  31085. };
  31086. /**
  31087. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  31088. */
  31089. DirectionalLight.prototype.computeTransformedPosition = function () {
  31090. if (this.parent && this.parent.getWorldMatrix) {
  31091. if (!this.transformedPosition) {
  31092. this.transformedPosition = BABYLON.Vector3.Zero();
  31093. }
  31094. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  31095. return true;
  31096. }
  31097. return false;
  31098. };
  31099. /**
  31100. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  31101. * Returns the DirectionalLight.
  31102. */
  31103. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  31104. if (this.parent && this.parent.getWorldMatrix) {
  31105. if (!this._transformedDirection) {
  31106. this._transformedDirection = BABYLON.Vector3.Zero();
  31107. }
  31108. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  31109. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  31110. return this;
  31111. }
  31112. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  31113. return this;
  31114. };
  31115. DirectionalLight.prototype._getWorldMatrix = function () {
  31116. if (!this._worldMatrix) {
  31117. this._worldMatrix = BABYLON.Matrix.Identity();
  31118. }
  31119. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  31120. return this._worldMatrix;
  31121. };
  31122. /**
  31123. * Returns the integer 1.
  31124. */
  31125. DirectionalLight.prototype.getTypeID = function () {
  31126. return 1;
  31127. };
  31128. return DirectionalLight;
  31129. }(BABYLON.Light));
  31130. __decorate([
  31131. BABYLON.serializeAsVector3()
  31132. ], DirectionalLight.prototype, "position", void 0);
  31133. __decorate([
  31134. BABYLON.serializeAsVector3()
  31135. ], DirectionalLight.prototype, "direction", void 0);
  31136. __decorate([
  31137. BABYLON.serialize()
  31138. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  31139. __decorate([
  31140. BABYLON.serialize()
  31141. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  31142. __decorate([
  31143. BABYLON.serialize()
  31144. ], DirectionalLight.prototype, "shadowMinZ", void 0);
  31145. __decorate([
  31146. BABYLON.serialize()
  31147. ], DirectionalLight.prototype, "shadowMaxZ", void 0);
  31148. BABYLON.DirectionalLight = DirectionalLight;
  31149. })(BABYLON || (BABYLON = {}));
  31150. //# sourceMappingURL=babylon.directionalLight.js.map
  31151. var BABYLON;
  31152. (function (BABYLON) {
  31153. var SpotLight = (function (_super) {
  31154. __extends(SpotLight, _super);
  31155. /**
  31156. * Creates a SpotLight object in the scene with the passed parameters :
  31157. * - `position` (Vector3) is the initial SpotLight position,
  31158. * - `direction` (Vector3) is the initial SpotLight direction,
  31159. * - `angle` (float, in radians) is the spot light cone angle,
  31160. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  31161. * A spot light is a simply light oriented cone.
  31162. * It can cast shadows.
  31163. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31164. */
  31165. function SpotLight(name, position, direction, angle, exponent, scene) {
  31166. var _this = _super.call(this, name, scene) || this;
  31167. _this.position = position;
  31168. _this.direction = direction;
  31169. _this.angle = angle;
  31170. _this.exponent = exponent;
  31171. return _this;
  31172. }
  31173. /**
  31174. * Returns the string "SpotLight".
  31175. */
  31176. SpotLight.prototype.getClassName = function () {
  31177. return "SpotLight";
  31178. };
  31179. /**
  31180. * Returns the SpotLight absolute position in the World (Vector3).
  31181. */
  31182. SpotLight.prototype.getAbsolutePosition = function () {
  31183. return this.transformedPosition ? this.transformedPosition : this.position;
  31184. };
  31185. /**
  31186. * Return the depth scale used for the shadow map.
  31187. */
  31188. SpotLight.prototype.getDepthScale = function () {
  31189. return 30.0;
  31190. };
  31191. /**
  31192. * 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.
  31193. * Returns the SpotLight.
  31194. */
  31195. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  31196. if (this.customProjectionMatrixBuilder) {
  31197. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  31198. }
  31199. else {
  31200. var activeCamera = this.getScene().activeCamera;
  31201. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  31202. }
  31203. return this;
  31204. };
  31205. /**
  31206. * Boolean : false by default.
  31207. */
  31208. SpotLight.prototype.needCube = function () {
  31209. return false;
  31210. };
  31211. /**
  31212. * Boolean : false by default.
  31213. */
  31214. SpotLight.prototype.needRefreshPerFrame = function () {
  31215. return false;
  31216. };
  31217. /**
  31218. * Returns the SpotLight direction (Vector3) for any passed face index.
  31219. */
  31220. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  31221. return this.direction;
  31222. };
  31223. /**
  31224. * Updates the SpotLight direction towards the passed target (Vector3).
  31225. * Returns the updated direction.
  31226. */
  31227. SpotLight.prototype.setDirectionToTarget = function (target) {
  31228. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  31229. return this.direction;
  31230. };
  31231. /**
  31232. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  31233. */
  31234. SpotLight.prototype.computeTransformedPosition = function () {
  31235. if (this.parent && this.parent.getWorldMatrix) {
  31236. if (!this.transformedPosition) {
  31237. this.transformedPosition = BABYLON.Vector3.Zero();
  31238. }
  31239. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  31240. return true;
  31241. }
  31242. return false;
  31243. };
  31244. /**
  31245. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  31246. * Return the SpotLight.
  31247. */
  31248. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  31249. var normalizeDirection;
  31250. if (this.parent && this.parent.getWorldMatrix) {
  31251. if (!this._transformedDirection) {
  31252. this._transformedDirection = BABYLON.Vector3.Zero();
  31253. }
  31254. this.computeTransformedPosition();
  31255. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  31256. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  31257. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  31258. }
  31259. else {
  31260. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  31261. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  31262. }
  31263. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  31264. return this;
  31265. };
  31266. SpotLight.prototype._getWorldMatrix = function () {
  31267. if (!this._worldMatrix) {
  31268. this._worldMatrix = BABYLON.Matrix.Identity();
  31269. }
  31270. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  31271. return this._worldMatrix;
  31272. };
  31273. /**
  31274. * Returns the integer 2.
  31275. */
  31276. SpotLight.prototype.getTypeID = function () {
  31277. return 2;
  31278. };
  31279. /**
  31280. * Returns the SpotLight rotation (Vector3).
  31281. */
  31282. SpotLight.prototype.getRotation = function () {
  31283. this.direction.normalize();
  31284. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  31285. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  31286. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  31287. };
  31288. return SpotLight;
  31289. }(BABYLON.Light));
  31290. __decorate([
  31291. BABYLON.serializeAsVector3()
  31292. ], SpotLight.prototype, "position", void 0);
  31293. __decorate([
  31294. BABYLON.serializeAsVector3()
  31295. ], SpotLight.prototype, "direction", void 0);
  31296. __decorate([
  31297. BABYLON.serialize()
  31298. ], SpotLight.prototype, "angle", void 0);
  31299. __decorate([
  31300. BABYLON.serialize()
  31301. ], SpotLight.prototype, "exponent", void 0);
  31302. __decorate([
  31303. BABYLON.serialize()
  31304. ], SpotLight.prototype, "shadowMinZ", void 0);
  31305. __decorate([
  31306. BABYLON.serialize()
  31307. ], SpotLight.prototype, "shadowMaxZ", void 0);
  31308. BABYLON.SpotLight = SpotLight;
  31309. })(BABYLON || (BABYLON = {}));
  31310. //# sourceMappingURL=babylon.spotLight.js.map
  31311. var BABYLON;
  31312. (function (BABYLON) {
  31313. var AnimationRange = (function () {
  31314. function AnimationRange(name, from, to) {
  31315. this.name = name;
  31316. this.from = from;
  31317. this.to = to;
  31318. }
  31319. AnimationRange.prototype.clone = function () {
  31320. return new AnimationRange(this.name, this.from, this.to);
  31321. };
  31322. return AnimationRange;
  31323. }());
  31324. BABYLON.AnimationRange = AnimationRange;
  31325. /**
  31326. * Composed of a frame, and an action function
  31327. */
  31328. var AnimationEvent = (function () {
  31329. function AnimationEvent(frame, action, onlyOnce) {
  31330. this.frame = frame;
  31331. this.action = action;
  31332. this.onlyOnce = onlyOnce;
  31333. this.isDone = false;
  31334. }
  31335. return AnimationEvent;
  31336. }());
  31337. BABYLON.AnimationEvent = AnimationEvent;
  31338. var PathCursor = (function () {
  31339. function PathCursor(path) {
  31340. this.path = path;
  31341. this._onchange = new Array();
  31342. this.value = 0;
  31343. this.animations = new Array();
  31344. }
  31345. PathCursor.prototype.getPoint = function () {
  31346. var point = this.path.getPointAtLengthPosition(this.value);
  31347. return new BABYLON.Vector3(point.x, 0, point.y);
  31348. };
  31349. PathCursor.prototype.moveAhead = function (step) {
  31350. if (step === void 0) { step = 0.002; }
  31351. this.move(step);
  31352. return this;
  31353. };
  31354. PathCursor.prototype.moveBack = function (step) {
  31355. if (step === void 0) { step = 0.002; }
  31356. this.move(-step);
  31357. return this;
  31358. };
  31359. PathCursor.prototype.move = function (step) {
  31360. if (Math.abs(step) > 1) {
  31361. throw "step size should be less than 1.";
  31362. }
  31363. this.value += step;
  31364. this.ensureLimits();
  31365. this.raiseOnChange();
  31366. return this;
  31367. };
  31368. PathCursor.prototype.ensureLimits = function () {
  31369. while (this.value > 1) {
  31370. this.value -= 1;
  31371. }
  31372. while (this.value < 0) {
  31373. this.value += 1;
  31374. }
  31375. return this;
  31376. };
  31377. // used by animation engine
  31378. PathCursor.prototype.markAsDirty = function (propertyName) {
  31379. this.ensureLimits();
  31380. this.raiseOnChange();
  31381. return this;
  31382. };
  31383. PathCursor.prototype.raiseOnChange = function () {
  31384. var _this = this;
  31385. this._onchange.forEach(function (f) { return f(_this); });
  31386. return this;
  31387. };
  31388. PathCursor.prototype.onchange = function (f) {
  31389. this._onchange.push(f);
  31390. return this;
  31391. };
  31392. return PathCursor;
  31393. }());
  31394. BABYLON.PathCursor = PathCursor;
  31395. var Animation = (function () {
  31396. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  31397. this.name = name;
  31398. this.targetProperty = targetProperty;
  31399. this.framePerSecond = framePerSecond;
  31400. this.dataType = dataType;
  31401. this.loopMode = loopMode;
  31402. this.enableBlending = enableBlending;
  31403. this._offsetsCache = {};
  31404. this._highLimitsCache = {};
  31405. this._stopped = false;
  31406. this._blendingFactor = 0;
  31407. // The set of event that will be linked to this animation
  31408. this._events = new Array();
  31409. this.allowMatricesInterpolation = false;
  31410. this.blendingSpeed = 0.01;
  31411. this._ranges = {};
  31412. this.targetPropertyPath = targetProperty.split(".");
  31413. this.dataType = dataType;
  31414. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  31415. }
  31416. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  31417. var dataType = undefined;
  31418. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  31419. dataType = Animation.ANIMATIONTYPE_FLOAT;
  31420. }
  31421. else if (from instanceof BABYLON.Quaternion) {
  31422. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  31423. }
  31424. else if (from instanceof BABYLON.Vector3) {
  31425. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  31426. }
  31427. else if (from instanceof BABYLON.Vector2) {
  31428. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  31429. }
  31430. else if (from instanceof BABYLON.Color3) {
  31431. dataType = Animation.ANIMATIONTYPE_COLOR3;
  31432. }
  31433. else if (from instanceof BABYLON.Size) {
  31434. dataType = Animation.ANIMATIONTYPE_SIZE;
  31435. }
  31436. if (dataType == undefined) {
  31437. return null;
  31438. }
  31439. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  31440. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  31441. animation.setKeys(keys);
  31442. if (easingFunction !== undefined) {
  31443. animation.setEasingFunction(easingFunction);
  31444. }
  31445. return animation;
  31446. };
  31447. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  31448. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  31449. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  31450. };
  31451. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  31452. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  31453. node.animations.push(animation);
  31454. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  31455. };
  31456. // Methods
  31457. /**
  31458. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31459. */
  31460. Animation.prototype.toString = function (fullDetails) {
  31461. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  31462. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  31463. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  31464. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  31465. if (fullDetails) {
  31466. ret += ", Ranges: {";
  31467. var first = true;
  31468. for (var name in this._ranges) {
  31469. if (first) {
  31470. ret += ", ";
  31471. first = false;
  31472. }
  31473. ret += name;
  31474. }
  31475. ret += "}";
  31476. }
  31477. return ret;
  31478. };
  31479. /**
  31480. * Add an event to this animation.
  31481. */
  31482. Animation.prototype.addEvent = function (event) {
  31483. this._events.push(event);
  31484. };
  31485. /**
  31486. * Remove all events found at the given frame
  31487. * @param frame
  31488. */
  31489. Animation.prototype.removeEvents = function (frame) {
  31490. for (var index = 0; index < this._events.length; index++) {
  31491. if (this._events[index].frame === frame) {
  31492. this._events.splice(index, 1);
  31493. index--;
  31494. }
  31495. }
  31496. };
  31497. Animation.prototype.createRange = function (name, from, to) {
  31498. // check name not already in use; could happen for bones after serialized
  31499. if (!this._ranges[name]) {
  31500. this._ranges[name] = new AnimationRange(name, from, to);
  31501. }
  31502. };
  31503. Animation.prototype.deleteRange = function (name, deleteFrames) {
  31504. if (deleteFrames === void 0) { deleteFrames = true; }
  31505. if (this._ranges[name]) {
  31506. if (deleteFrames) {
  31507. var from = this._ranges[name].from;
  31508. var to = this._ranges[name].to;
  31509. // this loop MUST go high to low for multiple splices to work
  31510. for (var key = this._keys.length - 1; key >= 0; key--) {
  31511. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  31512. this._keys.splice(key, 1);
  31513. }
  31514. }
  31515. }
  31516. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  31517. }
  31518. };
  31519. Animation.prototype.getRange = function (name) {
  31520. return this._ranges[name];
  31521. };
  31522. Animation.prototype.reset = function () {
  31523. this._offsetsCache = {};
  31524. this._highLimitsCache = {};
  31525. this.currentFrame = 0;
  31526. this._blendingFactor = 0;
  31527. this._originalBlendValue = null;
  31528. };
  31529. Animation.prototype.isStopped = function () {
  31530. return this._stopped;
  31531. };
  31532. Animation.prototype.getKeys = function () {
  31533. return this._keys;
  31534. };
  31535. Animation.prototype.getHighestFrame = function () {
  31536. var ret = 0;
  31537. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  31538. if (ret < this._keys[key].frame) {
  31539. ret = this._keys[key].frame;
  31540. }
  31541. }
  31542. return ret;
  31543. };
  31544. Animation.prototype.getEasingFunction = function () {
  31545. return this._easingFunction;
  31546. };
  31547. Animation.prototype.setEasingFunction = function (easingFunction) {
  31548. this._easingFunction = easingFunction;
  31549. };
  31550. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  31551. return startValue + (endValue - startValue) * gradient;
  31552. };
  31553. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  31554. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  31555. };
  31556. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  31557. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  31558. };
  31559. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  31560. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  31561. };
  31562. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  31563. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  31564. };
  31565. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  31566. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  31567. };
  31568. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  31569. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  31570. };
  31571. Animation.prototype.clone = function () {
  31572. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  31573. clone.enableBlending = this.enableBlending;
  31574. clone.blendingSpeed = this.blendingSpeed;
  31575. if (this._keys) {
  31576. clone.setKeys(this._keys);
  31577. }
  31578. if (this._ranges) {
  31579. clone._ranges = {};
  31580. for (var name in this._ranges) {
  31581. clone._ranges[name] = this._ranges[name].clone();
  31582. }
  31583. }
  31584. return clone;
  31585. };
  31586. Animation.prototype.setKeys = function (values) {
  31587. this._keys = values.slice(0);
  31588. this._offsetsCache = {};
  31589. this._highLimitsCache = {};
  31590. };
  31591. Animation.prototype._getKeyValue = function (value) {
  31592. if (typeof value === "function") {
  31593. return value();
  31594. }
  31595. return value;
  31596. };
  31597. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  31598. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  31599. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  31600. }
  31601. this.currentFrame = currentFrame;
  31602. // Try to get a hash to find the right key
  31603. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  31604. if (this._keys[startKey].frame >= currentFrame) {
  31605. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  31606. startKey--;
  31607. }
  31608. }
  31609. for (var key = startKey; key < this._keys.length; key++) {
  31610. if (this._keys[key + 1].frame >= currentFrame) {
  31611. var startValue = this._getKeyValue(this._keys[key].value);
  31612. var endValue = this._getKeyValue(this._keys[key + 1].value);
  31613. // gradient : percent of currentFrame between the frame inf and the frame sup
  31614. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  31615. // check for easingFunction and correction of gradient
  31616. if (this._easingFunction != null) {
  31617. gradient = this._easingFunction.ease(gradient);
  31618. }
  31619. switch (this.dataType) {
  31620. // Float
  31621. case Animation.ANIMATIONTYPE_FLOAT:
  31622. switch (loopMode) {
  31623. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31624. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31625. return this.floatInterpolateFunction(startValue, endValue, gradient);
  31626. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31627. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  31628. }
  31629. break;
  31630. // Quaternion
  31631. case Animation.ANIMATIONTYPE_QUATERNION:
  31632. var quaternion = null;
  31633. switch (loopMode) {
  31634. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31635. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31636. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  31637. break;
  31638. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31639. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  31640. break;
  31641. }
  31642. return quaternion;
  31643. // Vector3
  31644. case Animation.ANIMATIONTYPE_VECTOR3:
  31645. switch (loopMode) {
  31646. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31647. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31648. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  31649. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31650. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  31651. }
  31652. // Vector2
  31653. case Animation.ANIMATIONTYPE_VECTOR2:
  31654. switch (loopMode) {
  31655. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31656. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31657. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  31658. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31659. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  31660. }
  31661. // Size
  31662. case Animation.ANIMATIONTYPE_SIZE:
  31663. switch (loopMode) {
  31664. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31665. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31666. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  31667. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31668. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  31669. }
  31670. // Color3
  31671. case Animation.ANIMATIONTYPE_COLOR3:
  31672. switch (loopMode) {
  31673. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31674. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31675. return this.color3InterpolateFunction(startValue, endValue, gradient);
  31676. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31677. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  31678. }
  31679. // Matrix
  31680. case Animation.ANIMATIONTYPE_MATRIX:
  31681. switch (loopMode) {
  31682. case Animation.ANIMATIONLOOPMODE_CYCLE:
  31683. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  31684. if (this.allowMatricesInterpolation) {
  31685. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  31686. }
  31687. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  31688. return startValue;
  31689. }
  31690. default:
  31691. break;
  31692. }
  31693. break;
  31694. }
  31695. }
  31696. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  31697. };
  31698. Animation.prototype.setValue = function (currentValue, blend) {
  31699. if (blend === void 0) { blend = false; }
  31700. // Set value
  31701. var path;
  31702. var destination;
  31703. if (this.targetPropertyPath.length > 1) {
  31704. var property = this._target[this.targetPropertyPath[0]];
  31705. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  31706. property = property[this.targetPropertyPath[index]];
  31707. }
  31708. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  31709. destination = property;
  31710. }
  31711. else {
  31712. path = this.targetPropertyPath[0];
  31713. destination = this._target;
  31714. }
  31715. // Blending
  31716. if (this.enableBlending && this._blendingFactor <= 1.0) {
  31717. if (!this._originalBlendValue) {
  31718. if (destination[path].clone) {
  31719. this._originalBlendValue = destination[path].clone();
  31720. }
  31721. else {
  31722. this._originalBlendValue = destination[path];
  31723. }
  31724. }
  31725. if (this._originalBlendValue.prototype) {
  31726. if (this._originalBlendValue.prototype.Lerp) {
  31727. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  31728. }
  31729. else {
  31730. destination[path] = currentValue;
  31731. }
  31732. }
  31733. else if (this._originalBlendValue.m) {
  31734. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  31735. }
  31736. else {
  31737. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  31738. }
  31739. this._blendingFactor += this.blendingSpeed;
  31740. }
  31741. else {
  31742. destination[path] = currentValue;
  31743. }
  31744. if (this._target.markAsDirty) {
  31745. this._target.markAsDirty(this.targetProperty);
  31746. }
  31747. };
  31748. Animation.prototype.goToFrame = function (frame) {
  31749. if (frame < this._keys[0].frame) {
  31750. frame = this._keys[0].frame;
  31751. }
  31752. else if (frame > this._keys[this._keys.length - 1].frame) {
  31753. frame = this._keys[this._keys.length - 1].frame;
  31754. }
  31755. var currentValue = this._interpolate(frame, 0, this.loopMode);
  31756. this.setValue(currentValue);
  31757. };
  31758. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  31759. if (blend === void 0) { blend = false; }
  31760. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  31761. this._stopped = true;
  31762. return false;
  31763. }
  31764. var returnValue = true;
  31765. // Adding a start key at frame 0 if missing
  31766. if (this._keys[0].frame !== 0) {
  31767. var newKey = { frame: 0, value: this._keys[0].value };
  31768. this._keys.splice(0, 0, newKey);
  31769. }
  31770. // Check limits
  31771. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  31772. from = this._keys[0].frame;
  31773. }
  31774. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  31775. to = this._keys[this._keys.length - 1].frame;
  31776. }
  31777. //to and from cannot be the same key
  31778. if (from === to) {
  31779. from++;
  31780. }
  31781. // Compute ratio
  31782. var range = to - from;
  31783. var offsetValue;
  31784. // ratio represents the frame delta between from and to
  31785. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  31786. var highLimitValue = 0;
  31787. if (ratio > range && !loop) {
  31788. returnValue = false;
  31789. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  31790. }
  31791. else {
  31792. // Get max value if required
  31793. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  31794. var keyOffset = to.toString() + from.toString();
  31795. if (!this._offsetsCache[keyOffset]) {
  31796. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  31797. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  31798. switch (this.dataType) {
  31799. // Float
  31800. case Animation.ANIMATIONTYPE_FLOAT:
  31801. this._offsetsCache[keyOffset] = toValue - fromValue;
  31802. break;
  31803. // Quaternion
  31804. case Animation.ANIMATIONTYPE_QUATERNION:
  31805. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  31806. break;
  31807. // Vector3
  31808. case Animation.ANIMATIONTYPE_VECTOR3:
  31809. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  31810. // Vector2
  31811. case Animation.ANIMATIONTYPE_VECTOR2:
  31812. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  31813. // Size
  31814. case Animation.ANIMATIONTYPE_SIZE:
  31815. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  31816. // Color3
  31817. case Animation.ANIMATIONTYPE_COLOR3:
  31818. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  31819. default:
  31820. break;
  31821. }
  31822. this._highLimitsCache[keyOffset] = toValue;
  31823. }
  31824. highLimitValue = this._highLimitsCache[keyOffset];
  31825. offsetValue = this._offsetsCache[keyOffset];
  31826. }
  31827. }
  31828. if (offsetValue === undefined) {
  31829. switch (this.dataType) {
  31830. // Float
  31831. case Animation.ANIMATIONTYPE_FLOAT:
  31832. offsetValue = 0;
  31833. break;
  31834. // Quaternion
  31835. case Animation.ANIMATIONTYPE_QUATERNION:
  31836. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  31837. break;
  31838. // Vector3
  31839. case Animation.ANIMATIONTYPE_VECTOR3:
  31840. offsetValue = BABYLON.Vector3.Zero();
  31841. break;
  31842. // Vector2
  31843. case Animation.ANIMATIONTYPE_VECTOR2:
  31844. offsetValue = BABYLON.Vector2.Zero();
  31845. break;
  31846. // Size
  31847. case Animation.ANIMATIONTYPE_SIZE:
  31848. offsetValue = BABYLON.Size.Zero();
  31849. break;
  31850. // Color3
  31851. case Animation.ANIMATIONTYPE_COLOR3:
  31852. offsetValue = BABYLON.Color3.Black();
  31853. }
  31854. }
  31855. // Compute value
  31856. var repeatCount = (ratio / range) >> 0;
  31857. var currentFrame = returnValue ? from + ratio % range : to;
  31858. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  31859. // Set value
  31860. this.setValue(currentValue);
  31861. // Check events
  31862. for (var index = 0; index < this._events.length; index++) {
  31863. if (currentFrame >= this._events[index].frame) {
  31864. var event = this._events[index];
  31865. if (!event.isDone) {
  31866. // If event should be done only once, remove it.
  31867. if (event.onlyOnce) {
  31868. this._events.splice(index, 1);
  31869. index--;
  31870. }
  31871. event.isDone = true;
  31872. event.action();
  31873. } // Don't do anything if the event has already be done.
  31874. }
  31875. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  31876. // reset event, the animation is looping
  31877. this._events[index].isDone = false;
  31878. }
  31879. }
  31880. if (!returnValue) {
  31881. this._stopped = true;
  31882. }
  31883. return returnValue;
  31884. };
  31885. Animation.prototype.serialize = function () {
  31886. var serializationObject = {};
  31887. serializationObject.name = this.name;
  31888. serializationObject.property = this.targetProperty;
  31889. serializationObject.framePerSecond = this.framePerSecond;
  31890. serializationObject.dataType = this.dataType;
  31891. serializationObject.loopBehavior = this.loopMode;
  31892. serializationObject.enableBlending = this.enableBlending;
  31893. serializationObject.blendingSpeed = this.blendingSpeed;
  31894. var dataType = this.dataType;
  31895. serializationObject.keys = [];
  31896. var keys = this.getKeys();
  31897. for (var index = 0; index < keys.length; index++) {
  31898. var animationKey = keys[index];
  31899. var key = {};
  31900. key.frame = animationKey.frame;
  31901. switch (dataType) {
  31902. case Animation.ANIMATIONTYPE_FLOAT:
  31903. key.values = [animationKey.value];
  31904. break;
  31905. case Animation.ANIMATIONTYPE_QUATERNION:
  31906. case Animation.ANIMATIONTYPE_MATRIX:
  31907. case Animation.ANIMATIONTYPE_VECTOR3:
  31908. case Animation.ANIMATIONTYPE_COLOR3:
  31909. key.values = animationKey.value.asArray();
  31910. break;
  31911. }
  31912. serializationObject.keys.push(key);
  31913. }
  31914. serializationObject.ranges = [];
  31915. for (var name in this._ranges) {
  31916. var range = {};
  31917. range.name = name;
  31918. range.from = this._ranges[name].from;
  31919. range.to = this._ranges[name].to;
  31920. serializationObject.ranges.push(range);
  31921. }
  31922. return serializationObject;
  31923. };
  31924. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  31925. get: function () {
  31926. return Animation._ANIMATIONTYPE_FLOAT;
  31927. },
  31928. enumerable: true,
  31929. configurable: true
  31930. });
  31931. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  31932. get: function () {
  31933. return Animation._ANIMATIONTYPE_VECTOR3;
  31934. },
  31935. enumerable: true,
  31936. configurable: true
  31937. });
  31938. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  31939. get: function () {
  31940. return Animation._ANIMATIONTYPE_VECTOR2;
  31941. },
  31942. enumerable: true,
  31943. configurable: true
  31944. });
  31945. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  31946. get: function () {
  31947. return Animation._ANIMATIONTYPE_SIZE;
  31948. },
  31949. enumerable: true,
  31950. configurable: true
  31951. });
  31952. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  31953. get: function () {
  31954. return Animation._ANIMATIONTYPE_QUATERNION;
  31955. },
  31956. enumerable: true,
  31957. configurable: true
  31958. });
  31959. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  31960. get: function () {
  31961. return Animation._ANIMATIONTYPE_MATRIX;
  31962. },
  31963. enumerable: true,
  31964. configurable: true
  31965. });
  31966. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  31967. get: function () {
  31968. return Animation._ANIMATIONTYPE_COLOR3;
  31969. },
  31970. enumerable: true,
  31971. configurable: true
  31972. });
  31973. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  31974. get: function () {
  31975. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  31976. },
  31977. enumerable: true,
  31978. configurable: true
  31979. });
  31980. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  31981. get: function () {
  31982. return Animation._ANIMATIONLOOPMODE_CYCLE;
  31983. },
  31984. enumerable: true,
  31985. configurable: true
  31986. });
  31987. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  31988. get: function () {
  31989. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  31990. },
  31991. enumerable: true,
  31992. configurable: true
  31993. });
  31994. Animation.Parse = function (parsedAnimation) {
  31995. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  31996. var dataType = parsedAnimation.dataType;
  31997. var keys = [];
  31998. var data;
  31999. var index;
  32000. if (parsedAnimation.enableBlending) {
  32001. animation.enableBlending = parsedAnimation.enableBlending;
  32002. }
  32003. if (parsedAnimation.blendingSpeed) {
  32004. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  32005. }
  32006. for (index = 0; index < parsedAnimation.keys.length; index++) {
  32007. var key = parsedAnimation.keys[index];
  32008. switch (dataType) {
  32009. case Animation.ANIMATIONTYPE_FLOAT:
  32010. data = key.values[0];
  32011. break;
  32012. case Animation.ANIMATIONTYPE_QUATERNION:
  32013. data = BABYLON.Quaternion.FromArray(key.values);
  32014. break;
  32015. case Animation.ANIMATIONTYPE_MATRIX:
  32016. data = BABYLON.Matrix.FromArray(key.values);
  32017. break;
  32018. case Animation.ANIMATIONTYPE_COLOR3:
  32019. data = BABYLON.Color3.FromArray(key.values);
  32020. break;
  32021. case Animation.ANIMATIONTYPE_VECTOR3:
  32022. default:
  32023. data = BABYLON.Vector3.FromArray(key.values);
  32024. break;
  32025. }
  32026. keys.push({
  32027. frame: key.frame,
  32028. value: data
  32029. });
  32030. }
  32031. animation.setKeys(keys);
  32032. if (parsedAnimation.ranges) {
  32033. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  32034. data = parsedAnimation.ranges[index];
  32035. animation.createRange(data.name, data.from, data.to);
  32036. }
  32037. }
  32038. return animation;
  32039. };
  32040. Animation.AppendSerializedAnimations = function (source, destination) {
  32041. if (source.animations) {
  32042. destination.animations = [];
  32043. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  32044. var animation = source.animations[animationIndex];
  32045. destination.animations.push(animation.serialize());
  32046. }
  32047. }
  32048. };
  32049. return Animation;
  32050. }());
  32051. // Statics
  32052. Animation._ANIMATIONTYPE_FLOAT = 0;
  32053. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  32054. Animation._ANIMATIONTYPE_QUATERNION = 2;
  32055. Animation._ANIMATIONTYPE_MATRIX = 3;
  32056. Animation._ANIMATIONTYPE_COLOR3 = 4;
  32057. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  32058. Animation._ANIMATIONTYPE_SIZE = 6;
  32059. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  32060. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  32061. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  32062. BABYLON.Animation = Animation;
  32063. })(BABYLON || (BABYLON = {}));
  32064. //# sourceMappingURL=babylon.animation.js.map
  32065. var BABYLON;
  32066. (function (BABYLON) {
  32067. var Animatable = (function () {
  32068. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  32069. if (fromFrame === void 0) { fromFrame = 0; }
  32070. if (toFrame === void 0) { toFrame = 100; }
  32071. if (loopAnimation === void 0) { loopAnimation = false; }
  32072. if (speedRatio === void 0) { speedRatio = 1.0; }
  32073. this.target = target;
  32074. this.fromFrame = fromFrame;
  32075. this.toFrame = toFrame;
  32076. this.loopAnimation = loopAnimation;
  32077. this.speedRatio = speedRatio;
  32078. this.onAnimationEnd = onAnimationEnd;
  32079. this._animations = new Array();
  32080. this._paused = false;
  32081. this.animationStarted = false;
  32082. if (animations) {
  32083. this.appendAnimations(target, animations);
  32084. }
  32085. this._scene = scene;
  32086. scene._activeAnimatables.push(this);
  32087. }
  32088. // Methods
  32089. Animatable.prototype.getAnimations = function () {
  32090. return this._animations;
  32091. };
  32092. Animatable.prototype.appendAnimations = function (target, animations) {
  32093. for (var index = 0; index < animations.length; index++) {
  32094. var animation = animations[index];
  32095. animation._target = target;
  32096. this._animations.push(animation);
  32097. }
  32098. };
  32099. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  32100. var animations = this._animations;
  32101. for (var index = 0; index < animations.length; index++) {
  32102. if (animations[index].targetProperty === property) {
  32103. return animations[index];
  32104. }
  32105. }
  32106. return null;
  32107. };
  32108. Animatable.prototype.reset = function () {
  32109. var animations = this._animations;
  32110. for (var index = 0; index < animations.length; index++) {
  32111. animations[index].reset();
  32112. }
  32113. this._localDelayOffset = null;
  32114. this._pausedDelay = null;
  32115. };
  32116. Animatable.prototype.enableBlending = function (blendingSpeed) {
  32117. var animations = this._animations;
  32118. for (var index = 0; index < animations.length; index++) {
  32119. animations[index].enableBlending = true;
  32120. animations[index].blendingSpeed = blendingSpeed;
  32121. }
  32122. };
  32123. Animatable.prototype.disableBlending = function () {
  32124. var animations = this._animations;
  32125. for (var index = 0; index < animations.length; index++) {
  32126. animations[index].enableBlending = false;
  32127. }
  32128. };
  32129. Animatable.prototype.goToFrame = function (frame) {
  32130. var animations = this._animations;
  32131. if (animations[0]) {
  32132. var fps = animations[0].framePerSecond;
  32133. var currentFrame = animations[0].currentFrame;
  32134. var adjustTime = frame - currentFrame;
  32135. var delay = adjustTime * 1000 / fps;
  32136. this._localDelayOffset -= delay;
  32137. }
  32138. for (var index = 0; index < animations.length; index++) {
  32139. animations[index].goToFrame(frame);
  32140. }
  32141. };
  32142. Animatable.prototype.pause = function () {
  32143. if (this._paused) {
  32144. return;
  32145. }
  32146. this._paused = true;
  32147. };
  32148. Animatable.prototype.restart = function () {
  32149. this._paused = false;
  32150. };
  32151. Animatable.prototype.stop = function (animationName) {
  32152. if (animationName) {
  32153. var idx = this._scene._activeAnimatables.indexOf(this);
  32154. if (idx > -1) {
  32155. var animations = this._animations;
  32156. for (var index = animations.length - 1; index >= 0; index--) {
  32157. if (typeof animationName === "string" && animations[index].name != animationName) {
  32158. continue;
  32159. }
  32160. animations[index].reset();
  32161. animations.splice(index, 1);
  32162. }
  32163. if (animations.length == 0) {
  32164. this._scene._activeAnimatables.splice(idx, 1);
  32165. if (this.onAnimationEnd) {
  32166. this.onAnimationEnd();
  32167. }
  32168. }
  32169. }
  32170. }
  32171. else {
  32172. var index = this._scene._activeAnimatables.indexOf(this);
  32173. if (index > -1) {
  32174. this._scene._activeAnimatables.splice(index, 1);
  32175. var animations = this._animations;
  32176. for (var index = 0; index < animations.length; index++) {
  32177. animations[index].reset();
  32178. }
  32179. if (this.onAnimationEnd) {
  32180. this.onAnimationEnd();
  32181. }
  32182. }
  32183. }
  32184. };
  32185. Animatable.prototype._animate = function (delay) {
  32186. if (this._paused) {
  32187. this.animationStarted = false;
  32188. if (!this._pausedDelay) {
  32189. this._pausedDelay = delay;
  32190. }
  32191. return true;
  32192. }
  32193. if (!this._localDelayOffset) {
  32194. this._localDelayOffset = delay;
  32195. }
  32196. else if (this._pausedDelay) {
  32197. this._localDelayOffset += delay - this._pausedDelay;
  32198. this._pausedDelay = null;
  32199. }
  32200. // Animating
  32201. var running = false;
  32202. var animations = this._animations;
  32203. var index;
  32204. for (index = 0; index < animations.length; index++) {
  32205. var animation = animations[index];
  32206. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  32207. running = running || isRunning;
  32208. }
  32209. this.animationStarted = running;
  32210. if (!running) {
  32211. // Remove from active animatables
  32212. index = this._scene._activeAnimatables.indexOf(this);
  32213. this._scene._activeAnimatables.splice(index, 1);
  32214. }
  32215. if (!running && this.onAnimationEnd) {
  32216. this.onAnimationEnd();
  32217. this.onAnimationEnd = null;
  32218. }
  32219. return running;
  32220. };
  32221. return Animatable;
  32222. }());
  32223. BABYLON.Animatable = Animatable;
  32224. })(BABYLON || (BABYLON = {}));
  32225. //# sourceMappingURL=babylon.animatable.js.map
  32226. var BABYLON;
  32227. (function (BABYLON) {
  32228. var EasingFunction = (function () {
  32229. function EasingFunction() {
  32230. // Properties
  32231. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  32232. }
  32233. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  32234. get: function () {
  32235. return EasingFunction._EASINGMODE_EASEIN;
  32236. },
  32237. enumerable: true,
  32238. configurable: true
  32239. });
  32240. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  32241. get: function () {
  32242. return EasingFunction._EASINGMODE_EASEOUT;
  32243. },
  32244. enumerable: true,
  32245. configurable: true
  32246. });
  32247. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  32248. get: function () {
  32249. return EasingFunction._EASINGMODE_EASEINOUT;
  32250. },
  32251. enumerable: true,
  32252. configurable: true
  32253. });
  32254. EasingFunction.prototype.setEasingMode = function (easingMode) {
  32255. var n = Math.min(Math.max(easingMode, 0), 2);
  32256. this._easingMode = n;
  32257. };
  32258. EasingFunction.prototype.getEasingMode = function () {
  32259. return this._easingMode;
  32260. };
  32261. EasingFunction.prototype.easeInCore = function (gradient) {
  32262. throw new Error('You must implement this method');
  32263. };
  32264. EasingFunction.prototype.ease = function (gradient) {
  32265. switch (this._easingMode) {
  32266. case EasingFunction.EASINGMODE_EASEIN:
  32267. return this.easeInCore(gradient);
  32268. case EasingFunction.EASINGMODE_EASEOUT:
  32269. return (1 - this.easeInCore(1 - gradient));
  32270. }
  32271. if (gradient >= 0.5) {
  32272. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  32273. }
  32274. return (this.easeInCore(gradient * 2) * 0.5);
  32275. };
  32276. return EasingFunction;
  32277. }());
  32278. //Statics
  32279. EasingFunction._EASINGMODE_EASEIN = 0;
  32280. EasingFunction._EASINGMODE_EASEOUT = 1;
  32281. EasingFunction._EASINGMODE_EASEINOUT = 2;
  32282. BABYLON.EasingFunction = EasingFunction;
  32283. var CircleEase = (function (_super) {
  32284. __extends(CircleEase, _super);
  32285. function CircleEase() {
  32286. return _super !== null && _super.apply(this, arguments) || this;
  32287. }
  32288. CircleEase.prototype.easeInCore = function (gradient) {
  32289. gradient = Math.max(0, Math.min(1, gradient));
  32290. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  32291. };
  32292. return CircleEase;
  32293. }(EasingFunction));
  32294. BABYLON.CircleEase = CircleEase;
  32295. var BackEase = (function (_super) {
  32296. __extends(BackEase, _super);
  32297. function BackEase(amplitude) {
  32298. if (amplitude === void 0) { amplitude = 1; }
  32299. var _this = _super.call(this) || this;
  32300. _this.amplitude = amplitude;
  32301. return _this;
  32302. }
  32303. BackEase.prototype.easeInCore = function (gradient) {
  32304. var num = Math.max(0, this.amplitude);
  32305. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  32306. };
  32307. return BackEase;
  32308. }(EasingFunction));
  32309. BABYLON.BackEase = BackEase;
  32310. var BounceEase = (function (_super) {
  32311. __extends(BounceEase, _super);
  32312. function BounceEase(bounces, bounciness) {
  32313. if (bounces === void 0) { bounces = 3; }
  32314. if (bounciness === void 0) { bounciness = 2; }
  32315. var _this = _super.call(this) || this;
  32316. _this.bounces = bounces;
  32317. _this.bounciness = bounciness;
  32318. return _this;
  32319. }
  32320. BounceEase.prototype.easeInCore = function (gradient) {
  32321. var y = Math.max(0.0, this.bounces);
  32322. var bounciness = this.bounciness;
  32323. if (bounciness <= 1.0) {
  32324. bounciness = 1.001;
  32325. }
  32326. var num9 = Math.pow(bounciness, y);
  32327. var num5 = 1.0 - bounciness;
  32328. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  32329. var num15 = gradient * num4;
  32330. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  32331. var num3 = Math.floor(num65);
  32332. var num13 = num3 + 1.0;
  32333. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  32334. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  32335. var num7 = (num8 + num12) * 0.5;
  32336. var num6 = gradient - num7;
  32337. var num2 = num7 - num8;
  32338. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  32339. };
  32340. return BounceEase;
  32341. }(EasingFunction));
  32342. BABYLON.BounceEase = BounceEase;
  32343. var CubicEase = (function (_super) {
  32344. __extends(CubicEase, _super);
  32345. function CubicEase() {
  32346. return _super !== null && _super.apply(this, arguments) || this;
  32347. }
  32348. CubicEase.prototype.easeInCore = function (gradient) {
  32349. return (gradient * gradient * gradient);
  32350. };
  32351. return CubicEase;
  32352. }(EasingFunction));
  32353. BABYLON.CubicEase = CubicEase;
  32354. var ElasticEase = (function (_super) {
  32355. __extends(ElasticEase, _super);
  32356. function ElasticEase(oscillations, springiness) {
  32357. if (oscillations === void 0) { oscillations = 3; }
  32358. if (springiness === void 0) { springiness = 3; }
  32359. var _this = _super.call(this) || this;
  32360. _this.oscillations = oscillations;
  32361. _this.springiness = springiness;
  32362. return _this;
  32363. }
  32364. ElasticEase.prototype.easeInCore = function (gradient) {
  32365. var num2;
  32366. var num3 = Math.max(0.0, this.oscillations);
  32367. var num = Math.max(0.0, this.springiness);
  32368. if (num == 0) {
  32369. num2 = gradient;
  32370. }
  32371. else {
  32372. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  32373. }
  32374. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  32375. };
  32376. return ElasticEase;
  32377. }(EasingFunction));
  32378. BABYLON.ElasticEase = ElasticEase;
  32379. var ExponentialEase = (function (_super) {
  32380. __extends(ExponentialEase, _super);
  32381. function ExponentialEase(exponent) {
  32382. if (exponent === void 0) { exponent = 2; }
  32383. var _this = _super.call(this) || this;
  32384. _this.exponent = exponent;
  32385. return _this;
  32386. }
  32387. ExponentialEase.prototype.easeInCore = function (gradient) {
  32388. if (this.exponent <= 0) {
  32389. return gradient;
  32390. }
  32391. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  32392. };
  32393. return ExponentialEase;
  32394. }(EasingFunction));
  32395. BABYLON.ExponentialEase = ExponentialEase;
  32396. var PowerEase = (function (_super) {
  32397. __extends(PowerEase, _super);
  32398. function PowerEase(power) {
  32399. if (power === void 0) { power = 2; }
  32400. var _this = _super.call(this) || this;
  32401. _this.power = power;
  32402. return _this;
  32403. }
  32404. PowerEase.prototype.easeInCore = function (gradient) {
  32405. var y = Math.max(0.0, this.power);
  32406. return Math.pow(gradient, y);
  32407. };
  32408. return PowerEase;
  32409. }(EasingFunction));
  32410. BABYLON.PowerEase = PowerEase;
  32411. var QuadraticEase = (function (_super) {
  32412. __extends(QuadraticEase, _super);
  32413. function QuadraticEase() {
  32414. return _super !== null && _super.apply(this, arguments) || this;
  32415. }
  32416. QuadraticEase.prototype.easeInCore = function (gradient) {
  32417. return (gradient * gradient);
  32418. };
  32419. return QuadraticEase;
  32420. }(EasingFunction));
  32421. BABYLON.QuadraticEase = QuadraticEase;
  32422. var QuarticEase = (function (_super) {
  32423. __extends(QuarticEase, _super);
  32424. function QuarticEase() {
  32425. return _super !== null && _super.apply(this, arguments) || this;
  32426. }
  32427. QuarticEase.prototype.easeInCore = function (gradient) {
  32428. return (gradient * gradient * gradient * gradient);
  32429. };
  32430. return QuarticEase;
  32431. }(EasingFunction));
  32432. BABYLON.QuarticEase = QuarticEase;
  32433. var QuinticEase = (function (_super) {
  32434. __extends(QuinticEase, _super);
  32435. function QuinticEase() {
  32436. return _super !== null && _super.apply(this, arguments) || this;
  32437. }
  32438. QuinticEase.prototype.easeInCore = function (gradient) {
  32439. return (gradient * gradient * gradient * gradient * gradient);
  32440. };
  32441. return QuinticEase;
  32442. }(EasingFunction));
  32443. BABYLON.QuinticEase = QuinticEase;
  32444. var SineEase = (function (_super) {
  32445. __extends(SineEase, _super);
  32446. function SineEase() {
  32447. return _super !== null && _super.apply(this, arguments) || this;
  32448. }
  32449. SineEase.prototype.easeInCore = function (gradient) {
  32450. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  32451. };
  32452. return SineEase;
  32453. }(EasingFunction));
  32454. BABYLON.SineEase = SineEase;
  32455. var BezierCurveEase = (function (_super) {
  32456. __extends(BezierCurveEase, _super);
  32457. function BezierCurveEase(x1, y1, x2, y2) {
  32458. if (x1 === void 0) { x1 = 0; }
  32459. if (y1 === void 0) { y1 = 0; }
  32460. if (x2 === void 0) { x2 = 1; }
  32461. if (y2 === void 0) { y2 = 1; }
  32462. var _this = _super.call(this) || this;
  32463. _this.x1 = x1;
  32464. _this.y1 = y1;
  32465. _this.x2 = x2;
  32466. _this.y2 = y2;
  32467. return _this;
  32468. }
  32469. BezierCurveEase.prototype.easeInCore = function (gradient) {
  32470. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  32471. };
  32472. return BezierCurveEase;
  32473. }(EasingFunction));
  32474. BABYLON.BezierCurveEase = BezierCurveEase;
  32475. })(BABYLON || (BABYLON = {}));
  32476. //# sourceMappingURL=babylon.easing.js.map
  32477. var BABYLON;
  32478. (function (BABYLON) {
  32479. var Condition = (function () {
  32480. function Condition(actionManager) {
  32481. this._actionManager = actionManager;
  32482. }
  32483. Condition.prototype.isValid = function () {
  32484. return true;
  32485. };
  32486. Condition.prototype._getProperty = function (propertyPath) {
  32487. return this._actionManager._getProperty(propertyPath);
  32488. };
  32489. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  32490. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32491. };
  32492. Condition.prototype.serialize = function () {
  32493. };
  32494. Condition.prototype._serialize = function (serializedCondition) {
  32495. return {
  32496. type: 2,
  32497. children: [],
  32498. name: serializedCondition.name,
  32499. properties: serializedCondition.properties
  32500. };
  32501. };
  32502. return Condition;
  32503. }());
  32504. BABYLON.Condition = Condition;
  32505. var ValueCondition = (function (_super) {
  32506. __extends(ValueCondition, _super);
  32507. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  32508. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  32509. var _this = _super.call(this, actionManager) || this;
  32510. _this.propertyPath = propertyPath;
  32511. _this.value = value;
  32512. _this.operator = operator;
  32513. _this._target = target;
  32514. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  32515. _this._property = _this._getProperty(_this.propertyPath);
  32516. return _this;
  32517. }
  32518. Object.defineProperty(ValueCondition, "IsEqual", {
  32519. get: function () {
  32520. return ValueCondition._IsEqual;
  32521. },
  32522. enumerable: true,
  32523. configurable: true
  32524. });
  32525. Object.defineProperty(ValueCondition, "IsDifferent", {
  32526. get: function () {
  32527. return ValueCondition._IsDifferent;
  32528. },
  32529. enumerable: true,
  32530. configurable: true
  32531. });
  32532. Object.defineProperty(ValueCondition, "IsGreater", {
  32533. get: function () {
  32534. return ValueCondition._IsGreater;
  32535. },
  32536. enumerable: true,
  32537. configurable: true
  32538. });
  32539. Object.defineProperty(ValueCondition, "IsLesser", {
  32540. get: function () {
  32541. return ValueCondition._IsLesser;
  32542. },
  32543. enumerable: true,
  32544. configurable: true
  32545. });
  32546. // Methods
  32547. ValueCondition.prototype.isValid = function () {
  32548. switch (this.operator) {
  32549. case ValueCondition.IsGreater:
  32550. return this._effectiveTarget[this._property] > this.value;
  32551. case ValueCondition.IsLesser:
  32552. return this._effectiveTarget[this._property] < this.value;
  32553. case ValueCondition.IsEqual:
  32554. case ValueCondition.IsDifferent:
  32555. var check;
  32556. if (this.value.equals) {
  32557. check = this.value.equals(this._effectiveTarget[this._property]);
  32558. }
  32559. else {
  32560. check = this.value === this._effectiveTarget[this._property];
  32561. }
  32562. return this.operator === ValueCondition.IsEqual ? check : !check;
  32563. }
  32564. return false;
  32565. };
  32566. ValueCondition.prototype.serialize = function () {
  32567. return this._serialize({
  32568. name: "ValueCondition",
  32569. properties: [
  32570. BABYLON.Action._GetTargetProperty(this._target),
  32571. { name: "propertyPath", value: this.propertyPath },
  32572. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32573. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  32574. ]
  32575. });
  32576. };
  32577. ValueCondition.GetOperatorName = function (operator) {
  32578. switch (operator) {
  32579. case ValueCondition._IsEqual: return "IsEqual";
  32580. case ValueCondition._IsDifferent: return "IsDifferent";
  32581. case ValueCondition._IsGreater: return "IsGreater";
  32582. case ValueCondition._IsLesser: return "IsLesser";
  32583. default: return "";
  32584. }
  32585. };
  32586. return ValueCondition;
  32587. }(Condition));
  32588. // Statics
  32589. ValueCondition._IsEqual = 0;
  32590. ValueCondition._IsDifferent = 1;
  32591. ValueCondition._IsGreater = 2;
  32592. ValueCondition._IsLesser = 3;
  32593. BABYLON.ValueCondition = ValueCondition;
  32594. var PredicateCondition = (function (_super) {
  32595. __extends(PredicateCondition, _super);
  32596. function PredicateCondition(actionManager, predicate) {
  32597. var _this = _super.call(this, actionManager) || this;
  32598. _this.predicate = predicate;
  32599. return _this;
  32600. }
  32601. PredicateCondition.prototype.isValid = function () {
  32602. return this.predicate();
  32603. };
  32604. return PredicateCondition;
  32605. }(Condition));
  32606. BABYLON.PredicateCondition = PredicateCondition;
  32607. var StateCondition = (function (_super) {
  32608. __extends(StateCondition, _super);
  32609. function StateCondition(actionManager, target, value) {
  32610. var _this = _super.call(this, actionManager) || this;
  32611. _this.value = value;
  32612. _this._target = target;
  32613. return _this;
  32614. }
  32615. // Methods
  32616. StateCondition.prototype.isValid = function () {
  32617. return this._target.state === this.value;
  32618. };
  32619. StateCondition.prototype.serialize = function () {
  32620. return this._serialize({
  32621. name: "StateCondition",
  32622. properties: [
  32623. BABYLON.Action._GetTargetProperty(this._target),
  32624. { name: "value", value: this.value }
  32625. ]
  32626. });
  32627. };
  32628. return StateCondition;
  32629. }(Condition));
  32630. BABYLON.StateCondition = StateCondition;
  32631. })(BABYLON || (BABYLON = {}));
  32632. //# sourceMappingURL=babylon.condition.js.map
  32633. var BABYLON;
  32634. (function (BABYLON) {
  32635. var Action = (function () {
  32636. function Action(triggerOptions, condition) {
  32637. this.triggerOptions = triggerOptions;
  32638. if (triggerOptions.parameter) {
  32639. this.trigger = triggerOptions.trigger;
  32640. this._triggerParameter = triggerOptions.parameter;
  32641. }
  32642. else {
  32643. this.trigger = triggerOptions;
  32644. }
  32645. this._nextActiveAction = this;
  32646. this._condition = condition;
  32647. }
  32648. // Methods
  32649. Action.prototype._prepare = function () {
  32650. };
  32651. Action.prototype.getTriggerParameter = function () {
  32652. return this._triggerParameter;
  32653. };
  32654. Action.prototype._executeCurrent = function (evt) {
  32655. if (this._nextActiveAction._condition) {
  32656. var condition = this._nextActiveAction._condition;
  32657. var currentRenderId = this._actionManager.getScene().getRenderId();
  32658. // We cache the current evaluation for the current frame
  32659. if (condition._evaluationId === currentRenderId) {
  32660. if (!condition._currentResult) {
  32661. return;
  32662. }
  32663. }
  32664. else {
  32665. condition._evaluationId = currentRenderId;
  32666. if (!condition.isValid()) {
  32667. condition._currentResult = false;
  32668. return;
  32669. }
  32670. condition._currentResult = true;
  32671. }
  32672. }
  32673. this._nextActiveAction.execute(evt);
  32674. this.skipToNextActiveAction();
  32675. };
  32676. Action.prototype.execute = function (evt) {
  32677. };
  32678. Action.prototype.skipToNextActiveAction = function () {
  32679. if (this._nextActiveAction._child) {
  32680. if (!this._nextActiveAction._child._actionManager) {
  32681. this._nextActiveAction._child._actionManager = this._actionManager;
  32682. }
  32683. this._nextActiveAction = this._nextActiveAction._child;
  32684. }
  32685. else {
  32686. this._nextActiveAction = this;
  32687. }
  32688. };
  32689. Action.prototype.then = function (action) {
  32690. this._child = action;
  32691. action._actionManager = this._actionManager;
  32692. action._prepare();
  32693. return action;
  32694. };
  32695. Action.prototype._getProperty = function (propertyPath) {
  32696. return this._actionManager._getProperty(propertyPath);
  32697. };
  32698. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  32699. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32700. };
  32701. Action.prototype.serialize = function (parent) {
  32702. };
  32703. // Called by BABYLON.Action objects in serialize(...). Internal use
  32704. Action.prototype._serialize = function (serializedAction, parent) {
  32705. var serializationObject = {
  32706. type: 1,
  32707. children: [],
  32708. name: serializedAction.name,
  32709. properties: serializedAction.properties || []
  32710. };
  32711. // Serialize child
  32712. if (this._child) {
  32713. this._child.serialize(serializationObject);
  32714. }
  32715. // Check if "this" has a condition
  32716. if (this._condition) {
  32717. var serializedCondition = this._condition.serialize();
  32718. serializedCondition.children.push(serializationObject);
  32719. if (parent) {
  32720. parent.children.push(serializedCondition);
  32721. }
  32722. return serializedCondition;
  32723. }
  32724. if (parent) {
  32725. parent.children.push(serializationObject);
  32726. }
  32727. return serializationObject;
  32728. };
  32729. return Action;
  32730. }());
  32731. Action._SerializeValueAsString = function (value) {
  32732. if (typeof value === "number") {
  32733. return value.toString();
  32734. }
  32735. if (typeof value === "boolean") {
  32736. return value ? "true" : "false";
  32737. }
  32738. if (value instanceof BABYLON.Vector2) {
  32739. return value.x + ", " + value.y;
  32740. }
  32741. if (value instanceof BABYLON.Vector3) {
  32742. return value.x + ", " + value.y + ", " + value.z;
  32743. }
  32744. if (value instanceof BABYLON.Color3) {
  32745. return value.r + ", " + value.g + ", " + value.b;
  32746. }
  32747. if (value instanceof BABYLON.Color4) {
  32748. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  32749. }
  32750. return value; // string
  32751. };
  32752. Action._GetTargetProperty = function (target) {
  32753. return {
  32754. name: "target",
  32755. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  32756. : target instanceof BABYLON.Light ? "LightProperties"
  32757. : target instanceof BABYLON.Camera ? "CameraProperties"
  32758. : "SceneProperties",
  32759. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  32760. };
  32761. };
  32762. BABYLON.Action = Action;
  32763. })(BABYLON || (BABYLON = {}));
  32764. //# sourceMappingURL=babylon.action.js.map
  32765. var BABYLON;
  32766. (function (BABYLON) {
  32767. /**
  32768. * ActionEvent is the event beint sent when an action is triggered.
  32769. */
  32770. var ActionEvent = (function () {
  32771. /**
  32772. * @constructor
  32773. * @param source The mesh or sprite that triggered the action.
  32774. * @param pointerX The X mouse cursor position at the time of the event
  32775. * @param pointerY The Y mouse cursor position at the time of the event
  32776. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  32777. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  32778. */
  32779. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  32780. this.source = source;
  32781. this.pointerX = pointerX;
  32782. this.pointerY = pointerY;
  32783. this.meshUnderPointer = meshUnderPointer;
  32784. this.sourceEvent = sourceEvent;
  32785. this.additionalData = additionalData;
  32786. }
  32787. /**
  32788. * Helper function to auto-create an ActionEvent from a source mesh.
  32789. * @param source The source mesh that triggered the event
  32790. * @param evt {Event} The original (browser) event
  32791. */
  32792. ActionEvent.CreateNew = function (source, evt, additionalData) {
  32793. var scene = source.getScene();
  32794. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32795. };
  32796. /**
  32797. * Helper function to auto-create an ActionEvent from a source mesh.
  32798. * @param source The source sprite that triggered the event
  32799. * @param scene Scene associated with the sprite
  32800. * @param evt {Event} The original (browser) event
  32801. */
  32802. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  32803. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32804. };
  32805. /**
  32806. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  32807. * @param scene the scene where the event occurred
  32808. * @param evt {Event} The original (browser) event
  32809. */
  32810. ActionEvent.CreateNewFromScene = function (scene, evt) {
  32811. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  32812. };
  32813. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  32814. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  32815. };
  32816. return ActionEvent;
  32817. }());
  32818. BABYLON.ActionEvent = ActionEvent;
  32819. /**
  32820. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  32821. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  32822. */
  32823. var ActionManager = (function () {
  32824. function ActionManager(scene) {
  32825. // Members
  32826. this.actions = new Array();
  32827. this.hoverCursor = '';
  32828. this._scene = scene;
  32829. scene._actionManagers.push(this);
  32830. }
  32831. Object.defineProperty(ActionManager, "NothingTrigger", {
  32832. get: function () {
  32833. return ActionManager._NothingTrigger;
  32834. },
  32835. enumerable: true,
  32836. configurable: true
  32837. });
  32838. Object.defineProperty(ActionManager, "OnPickTrigger", {
  32839. get: function () {
  32840. return ActionManager._OnPickTrigger;
  32841. },
  32842. enumerable: true,
  32843. configurable: true
  32844. });
  32845. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  32846. get: function () {
  32847. return ActionManager._OnLeftPickTrigger;
  32848. },
  32849. enumerable: true,
  32850. configurable: true
  32851. });
  32852. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  32853. get: function () {
  32854. return ActionManager._OnRightPickTrigger;
  32855. },
  32856. enumerable: true,
  32857. configurable: true
  32858. });
  32859. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  32860. get: function () {
  32861. return ActionManager._OnCenterPickTrigger;
  32862. },
  32863. enumerable: true,
  32864. configurable: true
  32865. });
  32866. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  32867. get: function () {
  32868. return ActionManager._OnPickDownTrigger;
  32869. },
  32870. enumerable: true,
  32871. configurable: true
  32872. });
  32873. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  32874. get: function () {
  32875. return ActionManager._OnDoublePickTrigger;
  32876. },
  32877. enumerable: true,
  32878. configurable: true
  32879. });
  32880. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  32881. get: function () {
  32882. return ActionManager._OnPickUpTrigger;
  32883. },
  32884. enumerable: true,
  32885. configurable: true
  32886. });
  32887. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  32888. /// This trigger will only be raised if you also declared a OnPickDown
  32889. get: function () {
  32890. return ActionManager._OnPickOutTrigger;
  32891. },
  32892. enumerable: true,
  32893. configurable: true
  32894. });
  32895. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  32896. get: function () {
  32897. return ActionManager._OnLongPressTrigger;
  32898. },
  32899. enumerable: true,
  32900. configurable: true
  32901. });
  32902. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  32903. get: function () {
  32904. return ActionManager._OnPointerOverTrigger;
  32905. },
  32906. enumerable: true,
  32907. configurable: true
  32908. });
  32909. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  32910. get: function () {
  32911. return ActionManager._OnPointerOutTrigger;
  32912. },
  32913. enumerable: true,
  32914. configurable: true
  32915. });
  32916. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  32917. get: function () {
  32918. return ActionManager._OnEveryFrameTrigger;
  32919. },
  32920. enumerable: true,
  32921. configurable: true
  32922. });
  32923. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  32924. get: function () {
  32925. return ActionManager._OnIntersectionEnterTrigger;
  32926. },
  32927. enumerable: true,
  32928. configurable: true
  32929. });
  32930. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  32931. get: function () {
  32932. return ActionManager._OnIntersectionExitTrigger;
  32933. },
  32934. enumerable: true,
  32935. configurable: true
  32936. });
  32937. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  32938. get: function () {
  32939. return ActionManager._OnKeyDownTrigger;
  32940. },
  32941. enumerable: true,
  32942. configurable: true
  32943. });
  32944. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  32945. get: function () {
  32946. return ActionManager._OnKeyUpTrigger;
  32947. },
  32948. enumerable: true,
  32949. configurable: true
  32950. });
  32951. // Methods
  32952. ActionManager.prototype.dispose = function () {
  32953. var index = this._scene._actionManagers.indexOf(this);
  32954. for (var i = 0; i < this.actions.length; i++) {
  32955. var action = this.actions[i];
  32956. ActionManager.Triggers[action.trigger]--;
  32957. if (ActionManager.Triggers[action.trigger] === 0) {
  32958. delete ActionManager.Triggers[action.trigger];
  32959. }
  32960. }
  32961. if (index > -1) {
  32962. this._scene._actionManagers.splice(index, 1);
  32963. }
  32964. };
  32965. ActionManager.prototype.getScene = function () {
  32966. return this._scene;
  32967. };
  32968. /**
  32969. * Does this action manager handles actions of any of the given triggers
  32970. * @param {number[]} triggers - the triggers to be tested
  32971. * @return {boolean} whether one (or more) of the triggers is handeled
  32972. */
  32973. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  32974. for (var index = 0; index < this.actions.length; index++) {
  32975. var action = this.actions[index];
  32976. if (triggers.indexOf(action.trigger) > -1) {
  32977. return true;
  32978. }
  32979. }
  32980. return false;
  32981. };
  32982. /**
  32983. * Does this action manager handles actions of a given trigger
  32984. * @param {number} trigger - the trigger to be tested
  32985. * @return {boolean} whether the trigger is handeled
  32986. */
  32987. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  32988. for (var index = 0; index < this.actions.length; index++) {
  32989. var action = this.actions[index];
  32990. if (action.trigger === trigger) {
  32991. return true;
  32992. }
  32993. }
  32994. return false;
  32995. };
  32996. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  32997. /**
  32998. * Does this action manager has pointer triggers
  32999. * @return {boolean} whether or not it has pointer triggers
  33000. */
  33001. get: function () {
  33002. for (var index = 0; index < this.actions.length; index++) {
  33003. var action = this.actions[index];
  33004. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  33005. return true;
  33006. }
  33007. }
  33008. return false;
  33009. },
  33010. enumerable: true,
  33011. configurable: true
  33012. });
  33013. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33014. /**
  33015. * Does this action manager has pick triggers
  33016. * @return {boolean} whether or not it has pick triggers
  33017. */
  33018. get: function () {
  33019. for (var index = 0; index < this.actions.length; index++) {
  33020. var action = this.actions[index];
  33021. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33022. return true;
  33023. }
  33024. }
  33025. return false;
  33026. },
  33027. enumerable: true,
  33028. configurable: true
  33029. });
  33030. Object.defineProperty(ActionManager, "HasTriggers", {
  33031. /**
  33032. * Does exist one action manager with at least one trigger
  33033. * @return {boolean} whether or not it exists one action manager with one trigger
  33034. **/
  33035. get: function () {
  33036. for (var t in ActionManager.Triggers) {
  33037. if (ActionManager.Triggers.hasOwnProperty(t)) {
  33038. return true;
  33039. }
  33040. }
  33041. return false;
  33042. },
  33043. enumerable: true,
  33044. configurable: true
  33045. });
  33046. Object.defineProperty(ActionManager, "HasPickTriggers", {
  33047. /**
  33048. * Does exist one action manager with at least one pick trigger
  33049. * @return {boolean} whether or not it exists one action manager with one pick trigger
  33050. **/
  33051. get: function () {
  33052. for (var t in ActionManager.Triggers) {
  33053. if (ActionManager.Triggers.hasOwnProperty(t)) {
  33054. var t_int = parseInt(t);
  33055. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  33056. return true;
  33057. }
  33058. }
  33059. }
  33060. return false;
  33061. },
  33062. enumerable: true,
  33063. configurable: true
  33064. });
  33065. /**
  33066. * Does exist one action manager that handles actions of a given trigger
  33067. * @param {number} trigger - the trigger to be tested
  33068. * @return {boolean} whether the trigger is handeled by at least one action manager
  33069. **/
  33070. ActionManager.HasSpecificTrigger = function (trigger) {
  33071. for (var t in ActionManager.Triggers) {
  33072. if (ActionManager.Triggers.hasOwnProperty(t)) {
  33073. var t_int = parseInt(t);
  33074. if (t_int === trigger) {
  33075. return true;
  33076. }
  33077. }
  33078. }
  33079. return false;
  33080. };
  33081. /**
  33082. * Registers an action to this action manager
  33083. * @param {BABYLON.Action} action - the action to be registered
  33084. * @return {BABYLON.Action} the action amended (prepared) after registration
  33085. */
  33086. ActionManager.prototype.registerAction = function (action) {
  33087. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33088. if (this.getScene().actionManager !== this) {
  33089. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33090. return null;
  33091. }
  33092. }
  33093. this.actions.push(action);
  33094. if (ActionManager.Triggers[action.trigger]) {
  33095. ActionManager.Triggers[action.trigger]++;
  33096. }
  33097. else {
  33098. ActionManager.Triggers[action.trigger] = 1;
  33099. }
  33100. action._actionManager = this;
  33101. action._prepare();
  33102. return action;
  33103. };
  33104. /**
  33105. * Process a specific trigger
  33106. * @param {number} trigger - the trigger to process
  33107. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33108. */
  33109. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33110. for (var index = 0; index < this.actions.length; index++) {
  33111. var action = this.actions[index];
  33112. if (action.trigger === trigger) {
  33113. if (trigger === ActionManager.OnKeyUpTrigger
  33114. || trigger === ActionManager.OnKeyDownTrigger) {
  33115. var parameter = action.getTriggerParameter();
  33116. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  33117. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33118. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33119. if (actualkey !== parameter.toLowerCase()) {
  33120. continue;
  33121. }
  33122. }
  33123. }
  33124. action._executeCurrent(evt);
  33125. }
  33126. }
  33127. };
  33128. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33129. var properties = propertyPath.split(".");
  33130. for (var index = 0; index < properties.length - 1; index++) {
  33131. target = target[properties[index]];
  33132. }
  33133. return target;
  33134. };
  33135. ActionManager.prototype._getProperty = function (propertyPath) {
  33136. var properties = propertyPath.split(".");
  33137. return properties[properties.length - 1];
  33138. };
  33139. ActionManager.prototype.serialize = function (name) {
  33140. var root = {
  33141. children: [],
  33142. name: name,
  33143. type: 3,
  33144. properties: [] // Empty for root but required
  33145. };
  33146. for (var i = 0; i < this.actions.length; i++) {
  33147. var triggerObject = {
  33148. type: 0,
  33149. children: [],
  33150. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  33151. properties: []
  33152. };
  33153. var triggerOptions = this.actions[i].triggerOptions;
  33154. if (triggerOptions && typeof triggerOptions !== "number") {
  33155. if (triggerOptions.parameter instanceof BABYLON.Node) {
  33156. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  33157. }
  33158. else {
  33159. var parameter = {};
  33160. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  33161. if (triggerOptions.parameter.mesh) {
  33162. parameter._meshId = triggerOptions.parameter.mesh.id;
  33163. }
  33164. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  33165. }
  33166. }
  33167. // Serialize child action, recursively
  33168. this.actions[i].serialize(triggerObject);
  33169. // Add serialized trigger
  33170. root.children.push(triggerObject);
  33171. }
  33172. return root;
  33173. };
  33174. ActionManager.Parse = function (parsedActions, object, scene) {
  33175. var actionManager = new BABYLON.ActionManager(scene);
  33176. if (object === null)
  33177. scene.actionManager = actionManager;
  33178. else
  33179. object.actionManager = actionManager;
  33180. // instanciate a new object
  33181. var instanciate = function (name, params) {
  33182. var newInstance = Object.create(BABYLON[name].prototype);
  33183. newInstance.constructor.apply(newInstance, params);
  33184. return newInstance;
  33185. };
  33186. var parseParameter = function (name, value, target, propertyPath) {
  33187. if (propertyPath === null) {
  33188. // String, boolean or float
  33189. var floatValue = parseFloat(value);
  33190. if (value === "true" || value === "false")
  33191. return value === "true";
  33192. else
  33193. return isNaN(floatValue) ? value : floatValue;
  33194. }
  33195. var effectiveTarget = propertyPath.split(".");
  33196. var values = value.split(",");
  33197. // Get effective Target
  33198. for (var i = 0; i < effectiveTarget.length; i++) {
  33199. target = target[effectiveTarget[i]];
  33200. }
  33201. // Return appropriate value with its type
  33202. if (typeof (target) === "boolean")
  33203. return values[0] === "true";
  33204. if (typeof (target) === "string")
  33205. return values[0];
  33206. // Parameters with multiple values such as Vector3 etc.
  33207. var split = new Array();
  33208. for (var i = 0; i < values.length; i++)
  33209. split.push(parseFloat(values[i]));
  33210. if (target instanceof BABYLON.Vector3)
  33211. return BABYLON.Vector3.FromArray(split);
  33212. if (target instanceof BABYLON.Vector4)
  33213. return BABYLON.Vector4.FromArray(split);
  33214. if (target instanceof BABYLON.Color3)
  33215. return BABYLON.Color3.FromArray(split);
  33216. if (target instanceof BABYLON.Color4)
  33217. return BABYLON.Color4.FromArray(split);
  33218. return parseFloat(values[0]);
  33219. };
  33220. // traverse graph per trigger
  33221. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  33222. if (combineArray === void 0) { combineArray = null; }
  33223. if (parsedAction.detached)
  33224. return;
  33225. var parameters = new Array();
  33226. var target = null;
  33227. var propertyPath = null;
  33228. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  33229. // Parameters
  33230. if (parsedAction.type === 2)
  33231. parameters.push(actionManager);
  33232. else
  33233. parameters.push(trigger);
  33234. if (combine) {
  33235. var actions = new Array();
  33236. for (var j = 0; j < parsedAction.combine.length; j++) {
  33237. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  33238. }
  33239. parameters.push(actions);
  33240. }
  33241. else {
  33242. for (var i = 0; i < parsedAction.properties.length; i++) {
  33243. var value = parsedAction.properties[i].value;
  33244. var name = parsedAction.properties[i].name;
  33245. var targetType = parsedAction.properties[i].targetType;
  33246. if (name === "target")
  33247. if (targetType !== null && targetType === "SceneProperties")
  33248. value = target = scene;
  33249. else
  33250. value = target = scene.getNodeByName(value);
  33251. else if (name === "parent")
  33252. value = scene.getNodeByName(value);
  33253. else if (name === "sound")
  33254. value = scene.getSoundByName(value);
  33255. else if (name !== "propertyPath") {
  33256. if (parsedAction.type === 2 && name === "operator")
  33257. value = BABYLON.ValueCondition[value];
  33258. else
  33259. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  33260. }
  33261. else {
  33262. propertyPath = value;
  33263. }
  33264. parameters.push(value);
  33265. }
  33266. }
  33267. if (combineArray === null) {
  33268. parameters.push(condition);
  33269. }
  33270. else {
  33271. parameters.push(null);
  33272. }
  33273. // If interpolate value action
  33274. if (parsedAction.name === "InterpolateValueAction") {
  33275. var param = parameters[parameters.length - 2];
  33276. parameters[parameters.length - 1] = param;
  33277. parameters[parameters.length - 2] = condition;
  33278. }
  33279. // Action or condition(s) and not CombineAction
  33280. var newAction = instanciate(parsedAction.name, parameters);
  33281. if (newAction instanceof BABYLON.Condition && condition !== null) {
  33282. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  33283. if (action)
  33284. action.then(nothing);
  33285. else
  33286. actionManager.registerAction(nothing);
  33287. action = nothing;
  33288. }
  33289. if (combineArray === null) {
  33290. if (newAction instanceof BABYLON.Condition) {
  33291. condition = newAction;
  33292. newAction = action;
  33293. }
  33294. else {
  33295. condition = null;
  33296. if (action)
  33297. action.then(newAction);
  33298. else
  33299. actionManager.registerAction(newAction);
  33300. }
  33301. }
  33302. else {
  33303. combineArray.push(newAction);
  33304. }
  33305. for (var i = 0; i < parsedAction.children.length; i++)
  33306. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  33307. };
  33308. // triggers
  33309. for (var i = 0; i < parsedActions.children.length; i++) {
  33310. var triggerParams;
  33311. var trigger = parsedActions.children[i];
  33312. if (trigger.properties.length > 0) {
  33313. var param = trigger.properties[0].value;
  33314. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  33315. if (value._meshId) {
  33316. value.mesh = scene.getMeshByID(value._meshId);
  33317. }
  33318. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  33319. }
  33320. else
  33321. triggerParams = BABYLON.ActionManager[trigger.name];
  33322. for (var j = 0; j < trigger.children.length; j++) {
  33323. if (!trigger.detached)
  33324. traverse(trigger.children[j], triggerParams, null, null);
  33325. }
  33326. }
  33327. };
  33328. ActionManager.GetTriggerName = function (trigger) {
  33329. switch (trigger) {
  33330. case 0: return "NothingTrigger";
  33331. case 1: return "OnPickTrigger";
  33332. case 2: return "OnLeftPickTrigger";
  33333. case 3: return "OnRightPickTrigger";
  33334. case 4: return "OnCenterPickTrigger";
  33335. case 5: return "OnPickDownTrigger";
  33336. case 6: return "OnPickUpTrigger";
  33337. case 7: return "OnLongPressTrigger";
  33338. case 8: return "OnPointerOverTrigger";
  33339. case 9: return "OnPointerOutTrigger";
  33340. case 10: return "OnEveryFrameTrigger";
  33341. case 11: return "OnIntersectionEnterTrigger";
  33342. case 12: return "OnIntersectionExitTrigger";
  33343. case 13: return "OnKeyDownTrigger";
  33344. case 14: return "OnKeyUpTrigger";
  33345. case 15: return "OnPickOutTrigger";
  33346. default: return "";
  33347. }
  33348. };
  33349. return ActionManager;
  33350. }());
  33351. // Statics
  33352. ActionManager._NothingTrigger = 0;
  33353. ActionManager._OnPickTrigger = 1;
  33354. ActionManager._OnLeftPickTrigger = 2;
  33355. ActionManager._OnRightPickTrigger = 3;
  33356. ActionManager._OnCenterPickTrigger = 4;
  33357. ActionManager._OnPickDownTrigger = 5;
  33358. ActionManager._OnDoublePickTrigger = 6;
  33359. ActionManager._OnPickUpTrigger = 7;
  33360. ActionManager._OnLongPressTrigger = 8;
  33361. ActionManager._OnPointerOverTrigger = 9;
  33362. ActionManager._OnPointerOutTrigger = 10;
  33363. ActionManager._OnEveryFrameTrigger = 11;
  33364. ActionManager._OnIntersectionEnterTrigger = 12;
  33365. ActionManager._OnIntersectionExitTrigger = 13;
  33366. ActionManager._OnKeyDownTrigger = 14;
  33367. ActionManager._OnKeyUpTrigger = 15;
  33368. ActionManager._OnPickOutTrigger = 16;
  33369. ActionManager.Triggers = {};
  33370. BABYLON.ActionManager = ActionManager;
  33371. })(BABYLON || (BABYLON = {}));
  33372. //# sourceMappingURL=babylon.actionManager.js.map
  33373. var BABYLON;
  33374. (function (BABYLON) {
  33375. var InterpolateValueAction = (function (_super) {
  33376. __extends(InterpolateValueAction, _super);
  33377. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  33378. if (duration === void 0) { duration = 1000; }
  33379. var _this = _super.call(this, triggerOptions, condition) || this;
  33380. _this.propertyPath = propertyPath;
  33381. _this.value = value;
  33382. _this.duration = duration;
  33383. _this.stopOtherAnimations = stopOtherAnimations;
  33384. _this.onInterpolationDone = onInterpolationDone;
  33385. _this._target = _this._effectiveTarget = target;
  33386. return _this;
  33387. }
  33388. InterpolateValueAction.prototype._prepare = function () {
  33389. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33390. this._property = this._getProperty(this.propertyPath);
  33391. };
  33392. InterpolateValueAction.prototype.execute = function () {
  33393. var scene = this._actionManager.getScene();
  33394. var keys = [
  33395. {
  33396. frame: 0,
  33397. value: this._effectiveTarget[this._property]
  33398. }, {
  33399. frame: 100,
  33400. value: this.value
  33401. }
  33402. ];
  33403. var dataType;
  33404. if (typeof this.value === "number") {
  33405. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  33406. }
  33407. else if (this.value instanceof BABYLON.Color3) {
  33408. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  33409. }
  33410. else if (this.value instanceof BABYLON.Vector3) {
  33411. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  33412. }
  33413. else if (this.value instanceof BABYLON.Matrix) {
  33414. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  33415. }
  33416. else if (this.value instanceof BABYLON.Quaternion) {
  33417. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  33418. }
  33419. else {
  33420. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  33421. return;
  33422. }
  33423. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  33424. animation.setKeys(keys);
  33425. if (this.stopOtherAnimations) {
  33426. scene.stopAnimation(this._effectiveTarget);
  33427. }
  33428. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  33429. };
  33430. InterpolateValueAction.prototype.serialize = function (parent) {
  33431. return _super.prototype._serialize.call(this, {
  33432. name: "InterpolateValueAction",
  33433. properties: [
  33434. BABYLON.Action._GetTargetProperty(this._target),
  33435. { name: "propertyPath", value: this.propertyPath },
  33436. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33437. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  33438. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  33439. ]
  33440. }, parent);
  33441. };
  33442. return InterpolateValueAction;
  33443. }(BABYLON.Action));
  33444. BABYLON.InterpolateValueAction = InterpolateValueAction;
  33445. })(BABYLON || (BABYLON = {}));
  33446. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  33447. var BABYLON;
  33448. (function (BABYLON) {
  33449. var SwitchBooleanAction = (function (_super) {
  33450. __extends(SwitchBooleanAction, _super);
  33451. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  33452. var _this = _super.call(this, triggerOptions, condition) || this;
  33453. _this.propertyPath = propertyPath;
  33454. _this._target = _this._effectiveTarget = target;
  33455. return _this;
  33456. }
  33457. SwitchBooleanAction.prototype._prepare = function () {
  33458. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33459. this._property = this._getProperty(this.propertyPath);
  33460. };
  33461. SwitchBooleanAction.prototype.execute = function () {
  33462. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  33463. };
  33464. SwitchBooleanAction.prototype.serialize = function (parent) {
  33465. return _super.prototype._serialize.call(this, {
  33466. name: "SwitchBooleanAction",
  33467. properties: [
  33468. BABYLON.Action._GetTargetProperty(this._target),
  33469. { name: "propertyPath", value: this.propertyPath }
  33470. ]
  33471. }, parent);
  33472. };
  33473. return SwitchBooleanAction;
  33474. }(BABYLON.Action));
  33475. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  33476. var SetStateAction = (function (_super) {
  33477. __extends(SetStateAction, _super);
  33478. function SetStateAction(triggerOptions, target, value, condition) {
  33479. var _this = _super.call(this, triggerOptions, condition) || this;
  33480. _this.value = value;
  33481. _this._target = target;
  33482. return _this;
  33483. }
  33484. SetStateAction.prototype.execute = function () {
  33485. this._target.state = this.value;
  33486. };
  33487. SetStateAction.prototype.serialize = function (parent) {
  33488. return _super.prototype._serialize.call(this, {
  33489. name: "SetStateAction",
  33490. properties: [
  33491. BABYLON.Action._GetTargetProperty(this._target),
  33492. { name: "value", value: this.value }
  33493. ]
  33494. }, parent);
  33495. };
  33496. return SetStateAction;
  33497. }(BABYLON.Action));
  33498. BABYLON.SetStateAction = SetStateAction;
  33499. var SetValueAction = (function (_super) {
  33500. __extends(SetValueAction, _super);
  33501. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  33502. var _this = _super.call(this, triggerOptions, condition) || this;
  33503. _this.propertyPath = propertyPath;
  33504. _this.value = value;
  33505. _this._target = _this._effectiveTarget = target;
  33506. return _this;
  33507. }
  33508. SetValueAction.prototype._prepare = function () {
  33509. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33510. this._property = this._getProperty(this.propertyPath);
  33511. };
  33512. SetValueAction.prototype.execute = function () {
  33513. this._effectiveTarget[this._property] = this.value;
  33514. if (this._target.markAsDirty) {
  33515. this._target.markAsDirty(this._property);
  33516. }
  33517. };
  33518. SetValueAction.prototype.serialize = function (parent) {
  33519. return _super.prototype._serialize.call(this, {
  33520. name: "SetValueAction",
  33521. properties: [
  33522. BABYLON.Action._GetTargetProperty(this._target),
  33523. { name: "propertyPath", value: this.propertyPath },
  33524. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33525. ]
  33526. }, parent);
  33527. };
  33528. return SetValueAction;
  33529. }(BABYLON.Action));
  33530. BABYLON.SetValueAction = SetValueAction;
  33531. var IncrementValueAction = (function (_super) {
  33532. __extends(IncrementValueAction, _super);
  33533. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  33534. var _this = _super.call(this, triggerOptions, condition) || this;
  33535. _this.propertyPath = propertyPath;
  33536. _this.value = value;
  33537. _this._target = _this._effectiveTarget = target;
  33538. return _this;
  33539. }
  33540. IncrementValueAction.prototype._prepare = function () {
  33541. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33542. this._property = this._getProperty(this.propertyPath);
  33543. if (typeof this._effectiveTarget[this._property] !== "number") {
  33544. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  33545. }
  33546. };
  33547. IncrementValueAction.prototype.execute = function () {
  33548. this._effectiveTarget[this._property] += this.value;
  33549. if (this._target.markAsDirty) {
  33550. this._target.markAsDirty(this._property);
  33551. }
  33552. };
  33553. IncrementValueAction.prototype.serialize = function (parent) {
  33554. return _super.prototype._serialize.call(this, {
  33555. name: "IncrementValueAction",
  33556. properties: [
  33557. BABYLON.Action._GetTargetProperty(this._target),
  33558. { name: "propertyPath", value: this.propertyPath },
  33559. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33560. ]
  33561. }, parent);
  33562. };
  33563. return IncrementValueAction;
  33564. }(BABYLON.Action));
  33565. BABYLON.IncrementValueAction = IncrementValueAction;
  33566. var PlayAnimationAction = (function (_super) {
  33567. __extends(PlayAnimationAction, _super);
  33568. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  33569. var _this = _super.call(this, triggerOptions, condition) || this;
  33570. _this.from = from;
  33571. _this.to = to;
  33572. _this.loop = loop;
  33573. _this._target = target;
  33574. return _this;
  33575. }
  33576. PlayAnimationAction.prototype._prepare = function () {
  33577. };
  33578. PlayAnimationAction.prototype.execute = function () {
  33579. var scene = this._actionManager.getScene();
  33580. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  33581. };
  33582. PlayAnimationAction.prototype.serialize = function (parent) {
  33583. return _super.prototype._serialize.call(this, {
  33584. name: "PlayAnimationAction",
  33585. properties: [
  33586. BABYLON.Action._GetTargetProperty(this._target),
  33587. { name: "from", value: String(this.from) },
  33588. { name: "to", value: String(this.to) },
  33589. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  33590. ]
  33591. }, parent);
  33592. };
  33593. return PlayAnimationAction;
  33594. }(BABYLON.Action));
  33595. BABYLON.PlayAnimationAction = PlayAnimationAction;
  33596. var StopAnimationAction = (function (_super) {
  33597. __extends(StopAnimationAction, _super);
  33598. function StopAnimationAction(triggerOptions, target, condition) {
  33599. var _this = _super.call(this, triggerOptions, condition) || this;
  33600. _this._target = target;
  33601. return _this;
  33602. }
  33603. StopAnimationAction.prototype._prepare = function () {
  33604. };
  33605. StopAnimationAction.prototype.execute = function () {
  33606. var scene = this._actionManager.getScene();
  33607. scene.stopAnimation(this._target);
  33608. };
  33609. StopAnimationAction.prototype.serialize = function (parent) {
  33610. return _super.prototype._serialize.call(this, {
  33611. name: "StopAnimationAction",
  33612. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  33613. }, parent);
  33614. };
  33615. return StopAnimationAction;
  33616. }(BABYLON.Action));
  33617. BABYLON.StopAnimationAction = StopAnimationAction;
  33618. var DoNothingAction = (function (_super) {
  33619. __extends(DoNothingAction, _super);
  33620. function DoNothingAction(triggerOptions, condition) {
  33621. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  33622. return _super.call(this, triggerOptions, condition) || this;
  33623. }
  33624. DoNothingAction.prototype.execute = function () {
  33625. };
  33626. DoNothingAction.prototype.serialize = function (parent) {
  33627. return _super.prototype._serialize.call(this, {
  33628. name: "DoNothingAction",
  33629. properties: []
  33630. }, parent);
  33631. };
  33632. return DoNothingAction;
  33633. }(BABYLON.Action));
  33634. BABYLON.DoNothingAction = DoNothingAction;
  33635. var CombineAction = (function (_super) {
  33636. __extends(CombineAction, _super);
  33637. function CombineAction(triggerOptions, children, condition) {
  33638. var _this = _super.call(this, triggerOptions, condition) || this;
  33639. _this.children = children;
  33640. return _this;
  33641. }
  33642. CombineAction.prototype._prepare = function () {
  33643. for (var index = 0; index < this.children.length; index++) {
  33644. this.children[index]._actionManager = this._actionManager;
  33645. this.children[index]._prepare();
  33646. }
  33647. };
  33648. CombineAction.prototype.execute = function (evt) {
  33649. for (var index = 0; index < this.children.length; index++) {
  33650. this.children[index].execute(evt);
  33651. }
  33652. };
  33653. CombineAction.prototype.serialize = function (parent) {
  33654. var serializationObject = _super.prototype._serialize.call(this, {
  33655. name: "CombineAction",
  33656. properties: [],
  33657. combine: []
  33658. }, parent);
  33659. for (var i = 0; i < this.children.length; i++) {
  33660. serializationObject.combine.push(this.children[i].serialize(null));
  33661. }
  33662. return serializationObject;
  33663. };
  33664. return CombineAction;
  33665. }(BABYLON.Action));
  33666. BABYLON.CombineAction = CombineAction;
  33667. var ExecuteCodeAction = (function (_super) {
  33668. __extends(ExecuteCodeAction, _super);
  33669. function ExecuteCodeAction(triggerOptions, func, condition) {
  33670. var _this = _super.call(this, triggerOptions, condition) || this;
  33671. _this.func = func;
  33672. return _this;
  33673. }
  33674. ExecuteCodeAction.prototype.execute = function (evt) {
  33675. this.func(evt);
  33676. };
  33677. return ExecuteCodeAction;
  33678. }(BABYLON.Action));
  33679. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  33680. var SetParentAction = (function (_super) {
  33681. __extends(SetParentAction, _super);
  33682. function SetParentAction(triggerOptions, target, parent, condition) {
  33683. var _this = _super.call(this, triggerOptions, condition) || this;
  33684. _this._target = target;
  33685. _this._parent = parent;
  33686. return _this;
  33687. }
  33688. SetParentAction.prototype._prepare = function () {
  33689. };
  33690. SetParentAction.prototype.execute = function () {
  33691. if (this._target.parent === this._parent) {
  33692. return;
  33693. }
  33694. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  33695. invertParentWorldMatrix.invert();
  33696. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  33697. this._target.parent = this._parent;
  33698. };
  33699. SetParentAction.prototype.serialize = function (parent) {
  33700. return _super.prototype._serialize.call(this, {
  33701. name: "SetParentAction",
  33702. properties: [
  33703. BABYLON.Action._GetTargetProperty(this._target),
  33704. BABYLON.Action._GetTargetProperty(this._parent),
  33705. ]
  33706. }, parent);
  33707. };
  33708. return SetParentAction;
  33709. }(BABYLON.Action));
  33710. BABYLON.SetParentAction = SetParentAction;
  33711. var PlaySoundAction = (function (_super) {
  33712. __extends(PlaySoundAction, _super);
  33713. function PlaySoundAction(triggerOptions, sound, condition) {
  33714. var _this = _super.call(this, triggerOptions, condition) || this;
  33715. _this._sound = sound;
  33716. return _this;
  33717. }
  33718. PlaySoundAction.prototype._prepare = function () {
  33719. };
  33720. PlaySoundAction.prototype.execute = function () {
  33721. if (this._sound !== undefined)
  33722. this._sound.play();
  33723. };
  33724. PlaySoundAction.prototype.serialize = function (parent) {
  33725. return _super.prototype._serialize.call(this, {
  33726. name: "PlaySoundAction",
  33727. properties: [{ name: "sound", value: this._sound.name }]
  33728. }, parent);
  33729. };
  33730. return PlaySoundAction;
  33731. }(BABYLON.Action));
  33732. BABYLON.PlaySoundAction = PlaySoundAction;
  33733. var StopSoundAction = (function (_super) {
  33734. __extends(StopSoundAction, _super);
  33735. function StopSoundAction(triggerOptions, sound, condition) {
  33736. var _this = _super.call(this, triggerOptions, condition) || this;
  33737. _this._sound = sound;
  33738. return _this;
  33739. }
  33740. StopSoundAction.prototype._prepare = function () {
  33741. };
  33742. StopSoundAction.prototype.execute = function () {
  33743. if (this._sound !== undefined)
  33744. this._sound.stop();
  33745. };
  33746. StopSoundAction.prototype.serialize = function (parent) {
  33747. return _super.prototype._serialize.call(this, {
  33748. name: "StopSoundAction",
  33749. properties: [{ name: "sound", value: this._sound.name }]
  33750. }, parent);
  33751. };
  33752. return StopSoundAction;
  33753. }(BABYLON.Action));
  33754. BABYLON.StopSoundAction = StopSoundAction;
  33755. })(BABYLON || (BABYLON = {}));
  33756. //# sourceMappingURL=babylon.directActions.js.map
  33757. var BABYLON;
  33758. (function (BABYLON) {
  33759. var SpriteManager = (function () {
  33760. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  33761. if (epsilon === void 0) { epsilon = 0.01; }
  33762. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33763. this.name = name;
  33764. this.sprites = new Array();
  33765. this.renderingGroupId = 0;
  33766. this.layerMask = 0x0FFFFFFF;
  33767. this.fogEnabled = true;
  33768. this.isPickable = false;
  33769. /**
  33770. * An event triggered when the manager is disposed.
  33771. * @type {BABYLON.Observable}
  33772. */
  33773. this.onDisposeObservable = new BABYLON.Observable();
  33774. this._vertexBuffers = {};
  33775. this._capacity = capacity;
  33776. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  33777. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33778. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33779. if (cellSize.width && cellSize.height) {
  33780. this.cellWidth = cellSize.width;
  33781. this.cellHeight = cellSize.height;
  33782. }
  33783. else if (cellSize !== undefined) {
  33784. this.cellWidth = cellSize;
  33785. this.cellHeight = cellSize;
  33786. }
  33787. else {
  33788. return;
  33789. }
  33790. this._epsilon = epsilon;
  33791. this._scene = scene;
  33792. this._scene.spriteManagers.push(this);
  33793. var indices = [];
  33794. var index = 0;
  33795. for (var count = 0; count < capacity; count++) {
  33796. indices.push(index);
  33797. indices.push(index + 1);
  33798. indices.push(index + 2);
  33799. indices.push(index);
  33800. indices.push(index + 2);
  33801. indices.push(index + 3);
  33802. index += 4;
  33803. }
  33804. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33805. // VBO
  33806. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  33807. this._vertexData = new Float32Array(capacity * 16 * 4);
  33808. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  33809. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  33810. var options = this._buffer.createVertexBuffer("options", 4, 4);
  33811. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  33812. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  33813. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  33814. this._vertexBuffers["options"] = options;
  33815. this._vertexBuffers["cellInfo"] = cellInfo;
  33816. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  33817. // Effects
  33818. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  33819. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  33820. }
  33821. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  33822. set: function (callback) {
  33823. if (this._onDisposeObserver) {
  33824. this.onDisposeObservable.remove(this._onDisposeObserver);
  33825. }
  33826. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  33827. },
  33828. enumerable: true,
  33829. configurable: true
  33830. });
  33831. Object.defineProperty(SpriteManager.prototype, "texture", {
  33832. get: function () {
  33833. return this._spriteTexture;
  33834. },
  33835. set: function (value) {
  33836. this._spriteTexture = value;
  33837. },
  33838. enumerable: true,
  33839. configurable: true
  33840. });
  33841. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  33842. var arrayOffset = index * 16;
  33843. if (offsetX === 0)
  33844. offsetX = this._epsilon;
  33845. else if (offsetX === 1)
  33846. offsetX = 1 - this._epsilon;
  33847. if (offsetY === 0)
  33848. offsetY = this._epsilon;
  33849. else if (offsetY === 1)
  33850. offsetY = 1 - this._epsilon;
  33851. this._vertexData[arrayOffset] = sprite.position.x;
  33852. this._vertexData[arrayOffset + 1] = sprite.position.y;
  33853. this._vertexData[arrayOffset + 2] = sprite.position.z;
  33854. this._vertexData[arrayOffset + 3] = sprite.angle;
  33855. this._vertexData[arrayOffset + 4] = sprite.width;
  33856. this._vertexData[arrayOffset + 5] = sprite.height;
  33857. this._vertexData[arrayOffset + 6] = offsetX;
  33858. this._vertexData[arrayOffset + 7] = offsetY;
  33859. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  33860. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  33861. var offset = (sprite.cellIndex / rowSize) >> 0;
  33862. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  33863. this._vertexData[arrayOffset + 11] = offset;
  33864. // Color
  33865. this._vertexData[arrayOffset + 12] = sprite.color.r;
  33866. this._vertexData[arrayOffset + 13] = sprite.color.g;
  33867. this._vertexData[arrayOffset + 14] = sprite.color.b;
  33868. this._vertexData[arrayOffset + 15] = sprite.color.a;
  33869. };
  33870. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  33871. var count = Math.min(this._capacity, this.sprites.length);
  33872. var min = BABYLON.Vector3.Zero();
  33873. var max = BABYLON.Vector3.Zero();
  33874. var distance = Number.MAX_VALUE;
  33875. var currentSprite;
  33876. var cameraSpacePosition = BABYLON.Vector3.Zero();
  33877. var cameraView = camera.getViewMatrix();
  33878. for (var index = 0; index < count; index++) {
  33879. var sprite = this.sprites[index];
  33880. if (!sprite) {
  33881. continue;
  33882. }
  33883. if (predicate) {
  33884. if (!predicate(sprite)) {
  33885. continue;
  33886. }
  33887. }
  33888. else if (!sprite.isPickable) {
  33889. continue;
  33890. }
  33891. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  33892. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  33893. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  33894. if (ray.intersectsBoxMinMax(min, max)) {
  33895. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  33896. if (distance > currentDistance) {
  33897. distance = currentDistance;
  33898. currentSprite = sprite;
  33899. if (fastCheck) {
  33900. break;
  33901. }
  33902. }
  33903. }
  33904. }
  33905. if (currentSprite) {
  33906. var result = new BABYLON.PickingInfo();
  33907. result.hit = true;
  33908. result.pickedSprite = currentSprite;
  33909. result.distance = distance;
  33910. return result;
  33911. }
  33912. return null;
  33913. };
  33914. SpriteManager.prototype.render = function () {
  33915. // Check
  33916. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  33917. return;
  33918. var engine = this._scene.getEngine();
  33919. var baseSize = this._spriteTexture.getBaseSize();
  33920. // Sprites
  33921. var deltaTime = engine.getDeltaTime();
  33922. var max = Math.min(this._capacity, this.sprites.length);
  33923. var rowSize = baseSize.width / this.cellWidth;
  33924. var offset = 0;
  33925. for (var index = 0; index < max; index++) {
  33926. var sprite = this.sprites[index];
  33927. if (!sprite) {
  33928. continue;
  33929. }
  33930. sprite._animate(deltaTime);
  33931. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  33932. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  33933. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  33934. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  33935. }
  33936. this._buffer.update(this._vertexData);
  33937. // Render
  33938. var effect = this._effectBase;
  33939. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  33940. effect = this._effectFog;
  33941. }
  33942. engine.enableEffect(effect);
  33943. var viewMatrix = this._scene.getViewMatrix();
  33944. effect.setTexture("diffuseSampler", this._spriteTexture);
  33945. effect.setMatrix("view", viewMatrix);
  33946. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  33947. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  33948. // Fog
  33949. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  33950. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  33951. effect.setColor3("vFogColor", this._scene.fogColor);
  33952. }
  33953. // VBOs
  33954. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33955. // Draw order
  33956. engine.setDepthFunctionToLessOrEqual();
  33957. effect.setBool("alphaTest", true);
  33958. engine.setColorWrite(false);
  33959. engine.draw(true, 0, max * 6);
  33960. engine.setColorWrite(true);
  33961. effect.setBool("alphaTest", false);
  33962. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  33963. engine.draw(true, 0, max * 6);
  33964. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33965. };
  33966. SpriteManager.prototype.dispose = function () {
  33967. if (this._buffer) {
  33968. this._buffer.dispose();
  33969. this._buffer = null;
  33970. }
  33971. if (this._indexBuffer) {
  33972. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33973. this._indexBuffer = null;
  33974. }
  33975. if (this._spriteTexture) {
  33976. this._spriteTexture.dispose();
  33977. this._spriteTexture = null;
  33978. }
  33979. // Remove from scene
  33980. var index = this._scene.spriteManagers.indexOf(this);
  33981. this._scene.spriteManagers.splice(index, 1);
  33982. // Callback
  33983. this.onDisposeObservable.notifyObservers(this);
  33984. this.onDisposeObservable.clear();
  33985. };
  33986. return SpriteManager;
  33987. }());
  33988. BABYLON.SpriteManager = SpriteManager;
  33989. })(BABYLON || (BABYLON = {}));
  33990. //# sourceMappingURL=babylon.spriteManager.js.map
  33991. var BABYLON;
  33992. (function (BABYLON) {
  33993. var Sprite = (function () {
  33994. function Sprite(name, manager) {
  33995. this.name = name;
  33996. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  33997. this.width = 1.0;
  33998. this.height = 1.0;
  33999. this.angle = 0;
  34000. this.cellIndex = 0;
  34001. this.invertU = 0;
  34002. this.invertV = 0;
  34003. this.animations = new Array();
  34004. this.isPickable = false;
  34005. this._animationStarted = false;
  34006. this._loopAnimation = false;
  34007. this._fromIndex = 0;
  34008. this._toIndex = 0;
  34009. this._delay = 0;
  34010. this._direction = 1;
  34011. this._frameCount = 0;
  34012. this._time = 0;
  34013. this._manager = manager;
  34014. this._manager.sprites.push(this);
  34015. this.position = BABYLON.Vector3.Zero();
  34016. }
  34017. Object.defineProperty(Sprite.prototype, "size", {
  34018. get: function () {
  34019. return this.width;
  34020. },
  34021. set: function (value) {
  34022. this.width = value;
  34023. this.height = value;
  34024. },
  34025. enumerable: true,
  34026. configurable: true
  34027. });
  34028. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  34029. this._fromIndex = from;
  34030. this._toIndex = to;
  34031. this._loopAnimation = loop;
  34032. this._delay = delay;
  34033. this._animationStarted = true;
  34034. this._direction = from < to ? 1 : -1;
  34035. this.cellIndex = from;
  34036. this._time = 0;
  34037. this._onAnimationEnd = onAnimationEnd;
  34038. };
  34039. Sprite.prototype.stopAnimation = function () {
  34040. this._animationStarted = false;
  34041. };
  34042. Sprite.prototype._animate = function (deltaTime) {
  34043. if (!this._animationStarted)
  34044. return;
  34045. this._time += deltaTime;
  34046. if (this._time > this._delay) {
  34047. this._time = this._time % this._delay;
  34048. this.cellIndex += this._direction;
  34049. if (this.cellIndex === this._toIndex) {
  34050. if (this._loopAnimation) {
  34051. this.cellIndex = this._fromIndex;
  34052. }
  34053. else {
  34054. this._animationStarted = false;
  34055. if (this._onAnimationEnd) {
  34056. this._onAnimationEnd();
  34057. }
  34058. if (this.disposeWhenFinishedAnimating) {
  34059. this.dispose();
  34060. }
  34061. }
  34062. }
  34063. }
  34064. };
  34065. Sprite.prototype.dispose = function () {
  34066. for (var i = 0; i < this._manager.sprites.length; i++) {
  34067. if (this._manager.sprites[i] == this) {
  34068. this._manager.sprites.splice(i, 1);
  34069. }
  34070. }
  34071. };
  34072. return Sprite;
  34073. }());
  34074. BABYLON.Sprite = Sprite;
  34075. })(BABYLON || (BABYLON = {}));
  34076. //# sourceMappingURL=babylon.sprite.js.map
  34077. var BABYLON;
  34078. (function (BABYLON) {
  34079. var IntersectionInfo = (function () {
  34080. function IntersectionInfo(bu, bv, distance) {
  34081. this.bu = bu;
  34082. this.bv = bv;
  34083. this.distance = distance;
  34084. this.faceId = 0;
  34085. this.subMeshId = 0;
  34086. }
  34087. return IntersectionInfo;
  34088. }());
  34089. BABYLON.IntersectionInfo = IntersectionInfo;
  34090. var PickingInfo = (function () {
  34091. function PickingInfo() {
  34092. this.hit = false;
  34093. this.distance = 0;
  34094. this.pickedPoint = null;
  34095. this.pickedMesh = null;
  34096. this.bu = 0;
  34097. this.bv = 0;
  34098. this.faceId = -1;
  34099. this.subMeshId = 0;
  34100. this.pickedSprite = null;
  34101. }
  34102. // Methods
  34103. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  34104. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  34105. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  34106. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34107. return null;
  34108. }
  34109. var indices = this.pickedMesh.getIndices();
  34110. var result;
  34111. if (useVerticesNormals) {
  34112. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34113. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  34114. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  34115. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  34116. normal0 = normal0.scale(this.bu);
  34117. normal1 = normal1.scale(this.bv);
  34118. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  34119. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  34120. }
  34121. else {
  34122. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34123. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  34124. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  34125. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  34126. var p1p2 = vertex1.subtract(vertex2);
  34127. var p3p2 = vertex3.subtract(vertex2);
  34128. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  34129. }
  34130. if (useWorldCoordinates) {
  34131. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  34132. }
  34133. return BABYLON.Vector3.Normalize(result);
  34134. };
  34135. PickingInfo.prototype.getTextureCoordinates = function () {
  34136. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34137. return null;
  34138. }
  34139. var indices = this.pickedMesh.getIndices();
  34140. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34141. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  34142. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  34143. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  34144. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  34145. uv1 = uv1.scale(this.bu);
  34146. uv2 = uv2.scale(this.bv);
  34147. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  34148. };
  34149. return PickingInfo;
  34150. }());
  34151. BABYLON.PickingInfo = PickingInfo;
  34152. })(BABYLON || (BABYLON = {}));
  34153. //# sourceMappingURL=babylon.pickingInfo.js.map
  34154. var BABYLON;
  34155. (function (BABYLON) {
  34156. var Ray = (function () {
  34157. function Ray(origin, direction, length) {
  34158. if (length === void 0) { length = Number.MAX_VALUE; }
  34159. this.origin = origin;
  34160. this.direction = direction;
  34161. this.length = length;
  34162. }
  34163. // Methods
  34164. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  34165. var d = 0.0;
  34166. var maxValue = Number.MAX_VALUE;
  34167. var inv;
  34168. var min;
  34169. var max;
  34170. var temp;
  34171. if (Math.abs(this.direction.x) < 0.0000001) {
  34172. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  34173. return false;
  34174. }
  34175. }
  34176. else {
  34177. inv = 1.0 / this.direction.x;
  34178. min = (minimum.x - this.origin.x) * inv;
  34179. max = (maximum.x - this.origin.x) * inv;
  34180. if (max === -Infinity) {
  34181. max = Infinity;
  34182. }
  34183. if (min > max) {
  34184. temp = min;
  34185. min = max;
  34186. max = temp;
  34187. }
  34188. d = Math.max(min, d);
  34189. maxValue = Math.min(max, maxValue);
  34190. if (d > maxValue) {
  34191. return false;
  34192. }
  34193. }
  34194. if (Math.abs(this.direction.y) < 0.0000001) {
  34195. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  34196. return false;
  34197. }
  34198. }
  34199. else {
  34200. inv = 1.0 / this.direction.y;
  34201. min = (minimum.y - this.origin.y) * inv;
  34202. max = (maximum.y - this.origin.y) * inv;
  34203. if (max === -Infinity) {
  34204. max = Infinity;
  34205. }
  34206. if (min > max) {
  34207. temp = min;
  34208. min = max;
  34209. max = temp;
  34210. }
  34211. d = Math.max(min, d);
  34212. maxValue = Math.min(max, maxValue);
  34213. if (d > maxValue) {
  34214. return false;
  34215. }
  34216. }
  34217. if (Math.abs(this.direction.z) < 0.0000001) {
  34218. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  34219. return false;
  34220. }
  34221. }
  34222. else {
  34223. inv = 1.0 / this.direction.z;
  34224. min = (minimum.z - this.origin.z) * inv;
  34225. max = (maximum.z - this.origin.z) * inv;
  34226. if (max === -Infinity) {
  34227. max = Infinity;
  34228. }
  34229. if (min > max) {
  34230. temp = min;
  34231. min = max;
  34232. max = temp;
  34233. }
  34234. d = Math.max(min, d);
  34235. maxValue = Math.min(max, maxValue);
  34236. if (d > maxValue) {
  34237. return false;
  34238. }
  34239. }
  34240. return true;
  34241. };
  34242. Ray.prototype.intersectsBox = function (box) {
  34243. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  34244. };
  34245. Ray.prototype.intersectsSphere = function (sphere) {
  34246. var x = sphere.center.x - this.origin.x;
  34247. var y = sphere.center.y - this.origin.y;
  34248. var z = sphere.center.z - this.origin.z;
  34249. var pyth = (x * x) + (y * y) + (z * z);
  34250. var rr = sphere.radius * sphere.radius;
  34251. if (pyth <= rr) {
  34252. return true;
  34253. }
  34254. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  34255. if (dot < 0.0) {
  34256. return false;
  34257. }
  34258. var temp = pyth - (dot * dot);
  34259. return temp <= rr;
  34260. };
  34261. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  34262. if (!this._edge1) {
  34263. this._edge1 = BABYLON.Vector3.Zero();
  34264. this._edge2 = BABYLON.Vector3.Zero();
  34265. this._pvec = BABYLON.Vector3.Zero();
  34266. this._tvec = BABYLON.Vector3.Zero();
  34267. this._qvec = BABYLON.Vector3.Zero();
  34268. }
  34269. vertex1.subtractToRef(vertex0, this._edge1);
  34270. vertex2.subtractToRef(vertex0, this._edge2);
  34271. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  34272. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  34273. if (det === 0) {
  34274. return null;
  34275. }
  34276. var invdet = 1 / det;
  34277. this.origin.subtractToRef(vertex0, this._tvec);
  34278. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  34279. if (bu < 0 || bu > 1.0) {
  34280. return null;
  34281. }
  34282. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  34283. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  34284. if (bv < 0 || bu + bv > 1.0) {
  34285. return null;
  34286. }
  34287. //check if the distance is longer than the predefined length.
  34288. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  34289. if (distance > this.length) {
  34290. return null;
  34291. }
  34292. return new BABYLON.IntersectionInfo(bu, bv, distance);
  34293. };
  34294. Ray.prototype.intersectsPlane = function (plane) {
  34295. var distance;
  34296. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  34297. if (Math.abs(result1) < 9.99999997475243E-07) {
  34298. return null;
  34299. }
  34300. else {
  34301. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  34302. distance = (-plane.d - result2) / result1;
  34303. if (distance < 0.0) {
  34304. if (distance < -9.99999997475243E-07) {
  34305. return null;
  34306. }
  34307. else {
  34308. return 0;
  34309. }
  34310. }
  34311. return distance;
  34312. }
  34313. };
  34314. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  34315. var tm = BABYLON.Tmp.Matrix[0];
  34316. mesh.getWorldMatrix().invertToRef(tm);
  34317. if (this._tmpRay) {
  34318. Ray.TransformToRef(this, tm, this._tmpRay);
  34319. }
  34320. else {
  34321. this._tmpRay = Ray.Transform(this, tm);
  34322. }
  34323. return mesh.intersects(this._tmpRay, fastCheck);
  34324. };
  34325. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  34326. if (results) {
  34327. results.length = 0;
  34328. }
  34329. else {
  34330. results = [];
  34331. }
  34332. for (var i = 0; i < meshes.length; i++) {
  34333. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  34334. if (pickInfo.hit) {
  34335. results.push(pickInfo);
  34336. }
  34337. }
  34338. results.sort(this._comparePickingInfo);
  34339. return results;
  34340. };
  34341. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  34342. if (pickingInfoA.distance < pickingInfoB.distance) {
  34343. return -1;
  34344. }
  34345. else if (pickingInfoA.distance > pickingInfoB.distance) {
  34346. return 1;
  34347. }
  34348. else {
  34349. return 0;
  34350. }
  34351. };
  34352. /**
  34353. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  34354. * @param sega the first point of the segment to test the intersection against
  34355. * @param segb the second point of the segment to test the intersection against
  34356. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  34357. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  34358. */
  34359. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  34360. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  34361. var u = segb.subtract(sega);
  34362. var v = rsegb.subtract(this.origin);
  34363. var w = sega.subtract(this.origin);
  34364. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  34365. var b = BABYLON.Vector3.Dot(u, v);
  34366. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  34367. var d = BABYLON.Vector3.Dot(u, w);
  34368. var e = BABYLON.Vector3.Dot(v, w);
  34369. var D = a * c - b * b; // always >= 0
  34370. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  34371. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  34372. // compute the line parameters of the two closest points
  34373. if (D < Ray.smallnum) {
  34374. sN = 0.0; // force using point P0 on segment S1
  34375. sD = 1.0; // to prevent possible division by 0.0 later
  34376. tN = e;
  34377. tD = c;
  34378. }
  34379. else {
  34380. sN = (b * e - c * d);
  34381. tN = (a * e - b * d);
  34382. if (sN < 0.0) {
  34383. sN = 0.0;
  34384. tN = e;
  34385. tD = c;
  34386. }
  34387. else if (sN > sD) {
  34388. sN = sD;
  34389. tN = e + b;
  34390. tD = c;
  34391. }
  34392. }
  34393. if (tN < 0.0) {
  34394. tN = 0.0;
  34395. // recompute sc for this edge
  34396. if (-d < 0.0) {
  34397. sN = 0.0;
  34398. }
  34399. else if (-d > a)
  34400. sN = sD;
  34401. else {
  34402. sN = -d;
  34403. sD = a;
  34404. }
  34405. }
  34406. else if (tN > tD) {
  34407. tN = tD;
  34408. // recompute sc for this edge
  34409. if ((-d + b) < 0.0) {
  34410. sN = 0;
  34411. }
  34412. else if ((-d + b) > a) {
  34413. sN = sD;
  34414. }
  34415. else {
  34416. sN = (-d + b);
  34417. sD = a;
  34418. }
  34419. }
  34420. // finally do the division to get sc and tc
  34421. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  34422. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  34423. // get the difference of the two closest points
  34424. var qtc = v.multiplyByFloats(tc, tc, tc);
  34425. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  34426. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  34427. if (isIntersected) {
  34428. return qtc.length();
  34429. }
  34430. return -1;
  34431. };
  34432. // Statics
  34433. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  34434. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  34435. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  34436. var direction = end.subtract(start);
  34437. direction.normalize();
  34438. return new Ray(start, direction);
  34439. };
  34440. /**
  34441. * 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
  34442. * transformed to the given world matrix.
  34443. * @param origin The origin point
  34444. * @param end The end point
  34445. * @param world a matrix to transform the ray to. Default is the identity matrix.
  34446. */
  34447. Ray.CreateNewFromTo = function (origin, end, world) {
  34448. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  34449. var direction = end.subtract(origin);
  34450. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  34451. direction.normalize();
  34452. return Ray.Transform(new Ray(origin, direction, length), world);
  34453. };
  34454. Ray.Transform = function (ray, matrix) {
  34455. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  34456. Ray.TransformToRef(ray, matrix, result);
  34457. return result;
  34458. };
  34459. Ray.TransformToRef = function (ray, matrix, result) {
  34460. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  34461. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  34462. result.length = ray.length;
  34463. var dir = result.direction;
  34464. var len = dir.length();
  34465. if (!(len === 0 || len === 1)) {
  34466. var num = 1.0 / len;
  34467. dir.x *= num;
  34468. dir.y *= num;
  34469. dir.z *= num;
  34470. result.length *= len;
  34471. }
  34472. };
  34473. return Ray;
  34474. }());
  34475. Ray.smallnum = 0.00000001;
  34476. Ray.rayl = 10e8;
  34477. BABYLON.Ray = Ray;
  34478. })(BABYLON || (BABYLON = {}));
  34479. //# sourceMappingURL=babylon.ray.js.map
  34480. var BABYLON;
  34481. (function (BABYLON) {
  34482. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  34483. if (boxMin.x > sphereCenter.x + sphereRadius)
  34484. return false;
  34485. if (sphereCenter.x - sphereRadius > boxMax.x)
  34486. return false;
  34487. if (boxMin.y > sphereCenter.y + sphereRadius)
  34488. return false;
  34489. if (sphereCenter.y - sphereRadius > boxMax.y)
  34490. return false;
  34491. if (boxMin.z > sphereCenter.z + sphereRadius)
  34492. return false;
  34493. if (sphereCenter.z - sphereRadius > boxMax.z)
  34494. return false;
  34495. return true;
  34496. };
  34497. var getLowestRoot = (function () {
  34498. var result = { root: 0, found: false };
  34499. return function (a, b, c, maxR) {
  34500. result.root = 0;
  34501. result.found = false;
  34502. var determinant = b * b - 4.0 * a * c;
  34503. if (determinant < 0)
  34504. return result;
  34505. var sqrtD = Math.sqrt(determinant);
  34506. var r1 = (-b - sqrtD) / (2.0 * a);
  34507. var r2 = (-b + sqrtD) / (2.0 * a);
  34508. if (r1 > r2) {
  34509. var temp = r2;
  34510. r2 = r1;
  34511. r1 = temp;
  34512. }
  34513. if (r1 > 0 && r1 < maxR) {
  34514. result.root = r1;
  34515. result.found = true;
  34516. return result;
  34517. }
  34518. if (r2 > 0 && r2 < maxR) {
  34519. result.root = r2;
  34520. result.found = true;
  34521. return result;
  34522. }
  34523. return result;
  34524. };
  34525. })();
  34526. var Collider = (function () {
  34527. function Collider() {
  34528. this.radius = new BABYLON.Vector3(1, 1, 1);
  34529. this.retry = 0;
  34530. this.basePointWorld = BABYLON.Vector3.Zero();
  34531. this.velocityWorld = BABYLON.Vector3.Zero();
  34532. this.normalizedVelocity = BABYLON.Vector3.Zero();
  34533. this._collisionPoint = BABYLON.Vector3.Zero();
  34534. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  34535. this._tempVector = BABYLON.Vector3.Zero();
  34536. this._tempVector2 = BABYLON.Vector3.Zero();
  34537. this._tempVector3 = BABYLON.Vector3.Zero();
  34538. this._tempVector4 = BABYLON.Vector3.Zero();
  34539. this._edge = BABYLON.Vector3.Zero();
  34540. this._baseToVertex = BABYLON.Vector3.Zero();
  34541. this._destinationPoint = BABYLON.Vector3.Zero();
  34542. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  34543. this._displacementVector = BABYLON.Vector3.Zero();
  34544. this._collisionMask = -1;
  34545. }
  34546. Object.defineProperty(Collider.prototype, "collisionMask", {
  34547. get: function () {
  34548. return this._collisionMask;
  34549. },
  34550. set: function (mask) {
  34551. this._collisionMask = !isNaN(mask) ? mask : -1;
  34552. },
  34553. enumerable: true,
  34554. configurable: true
  34555. });
  34556. // Methods
  34557. Collider.prototype._initialize = function (source, dir, e) {
  34558. this.velocity = dir;
  34559. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  34560. this.basePoint = source;
  34561. source.multiplyToRef(this.radius, this.basePointWorld);
  34562. dir.multiplyToRef(this.radius, this.velocityWorld);
  34563. this.velocityWorldLength = this.velocityWorld.length();
  34564. this.epsilon = e;
  34565. this.collisionFound = false;
  34566. };
  34567. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  34568. pa.subtractToRef(point, this._tempVector);
  34569. pb.subtractToRef(point, this._tempVector2);
  34570. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  34571. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  34572. if (d < 0)
  34573. return false;
  34574. pc.subtractToRef(point, this._tempVector3);
  34575. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  34576. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  34577. if (d < 0)
  34578. return false;
  34579. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  34580. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  34581. return d >= 0;
  34582. };
  34583. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  34584. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  34585. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  34586. if (distance > this.velocityWorldLength + max + sphereRadius) {
  34587. return false;
  34588. }
  34589. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  34590. return false;
  34591. return true;
  34592. };
  34593. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  34594. var t0;
  34595. var embeddedInPlane = false;
  34596. //defensive programming, actually not needed.
  34597. if (!trianglePlaneArray) {
  34598. trianglePlaneArray = [];
  34599. }
  34600. if (!trianglePlaneArray[faceIndex]) {
  34601. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  34602. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  34603. }
  34604. var trianglePlane = trianglePlaneArray[faceIndex];
  34605. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  34606. return;
  34607. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  34608. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  34609. if (normalDotVelocity == 0) {
  34610. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  34611. return;
  34612. embeddedInPlane = true;
  34613. t0 = 0;
  34614. }
  34615. else {
  34616. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  34617. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  34618. if (t0 > t1) {
  34619. var temp = t1;
  34620. t1 = t0;
  34621. t0 = temp;
  34622. }
  34623. if (t0 > 1.0 || t1 < 0.0)
  34624. return;
  34625. if (t0 < 0)
  34626. t0 = 0;
  34627. if (t0 > 1.0)
  34628. t0 = 1.0;
  34629. }
  34630. this._collisionPoint.copyFromFloats(0, 0, 0);
  34631. var found = false;
  34632. var t = 1.0;
  34633. if (!embeddedInPlane) {
  34634. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  34635. this.velocity.scaleToRef(t0, this._tempVector);
  34636. this._planeIntersectionPoint.addInPlace(this._tempVector);
  34637. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  34638. found = true;
  34639. t = t0;
  34640. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  34641. }
  34642. }
  34643. if (!found) {
  34644. var velocitySquaredLength = this.velocity.lengthSquared();
  34645. var a = velocitySquaredLength;
  34646. this.basePoint.subtractToRef(p1, this._tempVector);
  34647. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  34648. var c = this._tempVector.lengthSquared() - 1.0;
  34649. var lowestRoot = getLowestRoot(a, b, c, t);
  34650. if (lowestRoot.found) {
  34651. t = lowestRoot.root;
  34652. found = true;
  34653. this._collisionPoint.copyFrom(p1);
  34654. }
  34655. this.basePoint.subtractToRef(p2, this._tempVector);
  34656. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  34657. c = this._tempVector.lengthSquared() - 1.0;
  34658. lowestRoot = getLowestRoot(a, b, c, t);
  34659. if (lowestRoot.found) {
  34660. t = lowestRoot.root;
  34661. found = true;
  34662. this._collisionPoint.copyFrom(p2);
  34663. }
  34664. this.basePoint.subtractToRef(p3, this._tempVector);
  34665. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  34666. c = this._tempVector.lengthSquared() - 1.0;
  34667. lowestRoot = getLowestRoot(a, b, c, t);
  34668. if (lowestRoot.found) {
  34669. t = lowestRoot.root;
  34670. found = true;
  34671. this._collisionPoint.copyFrom(p3);
  34672. }
  34673. p2.subtractToRef(p1, this._edge);
  34674. p1.subtractToRef(this.basePoint, this._baseToVertex);
  34675. var edgeSquaredLength = this._edge.lengthSquared();
  34676. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  34677. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  34678. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  34679. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  34680. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  34681. lowestRoot = getLowestRoot(a, b, c, t);
  34682. if (lowestRoot.found) {
  34683. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  34684. if (f >= 0.0 && f <= 1.0) {
  34685. t = lowestRoot.root;
  34686. found = true;
  34687. this._edge.scaleInPlace(f);
  34688. p1.addToRef(this._edge, this._collisionPoint);
  34689. }
  34690. }
  34691. p3.subtractToRef(p2, this._edge);
  34692. p2.subtractToRef(this.basePoint, this._baseToVertex);
  34693. edgeSquaredLength = this._edge.lengthSquared();
  34694. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  34695. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  34696. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  34697. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  34698. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  34699. lowestRoot = getLowestRoot(a, b, c, t);
  34700. if (lowestRoot.found) {
  34701. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  34702. if (f >= 0.0 && f <= 1.0) {
  34703. t = lowestRoot.root;
  34704. found = true;
  34705. this._edge.scaleInPlace(f);
  34706. p2.addToRef(this._edge, this._collisionPoint);
  34707. }
  34708. }
  34709. p1.subtractToRef(p3, this._edge);
  34710. p3.subtractToRef(this.basePoint, this._baseToVertex);
  34711. edgeSquaredLength = this._edge.lengthSquared();
  34712. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  34713. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  34714. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  34715. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  34716. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  34717. lowestRoot = getLowestRoot(a, b, c, t);
  34718. if (lowestRoot.found) {
  34719. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  34720. if (f >= 0.0 && f <= 1.0) {
  34721. t = lowestRoot.root;
  34722. found = true;
  34723. this._edge.scaleInPlace(f);
  34724. p3.addToRef(this._edge, this._collisionPoint);
  34725. }
  34726. }
  34727. }
  34728. if (found) {
  34729. var distToCollision = t * this.velocity.length();
  34730. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  34731. if (!this.intersectionPoint) {
  34732. this.intersectionPoint = this._collisionPoint.clone();
  34733. }
  34734. else {
  34735. this.intersectionPoint.copyFrom(this._collisionPoint);
  34736. }
  34737. this.nearestDistance = distToCollision;
  34738. this.collisionFound = true;
  34739. }
  34740. }
  34741. };
  34742. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  34743. for (var i = indexStart; i < indexEnd; i += 3) {
  34744. var p1 = pts[indices[i] - decal];
  34745. var p2 = pts[indices[i + 1] - decal];
  34746. var p3 = pts[indices[i + 2] - decal];
  34747. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  34748. }
  34749. };
  34750. Collider.prototype._getResponse = function (pos, vel) {
  34751. pos.addToRef(vel, this._destinationPoint);
  34752. vel.scaleInPlace((this.nearestDistance / vel.length()));
  34753. this.basePoint.addToRef(vel, pos);
  34754. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  34755. this._slidePlaneNormal.normalize();
  34756. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  34757. pos.addInPlace(this._displacementVector);
  34758. this.intersectionPoint.addInPlace(this._displacementVector);
  34759. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  34760. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  34761. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  34762. };
  34763. return Collider;
  34764. }());
  34765. BABYLON.Collider = Collider;
  34766. })(BABYLON || (BABYLON = {}));
  34767. //# sourceMappingURL=babylon.collider.js.map
  34768. var BABYLON;
  34769. (function (BABYLON) {
  34770. //WebWorker code will be inserted to this variable.
  34771. BABYLON.CollisionWorker = "";
  34772. var WorkerTaskType;
  34773. (function (WorkerTaskType) {
  34774. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  34775. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  34776. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  34777. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  34778. var WorkerReplyType;
  34779. (function (WorkerReplyType) {
  34780. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  34781. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  34782. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  34783. var CollisionCoordinatorWorker = (function () {
  34784. function CollisionCoordinatorWorker() {
  34785. var _this = this;
  34786. this._scaledPosition = BABYLON.Vector3.Zero();
  34787. this._scaledVelocity = BABYLON.Vector3.Zero();
  34788. this.onMeshUpdated = function (mesh) {
  34789. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  34790. };
  34791. this.onGeometryUpdated = function (geometry) {
  34792. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  34793. };
  34794. this._afterRender = function () {
  34795. if (!_this._init)
  34796. return;
  34797. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  34798. return;
  34799. }
  34800. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  34801. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  34802. if (_this._runningUpdated > 4) {
  34803. return;
  34804. }
  34805. ++_this._runningUpdated;
  34806. var payload = {
  34807. updatedMeshes: _this._addUpdateMeshesList,
  34808. updatedGeometries: _this._addUpdateGeometriesList,
  34809. removedGeometries: _this._toRemoveGeometryArray,
  34810. removedMeshes: _this._toRemoveMeshesArray
  34811. };
  34812. var message = {
  34813. payload: payload,
  34814. taskType: WorkerTaskType.UPDATE
  34815. };
  34816. var serializable = [];
  34817. for (var id in payload.updatedGeometries) {
  34818. if (payload.updatedGeometries.hasOwnProperty(id)) {
  34819. //prepare transferables
  34820. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  34821. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  34822. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  34823. }
  34824. }
  34825. _this._worker.postMessage(message, serializable);
  34826. _this._addUpdateMeshesList = {};
  34827. _this._addUpdateGeometriesList = {};
  34828. _this._toRemoveGeometryArray = [];
  34829. _this._toRemoveMeshesArray = [];
  34830. };
  34831. this._onMessageFromWorker = function (e) {
  34832. var returnData = e.data;
  34833. if (returnData.error != WorkerReplyType.SUCCESS) {
  34834. //TODO what errors can be returned from the worker?
  34835. BABYLON.Tools.Warn("error returned from worker!");
  34836. return;
  34837. }
  34838. switch (returnData.taskType) {
  34839. case WorkerTaskType.INIT:
  34840. _this._init = true;
  34841. //Update the worked with ALL of the scene's current state
  34842. _this._scene.meshes.forEach(function (mesh) {
  34843. _this.onMeshAdded(mesh);
  34844. });
  34845. _this._scene.getGeometries().forEach(function (geometry) {
  34846. _this.onGeometryAdded(geometry);
  34847. });
  34848. break;
  34849. case WorkerTaskType.UPDATE:
  34850. _this._runningUpdated--;
  34851. break;
  34852. case WorkerTaskType.COLLIDE:
  34853. _this._runningCollisionTask = false;
  34854. var returnPayload = returnData.payload;
  34855. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  34856. return;
  34857. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  34858. //cleanup
  34859. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  34860. break;
  34861. }
  34862. };
  34863. this._collisionsCallbackArray = [];
  34864. this._init = false;
  34865. this._runningUpdated = 0;
  34866. this._runningCollisionTask = false;
  34867. this._addUpdateMeshesList = {};
  34868. this._addUpdateGeometriesList = {};
  34869. this._toRemoveGeometryArray = [];
  34870. this._toRemoveMeshesArray = [];
  34871. }
  34872. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  34873. if (!this._init)
  34874. return;
  34875. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  34876. return;
  34877. position.divideToRef(collider.radius, this._scaledPosition);
  34878. velocity.divideToRef(collider.radius, this._scaledVelocity);
  34879. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  34880. var payload = {
  34881. collider: {
  34882. position: this._scaledPosition.asArray(),
  34883. velocity: this._scaledVelocity.asArray(),
  34884. radius: collider.radius.asArray()
  34885. },
  34886. collisionId: collisionIndex,
  34887. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  34888. maximumRetry: maximumRetry
  34889. };
  34890. var message = {
  34891. payload: payload,
  34892. taskType: WorkerTaskType.COLLIDE
  34893. };
  34894. this._worker.postMessage(message);
  34895. };
  34896. CollisionCoordinatorWorker.prototype.init = function (scene) {
  34897. this._scene = scene;
  34898. this._scene.registerAfterRender(this._afterRender);
  34899. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  34900. this._worker = new Worker(workerUrl);
  34901. this._worker.onmessage = this._onMessageFromWorker;
  34902. var message = {
  34903. payload: {},
  34904. taskType: WorkerTaskType.INIT
  34905. };
  34906. this._worker.postMessage(message);
  34907. };
  34908. CollisionCoordinatorWorker.prototype.destroy = function () {
  34909. this._scene.unregisterAfterRender(this._afterRender);
  34910. this._worker.terminate();
  34911. };
  34912. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  34913. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  34914. this.onMeshUpdated(mesh);
  34915. };
  34916. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  34917. this._toRemoveMeshesArray.push(mesh.uniqueId);
  34918. };
  34919. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  34920. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  34921. geometry.onGeometryUpdated = this.onGeometryUpdated;
  34922. this.onGeometryUpdated(geometry);
  34923. };
  34924. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  34925. this._toRemoveGeometryArray.push(geometry.id);
  34926. };
  34927. return CollisionCoordinatorWorker;
  34928. }());
  34929. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  34930. var submeshes = [];
  34931. if (mesh.subMeshes) {
  34932. submeshes = mesh.subMeshes.map(function (sm, idx) {
  34933. return {
  34934. position: idx,
  34935. verticesStart: sm.verticesStart,
  34936. verticesCount: sm.verticesCount,
  34937. indexStart: sm.indexStart,
  34938. indexCount: sm.indexCount,
  34939. hasMaterial: !!sm.getMaterial(),
  34940. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  34941. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  34942. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  34943. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  34944. };
  34945. });
  34946. }
  34947. var geometryId = null;
  34948. if (mesh instanceof BABYLON.Mesh) {
  34949. geometryId = mesh.geometry ? mesh.geometry.id : null;
  34950. }
  34951. else if (mesh instanceof BABYLON.InstancedMesh) {
  34952. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  34953. }
  34954. return {
  34955. uniqueId: mesh.uniqueId,
  34956. id: mesh.id,
  34957. name: mesh.name,
  34958. geometryId: geometryId,
  34959. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  34960. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  34961. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  34962. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  34963. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  34964. subMeshes: submeshes,
  34965. checkCollisions: mesh.checkCollisions
  34966. };
  34967. };
  34968. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  34969. return {
  34970. id: geometry.id,
  34971. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  34972. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  34973. indices: new Uint32Array(geometry.getIndices() || []),
  34974. };
  34975. };
  34976. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  34977. var CollisionCoordinatorLegacy = (function () {
  34978. function CollisionCoordinatorLegacy() {
  34979. this._scaledPosition = BABYLON.Vector3.Zero();
  34980. this._scaledVelocity = BABYLON.Vector3.Zero();
  34981. this._finalPosition = BABYLON.Vector3.Zero();
  34982. }
  34983. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  34984. position.divideToRef(collider.radius, this._scaledPosition);
  34985. velocity.divideToRef(collider.radius, this._scaledVelocity);
  34986. collider.collidedMesh = null;
  34987. collider.retry = 0;
  34988. collider.initialVelocity = this._scaledVelocity;
  34989. collider.initialPosition = this._scaledPosition;
  34990. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  34991. this._finalPosition.multiplyInPlace(collider.radius);
  34992. //run the callback
  34993. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  34994. };
  34995. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  34996. this._scene = scene;
  34997. };
  34998. CollisionCoordinatorLegacy.prototype.destroy = function () {
  34999. //Legacy need no destruction method.
  35000. };
  35001. //No update in legacy mode
  35002. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  35003. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  35004. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  35005. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  35006. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  35007. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  35008. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  35009. if (excludedMesh === void 0) { excludedMesh = null; }
  35010. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  35011. if (collider.retry >= maximumRetry) {
  35012. finalPosition.copyFrom(position);
  35013. return;
  35014. }
  35015. // Check if this is a mesh else camera or -1
  35016. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  35017. collider._initialize(position, velocity, closeDistance);
  35018. // Check all meshes
  35019. for (var index = 0; index < this._scene.meshes.length; index++) {
  35020. var mesh = this._scene.meshes[index];
  35021. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  35022. mesh._checkCollision(collider);
  35023. }
  35024. }
  35025. if (!collider.collisionFound) {
  35026. position.addToRef(velocity, finalPosition);
  35027. return;
  35028. }
  35029. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  35030. collider._getResponse(position, velocity);
  35031. }
  35032. if (velocity.length() <= closeDistance) {
  35033. finalPosition.copyFrom(position);
  35034. return;
  35035. }
  35036. collider.retry++;
  35037. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  35038. };
  35039. return CollisionCoordinatorLegacy;
  35040. }());
  35041. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  35042. })(BABYLON || (BABYLON = {}));
  35043. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  35044. var BABYLON;
  35045. (function (BABYLON) {
  35046. var Particle = (function () {
  35047. function Particle() {
  35048. this.position = BABYLON.Vector3.Zero();
  35049. this.direction = BABYLON.Vector3.Zero();
  35050. this.color = new BABYLON.Color4(0, 0, 0, 0);
  35051. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  35052. this.lifeTime = 1.0;
  35053. this.age = 0;
  35054. this.size = 0;
  35055. this.angle = 0;
  35056. this.angularSpeed = 0;
  35057. }
  35058. Particle.prototype.copyTo = function (other) {
  35059. other.position.copyFrom(this.position);
  35060. other.direction.copyFrom(this.direction);
  35061. other.color.copyFrom(this.color);
  35062. other.colorStep.copyFrom(this.colorStep);
  35063. other.lifeTime = this.lifeTime;
  35064. other.age = this.age;
  35065. other.size = this.size;
  35066. other.angle = this.angle;
  35067. other.angularSpeed = this.angularSpeed;
  35068. };
  35069. return Particle;
  35070. }());
  35071. BABYLON.Particle = Particle;
  35072. })(BABYLON || (BABYLON = {}));
  35073. //# sourceMappingURL=babylon.particle.js.map
  35074. var BABYLON;
  35075. (function (BABYLON) {
  35076. var randomNumber = function (min, max) {
  35077. if (min === max) {
  35078. return (min);
  35079. }
  35080. var random = Math.random();
  35081. return ((random * (max - min)) + min);
  35082. };
  35083. var ParticleSystem = (function () {
  35084. function ParticleSystem(name, capacity, scene, customEffect) {
  35085. var _this = this;
  35086. this.name = name;
  35087. // Members
  35088. this.animations = [];
  35089. this.renderingGroupId = 0;
  35090. this.emitter = null;
  35091. this.emitRate = 10;
  35092. this.manualEmitCount = -1;
  35093. this.updateSpeed = 0.01;
  35094. this.targetStopDuration = 0;
  35095. this.disposeOnStop = false;
  35096. this.minEmitPower = 1;
  35097. this.maxEmitPower = 1;
  35098. this.minLifeTime = 1;
  35099. this.maxLifeTime = 1;
  35100. this.minSize = 1;
  35101. this.maxSize = 1;
  35102. this.minAngularSpeed = 0;
  35103. this.maxAngularSpeed = 0;
  35104. this.layerMask = 0x0FFFFFFF;
  35105. this.customShader = null;
  35106. this.preventAutoStart = false;
  35107. /**
  35108. * An event triggered when the system is disposed.
  35109. * @type {BABYLON.Observable}
  35110. */
  35111. this.onDisposeObservable = new BABYLON.Observable();
  35112. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  35113. this.forceDepthWrite = false;
  35114. this.gravity = BABYLON.Vector3.Zero();
  35115. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  35116. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  35117. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  35118. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  35119. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35120. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35121. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  35122. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35123. this.particles = new Array();
  35124. this._stockParticles = new Array();
  35125. this._newPartsExcess = 0;
  35126. this._vertexBuffers = {};
  35127. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  35128. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  35129. this._scaledDirection = BABYLON.Vector3.Zero();
  35130. this._scaledGravity = BABYLON.Vector3.Zero();
  35131. this._currentRenderId = -1;
  35132. this._started = false;
  35133. this._stopped = false;
  35134. this._actualFrame = 0;
  35135. this.id = name;
  35136. this._capacity = capacity;
  35137. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35138. this._customEffect = customEffect;
  35139. scene.particleSystems.push(this);
  35140. var indices = [];
  35141. var index = 0;
  35142. for (var count = 0; count < capacity; count++) {
  35143. indices.push(index);
  35144. indices.push(index + 1);
  35145. indices.push(index + 2);
  35146. indices.push(index);
  35147. indices.push(index + 2);
  35148. indices.push(index + 3);
  35149. index += 4;
  35150. }
  35151. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  35152. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  35153. this._vertexData = new Float32Array(capacity * 11 * 4);
  35154. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  35155. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  35156. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  35157. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  35158. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  35159. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  35160. this._vertexBuffers["options"] = options;
  35161. // Default behaviors
  35162. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  35163. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  35164. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  35165. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  35166. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  35167. };
  35168. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  35169. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  35170. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  35171. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  35172. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  35173. };
  35174. this.updateFunction = function (particles) {
  35175. for (var index = 0; index < particles.length; index++) {
  35176. var particle = particles[index];
  35177. particle.age += _this._scaledUpdateSpeed;
  35178. if (particle.age >= particle.lifeTime) {
  35179. _this.recycleParticle(particle);
  35180. index--;
  35181. continue;
  35182. }
  35183. else {
  35184. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  35185. particle.color.addInPlace(_this._scaledColorStep);
  35186. if (particle.color.a < 0)
  35187. particle.color.a = 0;
  35188. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  35189. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  35190. particle.position.addInPlace(_this._scaledDirection);
  35191. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  35192. particle.direction.addInPlace(_this._scaledGravity);
  35193. }
  35194. }
  35195. };
  35196. }
  35197. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  35198. set: function (callback) {
  35199. if (this._onDisposeObserver) {
  35200. this.onDisposeObservable.remove(this._onDisposeObserver);
  35201. }
  35202. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35203. },
  35204. enumerable: true,
  35205. configurable: true
  35206. });
  35207. ParticleSystem.prototype.recycleParticle = function (particle) {
  35208. var lastParticle = this.particles.pop();
  35209. if (lastParticle !== particle) {
  35210. lastParticle.copyTo(particle);
  35211. this._stockParticles.push(lastParticle);
  35212. }
  35213. };
  35214. ParticleSystem.prototype.getCapacity = function () {
  35215. return this._capacity;
  35216. };
  35217. ParticleSystem.prototype.isAlive = function () {
  35218. return this._alive;
  35219. };
  35220. ParticleSystem.prototype.isStarted = function () {
  35221. return this._started;
  35222. };
  35223. ParticleSystem.prototype.start = function () {
  35224. this._started = true;
  35225. this._stopped = false;
  35226. this._actualFrame = 0;
  35227. };
  35228. ParticleSystem.prototype.stop = function () {
  35229. this._stopped = true;
  35230. };
  35231. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  35232. var offset = index * 11;
  35233. this._vertexData[offset] = particle.position.x;
  35234. this._vertexData[offset + 1] = particle.position.y;
  35235. this._vertexData[offset + 2] = particle.position.z;
  35236. this._vertexData[offset + 3] = particle.color.r;
  35237. this._vertexData[offset + 4] = particle.color.g;
  35238. this._vertexData[offset + 5] = particle.color.b;
  35239. this._vertexData[offset + 6] = particle.color.a;
  35240. this._vertexData[offset + 7] = particle.angle;
  35241. this._vertexData[offset + 8] = particle.size;
  35242. this._vertexData[offset + 9] = offsetX;
  35243. this._vertexData[offset + 10] = offsetY;
  35244. };
  35245. ParticleSystem.prototype._update = function (newParticles) {
  35246. // Update current
  35247. this._alive = this.particles.length > 0;
  35248. this.updateFunction(this.particles);
  35249. // Add new ones
  35250. var worldMatrix;
  35251. if (this.emitter.position) {
  35252. worldMatrix = this.emitter.getWorldMatrix();
  35253. }
  35254. else {
  35255. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  35256. }
  35257. var particle;
  35258. for (var index = 0; index < newParticles; index++) {
  35259. if (this.particles.length === this._capacity) {
  35260. break;
  35261. }
  35262. if (this._stockParticles.length !== 0) {
  35263. particle = this._stockParticles.pop();
  35264. particle.age = 0;
  35265. }
  35266. else {
  35267. particle = new BABYLON.Particle();
  35268. }
  35269. this.particles.push(particle);
  35270. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  35271. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  35272. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  35273. particle.size = randomNumber(this.minSize, this.maxSize);
  35274. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  35275. this.startPositionFunction(worldMatrix, particle.position, particle);
  35276. var step = randomNumber(0, 1.0);
  35277. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  35278. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  35279. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  35280. }
  35281. };
  35282. ParticleSystem.prototype._getEffect = function () {
  35283. if (this._customEffect) {
  35284. return this._customEffect;
  35285. }
  35286. ;
  35287. var defines = [];
  35288. if (this._scene.clipPlane) {
  35289. defines.push("#define CLIPPLANE");
  35290. }
  35291. // Effect
  35292. var join = defines.join("\n");
  35293. if (this._cachedDefines !== join) {
  35294. this._cachedDefines = join;
  35295. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  35296. }
  35297. return this._effect;
  35298. };
  35299. ParticleSystem.prototype.animate = function () {
  35300. if (!this._started)
  35301. return;
  35302. var effect = this._getEffect();
  35303. // Check
  35304. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  35305. return;
  35306. if (this._currentRenderId === this._scene.getRenderId()) {
  35307. return;
  35308. }
  35309. this._currentRenderId = this._scene.getRenderId();
  35310. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  35311. // determine the number of particles we need to create
  35312. var newParticles;
  35313. if (this.manualEmitCount > -1) {
  35314. newParticles = this.manualEmitCount;
  35315. this._newPartsExcess = 0;
  35316. this.manualEmitCount = 0;
  35317. }
  35318. else {
  35319. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  35320. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  35321. }
  35322. if (this._newPartsExcess > 1.0) {
  35323. newParticles += this._newPartsExcess >> 0;
  35324. this._newPartsExcess -= this._newPartsExcess >> 0;
  35325. }
  35326. this._alive = false;
  35327. if (!this._stopped) {
  35328. this._actualFrame += this._scaledUpdateSpeed;
  35329. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  35330. this.stop();
  35331. }
  35332. else {
  35333. newParticles = 0;
  35334. }
  35335. this._update(newParticles);
  35336. // Stopped?
  35337. if (this._stopped) {
  35338. if (!this._alive) {
  35339. this._started = false;
  35340. if (this.disposeOnStop) {
  35341. this._scene._toBeDisposed.push(this);
  35342. }
  35343. }
  35344. }
  35345. // Update VBO
  35346. var offset = 0;
  35347. for (var index = 0; index < this.particles.length; index++) {
  35348. var particle = this.particles[index];
  35349. this._appendParticleVertex(offset++, particle, 0, 0);
  35350. this._appendParticleVertex(offset++, particle, 1, 0);
  35351. this._appendParticleVertex(offset++, particle, 1, 1);
  35352. this._appendParticleVertex(offset++, particle, 0, 1);
  35353. }
  35354. this._vertexBuffer.update(this._vertexData);
  35355. };
  35356. ParticleSystem.prototype.render = function () {
  35357. var effect = this._getEffect();
  35358. // Check
  35359. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  35360. return 0;
  35361. var engine = this._scene.getEngine();
  35362. // Render
  35363. engine.enableEffect(effect);
  35364. engine.setState(false);
  35365. var viewMatrix = this._scene.getViewMatrix();
  35366. effect.setTexture("diffuseSampler", this.particleTexture);
  35367. effect.setMatrix("view", viewMatrix);
  35368. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  35369. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  35370. if (this._scene.clipPlane) {
  35371. var clipPlane = this._scene.clipPlane;
  35372. var invView = viewMatrix.clone();
  35373. invView.invert();
  35374. effect.setMatrix("invView", invView);
  35375. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  35376. }
  35377. // VBOs
  35378. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35379. // Draw order
  35380. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  35381. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  35382. }
  35383. else {
  35384. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35385. }
  35386. if (this.forceDepthWrite) {
  35387. engine.setDepthWrite(true);
  35388. }
  35389. engine.draw(true, 0, this.particles.length * 6);
  35390. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35391. return this.particles.length;
  35392. };
  35393. ParticleSystem.prototype.dispose = function () {
  35394. if (this._vertexBuffer) {
  35395. this._vertexBuffer.dispose();
  35396. this._vertexBuffer = null;
  35397. }
  35398. if (this._indexBuffer) {
  35399. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35400. this._indexBuffer = null;
  35401. }
  35402. if (this.particleTexture) {
  35403. this.particleTexture.dispose();
  35404. this.particleTexture = null;
  35405. }
  35406. // Remove from scene
  35407. var index = this._scene.particleSystems.indexOf(this);
  35408. this._scene.particleSystems.splice(index, 1);
  35409. // Callback
  35410. this.onDisposeObservable.notifyObservers(this);
  35411. this.onDisposeObservable.clear();
  35412. };
  35413. // Clone
  35414. ParticleSystem.prototype.clone = function (name, newEmitter) {
  35415. var custom = null;
  35416. var program = null;
  35417. if (this.customShader != null) {
  35418. program = this.customShader;
  35419. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  35420. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  35421. }
  35422. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  35423. result.customShader = program;
  35424. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  35425. if (newEmitter === undefined) {
  35426. newEmitter = this.emitter;
  35427. }
  35428. result.emitter = newEmitter;
  35429. if (this.particleTexture) {
  35430. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  35431. }
  35432. if (!this.preventAutoStart) {
  35433. result.start();
  35434. }
  35435. return result;
  35436. };
  35437. ParticleSystem.prototype.serialize = function () {
  35438. var serializationObject = {};
  35439. serializationObject.name = this.name;
  35440. serializationObject.id = this.id;
  35441. // Emitter
  35442. if (this.emitter.position) {
  35443. serializationObject.emitterId = this.emitter.id;
  35444. }
  35445. else {
  35446. serializationObject.emitter = this.emitter.asArray();
  35447. }
  35448. serializationObject.capacity = this.getCapacity();
  35449. if (this.particleTexture) {
  35450. serializationObject.textureName = this.particleTexture.name;
  35451. }
  35452. // Animations
  35453. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  35454. // Particle system
  35455. serializationObject.minAngularSpeed = this.minAngularSpeed;
  35456. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  35457. serializationObject.minSize = this.minSize;
  35458. serializationObject.maxSize = this.maxSize;
  35459. serializationObject.minEmitPower = this.minEmitPower;
  35460. serializationObject.maxEmitPower = this.maxEmitPower;
  35461. serializationObject.minLifeTime = this.minLifeTime;
  35462. serializationObject.maxLifeTime = this.maxLifeTime;
  35463. serializationObject.emitRate = this.emitRate;
  35464. serializationObject.minEmitBox = this.minEmitBox.asArray();
  35465. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  35466. serializationObject.gravity = this.gravity.asArray();
  35467. serializationObject.direction1 = this.direction1.asArray();
  35468. serializationObject.direction2 = this.direction2.asArray();
  35469. serializationObject.color1 = this.color1.asArray();
  35470. serializationObject.color2 = this.color2.asArray();
  35471. serializationObject.colorDead = this.colorDead.asArray();
  35472. serializationObject.updateSpeed = this.updateSpeed;
  35473. serializationObject.targetStopDuration = this.targetStopDuration;
  35474. serializationObject.textureMask = this.textureMask.asArray();
  35475. serializationObject.blendMode = this.blendMode;
  35476. serializationObject.customShader = this.customShader;
  35477. serializationObject.preventAutoStart = this.preventAutoStart;
  35478. return serializationObject;
  35479. };
  35480. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  35481. var name = parsedParticleSystem.name;
  35482. var custom = null;
  35483. var program = null;
  35484. if (parsedParticleSystem.customShader) {
  35485. program = parsedParticleSystem.customShader;
  35486. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  35487. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  35488. }
  35489. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  35490. particleSystem.customShader = program;
  35491. if (parsedParticleSystem.id) {
  35492. particleSystem.id = parsedParticleSystem.id;
  35493. }
  35494. // Auto start
  35495. if (parsedParticleSystem.preventAutoStart) {
  35496. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  35497. }
  35498. // Texture
  35499. if (parsedParticleSystem.textureName) {
  35500. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  35501. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  35502. }
  35503. // Emitter
  35504. if (parsedParticleSystem.emitterId) {
  35505. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  35506. }
  35507. else {
  35508. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  35509. }
  35510. // Animations
  35511. if (parsedParticleSystem.animations) {
  35512. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  35513. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  35514. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  35515. }
  35516. }
  35517. if (parsedParticleSystem.autoAnimate) {
  35518. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  35519. }
  35520. // Particle system
  35521. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  35522. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  35523. particleSystem.minSize = parsedParticleSystem.minSize;
  35524. particleSystem.maxSize = parsedParticleSystem.maxSize;
  35525. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  35526. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  35527. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  35528. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  35529. particleSystem.emitRate = parsedParticleSystem.emitRate;
  35530. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  35531. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  35532. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  35533. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  35534. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  35535. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  35536. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  35537. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  35538. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  35539. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  35540. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  35541. particleSystem.blendMode = parsedParticleSystem.blendMode;
  35542. if (!particleSystem.preventAutoStart) {
  35543. particleSystem.start();
  35544. }
  35545. return particleSystem;
  35546. };
  35547. return ParticleSystem;
  35548. }());
  35549. // Statics
  35550. ParticleSystem.BLENDMODE_ONEONE = 0;
  35551. ParticleSystem.BLENDMODE_STANDARD = 1;
  35552. BABYLON.ParticleSystem = ParticleSystem;
  35553. })(BABYLON || (BABYLON = {}));
  35554. //# sourceMappingURL=babylon.particleSystem.js.map
  35555. var BABYLON;
  35556. (function (BABYLON) {
  35557. var SolidParticle = (function () {
  35558. /**
  35559. * Creates a Solid Particle object.
  35560. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  35561. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  35562. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  35563. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  35564. * `shapeId` (integer) is the model shape identifier in the SPS.
  35565. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  35566. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  35567. */
  35568. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  35569. this.idx = 0; // particle global index
  35570. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  35571. this.position = BABYLON.Vector3.Zero(); // position
  35572. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35573. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  35574. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  35575. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35576. this.alive = true; // alive
  35577. this.isVisible = true; // visibility
  35578. this._pos = 0; // index of this particle in the global "positions" array
  35579. this.shapeId = 0; // model shape id
  35580. this.idxInShape = 0; // index of the particle in its shape id
  35581. this.idx = particleIndex;
  35582. this._pos = positionIndex;
  35583. this._model = model;
  35584. this.shapeId = shapeId;
  35585. this.idxInShape = idxInShape;
  35586. this._sps = sps;
  35587. if (modelBoundingInfo) {
  35588. this._modelBoundingInfo = modelBoundingInfo;
  35589. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  35590. }
  35591. }
  35592. Object.defineProperty(SolidParticle.prototype, "scale", {
  35593. /**
  35594. * legacy support, changed scale to scaling
  35595. */
  35596. get: function () {
  35597. return this.scaling;
  35598. },
  35599. set: function (scale) {
  35600. this.scaling = scale;
  35601. },
  35602. enumerable: true,
  35603. configurable: true
  35604. });
  35605. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  35606. /**
  35607. * legacy support, changed quaternion to rotationQuaternion
  35608. */
  35609. get: function () {
  35610. return this.rotationQuaternion;
  35611. },
  35612. set: function (q) {
  35613. this.rotationQuaternion = q;
  35614. },
  35615. enumerable: true,
  35616. configurable: true
  35617. });
  35618. /**
  35619. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  35620. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  35621. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  35622. */
  35623. SolidParticle.prototype.intersectsMesh = function (target) {
  35624. if (!this._boundingInfo || !target._boundingInfo) {
  35625. return false;
  35626. }
  35627. if (this._sps._bSphereOnly) {
  35628. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  35629. }
  35630. return this._boundingInfo.intersects(target._boundingInfo, false);
  35631. };
  35632. return SolidParticle;
  35633. }());
  35634. BABYLON.SolidParticle = SolidParticle;
  35635. var ModelShape = (function () {
  35636. /**
  35637. * 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.
  35638. * SPS internal tool, don't use it manually.
  35639. */
  35640. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  35641. this.shapeID = id;
  35642. this._shape = shape;
  35643. this._shapeUV = shapeUV;
  35644. this._positionFunction = posFunction;
  35645. this._vertexFunction = vtxFunction;
  35646. }
  35647. return ModelShape;
  35648. }());
  35649. BABYLON.ModelShape = ModelShape;
  35650. })(BABYLON || (BABYLON = {}));
  35651. //# sourceMappingURL=babylon.solidParticle.js.map
  35652. var BABYLON;
  35653. (function (BABYLON) {
  35654. /**
  35655. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  35656. */
  35657. var SolidParticleSystem = (function () {
  35658. /**
  35659. * Creates a SPS (Solid Particle System) object.
  35660. * `name` (String) is the SPS name, this will be the underlying mesh name.
  35661. * `scene` (Scene) is the scene in which the SPS is added.
  35662. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  35663. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  35664. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  35665. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  35666. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  35667. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  35668. */
  35669. function SolidParticleSystem(name, scene, options) {
  35670. // public members
  35671. /**
  35672. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  35673. * Example : var p = SPS.particles[i];
  35674. */
  35675. this.particles = new Array();
  35676. /**
  35677. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  35678. */
  35679. this.nbParticles = 0;
  35680. /**
  35681. * If the particles must ever face the camera (default false). Useful for planar particles.
  35682. */
  35683. this.billboard = false;
  35684. /**
  35685. * Recompute normals when adding a shape
  35686. */
  35687. this.recomputeNormals = true;
  35688. /**
  35689. * This a counter ofr your own usage. It's not set by any SPS functions.
  35690. */
  35691. this.counter = 0;
  35692. /**
  35693. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  35694. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  35695. */
  35696. this.vars = {};
  35697. this._positions = new Array();
  35698. this._indices = new Array();
  35699. this._normals = new Array();
  35700. this._colors = new Array();
  35701. this._uvs = new Array();
  35702. this._index = 0; // indices index
  35703. this._updatable = true;
  35704. this._pickable = false;
  35705. this._isVisibilityBoxLocked = false;
  35706. this._alwaysVisible = false;
  35707. this._shapeCounter = 0;
  35708. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  35709. this._color = new BABYLON.Color4(0, 0, 0, 0);
  35710. this._computeParticleColor = true;
  35711. this._computeParticleTexture = true;
  35712. this._computeParticleRotation = true;
  35713. this._computeParticleVertex = false;
  35714. this._computeBoundingBox = false;
  35715. this._cam_axisZ = BABYLON.Vector3.Zero();
  35716. this._cam_axisY = BABYLON.Vector3.Zero();
  35717. this._cam_axisX = BABYLON.Vector3.Zero();
  35718. this._axisX = BABYLON.Axis.X;
  35719. this._axisY = BABYLON.Axis.Y;
  35720. this._axisZ = BABYLON.Axis.Z;
  35721. this._camDir = BABYLON.Vector3.Zero();
  35722. this._rotMatrix = new BABYLON.Matrix();
  35723. this._invertMatrix = new BABYLON.Matrix();
  35724. this._rotated = BABYLON.Vector3.Zero();
  35725. this._quaternion = new BABYLON.Quaternion();
  35726. this._vertex = BABYLON.Vector3.Zero();
  35727. this._normal = BABYLON.Vector3.Zero();
  35728. this._yaw = 0.0;
  35729. this._pitch = 0.0;
  35730. this._roll = 0.0;
  35731. this._halfroll = 0.0;
  35732. this._halfpitch = 0.0;
  35733. this._halfyaw = 0.0;
  35734. this._sinRoll = 0.0;
  35735. this._cosRoll = 0.0;
  35736. this._sinPitch = 0.0;
  35737. this._cosPitch = 0.0;
  35738. this._sinYaw = 0.0;
  35739. this._cosYaw = 0.0;
  35740. this._w = 0.0;
  35741. this._mustUnrotateFixedNormals = false;
  35742. this._minimum = BABYLON.Tmp.Vector3[0];
  35743. this._maximum = BABYLON.Tmp.Vector3[1];
  35744. this._scale = BABYLON.Tmp.Vector3[2];
  35745. this._translation = BABYLON.Tmp.Vector3[3];
  35746. this._minBbox = BABYLON.Tmp.Vector3[4];
  35747. this._maxBbox = BABYLON.Tmp.Vector3[5];
  35748. this._particlesIntersect = false;
  35749. this._bSphereOnly = false;
  35750. this._bSphereRadiusFactor = 1.0;
  35751. this.name = name;
  35752. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35753. this._camera = scene.activeCamera;
  35754. this._pickable = options ? options.isPickable : false;
  35755. this._particlesIntersect = options ? options.particleIntersection : false;
  35756. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  35757. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  35758. if (options && options.updatable) {
  35759. this._updatable = options.updatable;
  35760. }
  35761. else {
  35762. this._updatable = true;
  35763. }
  35764. if (this._pickable) {
  35765. this.pickedParticles = [];
  35766. }
  35767. }
  35768. /**
  35769. * Builds the SPS underlying mesh. Returns a standard Mesh.
  35770. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  35771. */
  35772. SolidParticleSystem.prototype.buildMesh = function () {
  35773. if (this.nbParticles === 0) {
  35774. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35775. this.addShape(triangle, 1);
  35776. triangle.dispose();
  35777. }
  35778. this._positions32 = new Float32Array(this._positions);
  35779. this._uvs32 = new Float32Array(this._uvs);
  35780. this._colors32 = new Float32Array(this._colors);
  35781. if (this.recomputeNormals) {
  35782. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  35783. }
  35784. this._normals32 = new Float32Array(this._normals);
  35785. this._fixedNormal32 = new Float32Array(this._normals);
  35786. if (this._mustUnrotateFixedNormals) {
  35787. this._unrotateFixedNormals();
  35788. }
  35789. var vertexData = new BABYLON.VertexData();
  35790. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  35791. vertexData.indices = this._indices;
  35792. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  35793. if (this._uvs32) {
  35794. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  35795. ;
  35796. }
  35797. if (this._colors32) {
  35798. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  35799. }
  35800. var mesh = new BABYLON.Mesh(this.name, this._scene);
  35801. vertexData.applyToMesh(mesh, this._updatable);
  35802. this.mesh = mesh;
  35803. this.mesh.isPickable = this._pickable;
  35804. // free memory
  35805. this._positions = null;
  35806. this._normals = null;
  35807. this._uvs = null;
  35808. this._colors = null;
  35809. if (!this._updatable) {
  35810. this.particles.length = 0;
  35811. }
  35812. return mesh;
  35813. };
  35814. /**
  35815. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  35816. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  35817. * Thus the particles generated from `digest()` have their property `position` set yet.
  35818. * `mesh` ( Mesh ) is the mesh to be digested
  35819. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  35820. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  35821. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  35822. */
  35823. SolidParticleSystem.prototype.digest = function (mesh, options) {
  35824. var size = (options && options.facetNb) || 1;
  35825. var number = (options && options.number);
  35826. var delta = (options && options.delta) || 0;
  35827. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35828. var meshInd = mesh.getIndices();
  35829. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35830. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35831. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35832. var f = 0; // facet counter
  35833. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  35834. // compute size from number
  35835. if (number) {
  35836. number = (number > totalFacets) ? totalFacets : number;
  35837. size = Math.round(totalFacets / number);
  35838. delta = 0;
  35839. }
  35840. else {
  35841. size = (size > totalFacets) ? totalFacets : size;
  35842. }
  35843. var facetPos = []; // submesh positions
  35844. var facetInd = []; // submesh indices
  35845. var facetUV = []; // submesh UV
  35846. var facetCol = []; // submesh colors
  35847. var barycenter = BABYLON.Tmp.Vector3[0];
  35848. var rand;
  35849. var sizeO = size;
  35850. while (f < totalFacets) {
  35851. size = sizeO + Math.floor((1 + delta) * Math.random());
  35852. if (f > totalFacets - size) {
  35853. size = totalFacets - f;
  35854. }
  35855. // reset temp arrays
  35856. facetPos.length = 0;
  35857. facetInd.length = 0;
  35858. facetUV.length = 0;
  35859. facetCol.length = 0;
  35860. // iterate over "size" facets
  35861. var fi = 0;
  35862. for (var j = f * 3; j < (f + size) * 3; j++) {
  35863. facetInd.push(fi);
  35864. var i = meshInd[j];
  35865. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  35866. if (meshUV) {
  35867. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  35868. }
  35869. if (meshCol) {
  35870. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  35871. }
  35872. fi++;
  35873. }
  35874. // create a model shape for each single particle
  35875. var idx = this.nbParticles;
  35876. var shape = this._posToShape(facetPos);
  35877. var shapeUV = this._uvsToShapeUV(facetUV);
  35878. // compute the barycenter of the shape
  35879. var v;
  35880. for (v = 0; v < shape.length; v++) {
  35881. barycenter.addInPlace(shape[v]);
  35882. }
  35883. barycenter.scaleInPlace(1 / shape.length);
  35884. // shift the shape from its barycenter to the origin
  35885. for (v = 0; v < shape.length; v++) {
  35886. shape[v].subtractInPlace(barycenter);
  35887. }
  35888. var bInfo;
  35889. if (this._particlesIntersect) {
  35890. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  35891. }
  35892. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  35893. // add the particle in the SPS
  35894. var currentPos = this._positions.length;
  35895. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  35896. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  35897. // initialize the particle position
  35898. this.particles[this.nbParticles].position.addInPlace(barycenter);
  35899. this._index += shape.length;
  35900. idx++;
  35901. this.nbParticles++;
  35902. this._shapeCounter++;
  35903. f += size;
  35904. }
  35905. return this;
  35906. };
  35907. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  35908. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  35909. var index = 0;
  35910. var idx = 0;
  35911. for (var p = 0; p < this.particles.length; p++) {
  35912. this._particle = this.particles[p];
  35913. this._shape = this._particle._model._shape;
  35914. if (this._particle.rotationQuaternion) {
  35915. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  35916. }
  35917. else {
  35918. this._yaw = this._particle.rotation.y;
  35919. this._pitch = this._particle.rotation.x;
  35920. this._roll = this._particle.rotation.z;
  35921. this._quaternionRotationYPR();
  35922. }
  35923. this._quaternionToRotationMatrix();
  35924. this._rotMatrix.invertToRef(this._invertMatrix);
  35925. for (var pt = 0; pt < this._shape.length; pt++) {
  35926. idx = index + pt * 3;
  35927. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  35928. this._fixedNormal32[idx] = this._normal.x;
  35929. this._fixedNormal32[idx + 1] = this._normal.y;
  35930. this._fixedNormal32[idx + 2] = this._normal.z;
  35931. }
  35932. index = idx + 3;
  35933. }
  35934. };
  35935. //reset copy
  35936. SolidParticleSystem.prototype._resetCopy = function () {
  35937. this._copy.position.x = 0;
  35938. this._copy.position.y = 0;
  35939. this._copy.position.z = 0;
  35940. this._copy.rotation.x = 0;
  35941. this._copy.rotation.y = 0;
  35942. this._copy.rotation.z = 0;
  35943. this._copy.rotationQuaternion = null;
  35944. this._copy.scaling.x = 1;
  35945. this._copy.scaling.y = 1;
  35946. this._copy.scaling.z = 1;
  35947. this._copy.uvs.x = 0;
  35948. this._copy.uvs.y = 0;
  35949. this._copy.uvs.z = 1;
  35950. this._copy.uvs.w = 1;
  35951. this._copy.color = null;
  35952. };
  35953. // _meshBuilder : inserts the shape model in the global SPS mesh
  35954. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  35955. var i;
  35956. var u = 0;
  35957. var c = 0;
  35958. var n = 0;
  35959. this._resetCopy();
  35960. if (options && options.positionFunction) {
  35961. options.positionFunction(this._copy, idx, idxInShape);
  35962. this._mustUnrotateFixedNormals = true;
  35963. }
  35964. if (this._copy.rotationQuaternion) {
  35965. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  35966. }
  35967. else {
  35968. this._yaw = this._copy.rotation.y;
  35969. this._pitch = this._copy.rotation.x;
  35970. this._roll = this._copy.rotation.z;
  35971. this._quaternionRotationYPR();
  35972. }
  35973. this._quaternionToRotationMatrix();
  35974. for (i = 0; i < shape.length; i++) {
  35975. this._vertex.x = shape[i].x;
  35976. this._vertex.y = shape[i].y;
  35977. this._vertex.z = shape[i].z;
  35978. if (options && options.vertexFunction) {
  35979. options.vertexFunction(this._copy, this._vertex, i);
  35980. }
  35981. this._vertex.x *= this._copy.scaling.x;
  35982. this._vertex.y *= this._copy.scaling.y;
  35983. this._vertex.z *= this._copy.scaling.z;
  35984. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35985. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  35986. if (meshUV) {
  35987. 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);
  35988. u += 2;
  35989. }
  35990. if (this._copy.color) {
  35991. this._color = this._copy.color;
  35992. }
  35993. else if (meshCol && meshCol[c] !== undefined) {
  35994. this._color.r = meshCol[c];
  35995. this._color.g = meshCol[c + 1];
  35996. this._color.b = meshCol[c + 2];
  35997. this._color.a = meshCol[c + 3];
  35998. }
  35999. else {
  36000. this._color.r = 1;
  36001. this._color.g = 1;
  36002. this._color.b = 1;
  36003. this._color.a = 1;
  36004. }
  36005. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36006. c += 4;
  36007. if (!this.recomputeNormals && meshNor) {
  36008. this._normal.x = meshNor[n];
  36009. this._normal.y = meshNor[n + 1];
  36010. this._normal.z = meshNor[n + 2];
  36011. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  36012. normals.push(this._normal.x, this._normal.y, this._normal.z);
  36013. n += 3;
  36014. }
  36015. }
  36016. for (i = 0; i < meshInd.length; i++) {
  36017. indices.push(p + meshInd[i]);
  36018. }
  36019. if (this._pickable) {
  36020. var nbfaces = meshInd.length / 3;
  36021. for (i = 0; i < nbfaces; i++) {
  36022. this.pickedParticles.push({ idx: idx, faceId: i });
  36023. }
  36024. }
  36025. return this._copy;
  36026. };
  36027. // returns a shape array from positions array
  36028. SolidParticleSystem.prototype._posToShape = function (positions) {
  36029. var shape = [];
  36030. for (var i = 0; i < positions.length; i += 3) {
  36031. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36032. }
  36033. return shape;
  36034. };
  36035. // returns a shapeUV array from a Vector4 uvs
  36036. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36037. var shapeUV = [];
  36038. if (uvs) {
  36039. for (var i = 0; i < uvs.length; i++)
  36040. shapeUV.push(uvs[i]);
  36041. }
  36042. return shapeUV;
  36043. };
  36044. // adds a new particle object in the particles array
  36045. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  36046. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  36047. this.particles.push(sp);
  36048. return sp;
  36049. };
  36050. /**
  36051. * Adds some particles to the SPS from the model shape. Returns the shape id.
  36052. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  36053. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  36054. * `nb` (positive integer) the number of particles to be created from this model
  36055. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  36056. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  36057. */
  36058. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36059. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36060. var meshInd = mesh.getIndices();
  36061. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36062. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36063. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36064. var bbInfo;
  36065. if (this._particlesIntersect) {
  36066. bbInfo = mesh.getBoundingInfo();
  36067. }
  36068. var shape = this._posToShape(meshPos);
  36069. var shapeUV = this._uvsToShapeUV(meshUV);
  36070. var posfunc = options ? options.positionFunction : null;
  36071. var vtxfunc = options ? options.vertexFunction : null;
  36072. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36073. // particles
  36074. var sp;
  36075. var currentCopy;
  36076. var idx = this.nbParticles;
  36077. for (var i = 0; i < nb; i++) {
  36078. var currentPos = this._positions.length;
  36079. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  36080. if (this._updatable) {
  36081. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  36082. sp.position.copyFrom(currentCopy.position);
  36083. sp.rotation.copyFrom(currentCopy.rotation);
  36084. if (currentCopy.rotationQuaternion) {
  36085. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  36086. }
  36087. if (currentCopy.color) {
  36088. sp.color.copyFrom(currentCopy.color);
  36089. }
  36090. sp.scaling.copyFrom(currentCopy.scaling);
  36091. sp.uvs.copyFrom(currentCopy.uvs);
  36092. }
  36093. this._index += shape.length;
  36094. idx++;
  36095. }
  36096. this.nbParticles += nb;
  36097. this._shapeCounter++;
  36098. return this._shapeCounter - 1;
  36099. };
  36100. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36101. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36102. this._resetCopy();
  36103. if (particle._model._positionFunction) {
  36104. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36105. }
  36106. if (this._copy.rotationQuaternion) {
  36107. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  36108. }
  36109. else {
  36110. this._yaw = this._copy.rotation.y;
  36111. this._pitch = this._copy.rotation.x;
  36112. this._roll = this._copy.rotation.z;
  36113. this._quaternionRotationYPR();
  36114. }
  36115. this._quaternionToRotationMatrix();
  36116. this._shape = particle._model._shape;
  36117. for (var pt = 0; pt < this._shape.length; pt++) {
  36118. this._vertex.x = this._shape[pt].x;
  36119. this._vertex.y = this._shape[pt].y;
  36120. this._vertex.z = this._shape[pt].z;
  36121. if (particle._model._vertexFunction) {
  36122. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36123. }
  36124. this._vertex.x *= this._copy.scaling.x;
  36125. this._vertex.y *= this._copy.scaling.y;
  36126. this._vertex.z *= this._copy.scaling.z;
  36127. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36128. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36129. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36130. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36131. }
  36132. particle.position.x = 0.0;
  36133. particle.position.y = 0.0;
  36134. particle.position.z = 0.0;
  36135. particle.rotation.x = 0.0;
  36136. particle.rotation.y = 0.0;
  36137. particle.rotation.z = 0.0;
  36138. particle.rotationQuaternion = null;
  36139. particle.scaling.x = 1.0;
  36140. particle.scaling.y = 1.0;
  36141. particle.scaling.z = 1.0;
  36142. };
  36143. /**
  36144. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  36145. * Returns the SPS.
  36146. */
  36147. SolidParticleSystem.prototype.rebuildMesh = function () {
  36148. for (var p = 0; p < this.particles.length; p++) {
  36149. this._rebuildParticle(this.particles[p]);
  36150. }
  36151. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36152. return this;
  36153. };
  36154. /**
  36155. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  36156. * This method calls `updateParticle()` for each particle of the SPS.
  36157. * For an animated SPS, it is usually called within the render loop.
  36158. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  36159. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  36160. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  36161. * Returns the SPS.
  36162. */
  36163. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36164. if (start === void 0) { start = 0; }
  36165. if (end === void 0) { end = this.nbParticles - 1; }
  36166. if (update === void 0) { update = true; }
  36167. if (!this._updatable) {
  36168. return;
  36169. }
  36170. // custom beforeUpdate
  36171. this.beforeUpdateParticles(start, end, update);
  36172. this._cam_axisX.x = 1.0;
  36173. this._cam_axisX.y = 0.0;
  36174. this._cam_axisX.z = 0.0;
  36175. this._cam_axisY.x = 0.0;
  36176. this._cam_axisY.y = 1.0;
  36177. this._cam_axisY.z = 0.0;
  36178. this._cam_axisZ.x = 0.0;
  36179. this._cam_axisZ.y = 0.0;
  36180. this._cam_axisZ.z = 1.0;
  36181. // if the particles will always face the camera
  36182. if (this.billboard) {
  36183. this.mesh.computeWorldMatrix(true);
  36184. // compute the camera position and un-rotate it by the current mesh rotation
  36185. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  36186. this._quaternionToRotationMatrix();
  36187. this._rotMatrix.invertToRef(this._invertMatrix);
  36188. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  36189. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  36190. this._cam_axisZ.normalize();
  36191. // same for camera up vector extracted from the cam view matrix
  36192. var view = this._camera.getViewMatrix(true);
  36193. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  36194. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  36195. this._cam_axisY.normalize();
  36196. this._cam_axisX.normalize();
  36197. }
  36198. }
  36199. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36200. var idx = 0; // current position index in the global array positions32
  36201. var index = 0; // position start index in the global array positions32 of the current particle
  36202. var colidx = 0; // current color index in the global array colors32
  36203. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  36204. var uvidx = 0; // current uv index in the global array uvs32
  36205. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  36206. var pt = 0; // current index in the particle model shape
  36207. if (this.mesh.isFacetDataEnabled) {
  36208. this._computeBoundingBox = true;
  36209. }
  36210. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  36211. if (this._computeBoundingBox) {
  36212. if (start == 0 && end == this.nbParticles - 1) {
  36213. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  36214. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  36215. }
  36216. else {
  36217. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  36218. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  36219. }
  36220. }
  36221. // particle loop
  36222. index = this.particles[start]._pos;
  36223. var vpos = (index / 3) | 0;
  36224. colorIndex = vpos * 4;
  36225. uvIndex = vpos * 2;
  36226. for (var p = start; p <= end; p++) {
  36227. this._particle = this.particles[p];
  36228. this._shape = this._particle._model._shape;
  36229. this._shapeUV = this._particle._model._shapeUV;
  36230. // call to custom user function to update the particle properties
  36231. this.updateParticle(this._particle);
  36232. if (this._particle.isVisible) {
  36233. // particle rotation matrix
  36234. if (this.billboard) {
  36235. this._particle.rotation.x = 0.0;
  36236. this._particle.rotation.y = 0.0;
  36237. }
  36238. if (this._computeParticleRotation || this.billboard) {
  36239. if (this._particle.rotationQuaternion) {
  36240. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  36241. }
  36242. else {
  36243. this._yaw = this._particle.rotation.y;
  36244. this._pitch = this._particle.rotation.x;
  36245. this._roll = this._particle.rotation.z;
  36246. this._quaternionRotationYPR();
  36247. }
  36248. this._quaternionToRotationMatrix();
  36249. }
  36250. // particle vertex loop
  36251. for (pt = 0; pt < this._shape.length; pt++) {
  36252. idx = index + pt * 3;
  36253. colidx = colorIndex + pt * 4;
  36254. uvidx = uvIndex + pt * 2;
  36255. this._vertex.x = this._shape[pt].x;
  36256. this._vertex.y = this._shape[pt].y;
  36257. this._vertex.z = this._shape[pt].z;
  36258. if (this._computeParticleVertex) {
  36259. this.updateParticleVertex(this._particle, this._vertex, pt);
  36260. }
  36261. // positions
  36262. this._vertex.x *= this._particle.scaling.x;
  36263. this._vertex.y *= this._particle.scaling.y;
  36264. this._vertex.z *= this._particle.scaling.z;
  36265. 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];
  36266. 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;
  36267. 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;
  36268. 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;
  36269. 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;
  36270. 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;
  36271. 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;
  36272. if (this._computeBoundingBox) {
  36273. if (this._positions32[idx] < this._minimum.x) {
  36274. this._minimum.x = this._positions32[idx];
  36275. }
  36276. if (this._positions32[idx] > this._maximum.x) {
  36277. this._maximum.x = this._positions32[idx];
  36278. }
  36279. if (this._positions32[idx + 1] < this._minimum.y) {
  36280. this._minimum.y = this._positions32[idx + 1];
  36281. }
  36282. if (this._positions32[idx + 1] > this._maximum.y) {
  36283. this._maximum.y = this._positions32[idx + 1];
  36284. }
  36285. if (this._positions32[idx + 2] < this._minimum.z) {
  36286. this._minimum.z = this._positions32[idx + 2];
  36287. }
  36288. if (this._positions32[idx + 2] > this._maximum.z) {
  36289. this._maximum.z = this._positions32[idx + 2];
  36290. }
  36291. }
  36292. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  36293. if (!this._computeParticleVertex) {
  36294. this._normal.x = this._fixedNormal32[idx];
  36295. this._normal.y = this._fixedNormal32[idx + 1];
  36296. this._normal.z = this._fixedNormal32[idx + 2];
  36297. 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]);
  36298. 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]);
  36299. 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]);
  36300. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36301. 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;
  36302. 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;
  36303. }
  36304. if (this._computeParticleColor) {
  36305. this._colors32[colidx] = this._particle.color.r;
  36306. this._colors32[colidx + 1] = this._particle.color.g;
  36307. this._colors32[colidx + 2] = this._particle.color.b;
  36308. this._colors32[colidx + 3] = this._particle.color.a;
  36309. }
  36310. if (this._computeParticleTexture) {
  36311. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36312. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36313. }
  36314. }
  36315. }
  36316. else {
  36317. for (pt = 0; pt < this._shape.length; pt++) {
  36318. idx = index + pt * 3;
  36319. colidx = colorIndex + pt * 4;
  36320. uvidx = uvIndex + pt * 2;
  36321. this._positions32[idx] = this._camera.position.x;
  36322. this._positions32[idx + 1] = this._camera.position.y;
  36323. this._positions32[idx + 2] = this._camera.position.z;
  36324. this._normals32[idx] = 0.0;
  36325. this._normals32[idx + 1] = 0.0;
  36326. this._normals32[idx + 2] = 0.0;
  36327. if (this._computeParticleColor) {
  36328. this._colors32[colidx] = this._particle.color.r;
  36329. this._colors32[colidx + 1] = this._particle.color.g;
  36330. this._colors32[colidx + 2] = this._particle.color.b;
  36331. this._colors32[colidx + 3] = this._particle.color.a;
  36332. }
  36333. if (this._computeParticleTexture) {
  36334. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36335. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36336. }
  36337. }
  36338. }
  36339. // if the particle intersections must be computed : update the bbInfo
  36340. if (this._particlesIntersect) {
  36341. var bInfo = this._particle._boundingInfo;
  36342. var bBox = bInfo.boundingBox;
  36343. var bSphere = bInfo.boundingSphere;
  36344. if (!this._bSphereOnly) {
  36345. // place, scale and rotate the particle bbox within the SPS local system, then update it
  36346. for (var b = 0; b < bBox.vectors.length; b++) {
  36347. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  36348. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  36349. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  36350. 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];
  36351. 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;
  36352. 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;
  36353. 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;
  36354. 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;
  36355. 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;
  36356. 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;
  36357. }
  36358. bBox._update(this.mesh._worldMatrix);
  36359. }
  36360. // place and scale the particle bouding sphere in the SPS local system, then update it
  36361. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  36362. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  36363. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  36364. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  36365. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  36366. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  36367. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  36368. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  36369. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  36370. 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));
  36371. bSphere._update(this.mesh._worldMatrix);
  36372. }
  36373. // increment indexes for the next particle
  36374. index = idx + 3;
  36375. colorIndex = colidx + 4;
  36376. uvIndex = uvidx + 2;
  36377. }
  36378. // if the VBO must be updated
  36379. if (update) {
  36380. if (this._computeParticleColor) {
  36381. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36382. }
  36383. if (this._computeParticleTexture) {
  36384. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36385. }
  36386. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36387. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  36388. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  36389. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  36390. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  36391. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  36392. for (var i = 0; i < this._normals32.length; i++) {
  36393. this._fixedNormal32[i] = this._normals32[i];
  36394. }
  36395. }
  36396. if (!this.mesh.areNormalsFrozen) {
  36397. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36398. }
  36399. }
  36400. }
  36401. if (this._computeBoundingBox) {
  36402. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  36403. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  36404. }
  36405. this.afterUpdateParticles(start, end, update);
  36406. return this;
  36407. };
  36408. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36409. this._halfroll = this._roll * 0.5;
  36410. this._halfpitch = this._pitch * 0.5;
  36411. this._halfyaw = this._yaw * 0.5;
  36412. this._sinRoll = Math.sin(this._halfroll);
  36413. this._cosRoll = Math.cos(this._halfroll);
  36414. this._sinPitch = Math.sin(this._halfpitch);
  36415. this._cosPitch = Math.cos(this._halfpitch);
  36416. this._sinYaw = Math.sin(this._halfyaw);
  36417. this._cosYaw = Math.cos(this._halfyaw);
  36418. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36419. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36420. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36421. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36422. };
  36423. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36424. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36425. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36426. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36427. this._rotMatrix.m[3] = 0;
  36428. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36429. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36430. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36431. this._rotMatrix.m[7] = 0;
  36432. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36433. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36434. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36435. this._rotMatrix.m[11] = 0;
  36436. this._rotMatrix.m[12] = 0;
  36437. this._rotMatrix.m[13] = 0;
  36438. this._rotMatrix.m[14] = 0;
  36439. this._rotMatrix.m[15] = 1.0;
  36440. };
  36441. /**
  36442. * Disposes the SPS.
  36443. * Returns nothing.
  36444. */
  36445. SolidParticleSystem.prototype.dispose = function () {
  36446. this.mesh.dispose();
  36447. this.vars = null;
  36448. // drop references to internal big arrays for the GC
  36449. this._positions = null;
  36450. this._indices = null;
  36451. this._normals = null;
  36452. this._uvs = null;
  36453. this._colors = null;
  36454. this._positions32 = null;
  36455. this._normals32 = null;
  36456. this._fixedNormal32 = null;
  36457. this._uvs32 = null;
  36458. this._colors32 = null;
  36459. this.pickedParticles = null;
  36460. };
  36461. /**
  36462. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  36463. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  36464. * Returns the SPS.
  36465. */
  36466. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36467. if (!this._isVisibilityBoxLocked) {
  36468. this.mesh.refreshBoundingInfo();
  36469. }
  36470. return this;
  36471. };
  36472. /**
  36473. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  36474. * @param size the size (float) of the visibility box
  36475. * note : this doesn't lock the SPS mesh bounding box.
  36476. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  36477. */
  36478. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  36479. var vis = size / 2;
  36480. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  36481. };
  36482. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36483. // getter and setter
  36484. get: function () {
  36485. return this._alwaysVisible;
  36486. },
  36487. /**
  36488. * Sets the SPS as always visible or not
  36489. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  36490. */
  36491. set: function (val) {
  36492. this._alwaysVisible = val;
  36493. this.mesh.alwaysSelectAsActiveMesh = val;
  36494. },
  36495. enumerable: true,
  36496. configurable: true
  36497. });
  36498. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  36499. get: function () {
  36500. return this._isVisibilityBoxLocked;
  36501. },
  36502. /**
  36503. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  36504. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  36505. */
  36506. set: function (val) {
  36507. this._isVisibilityBoxLocked = val;
  36508. this.mesh.getBoundingInfo().isLocked = val;
  36509. },
  36510. enumerable: true,
  36511. configurable: true
  36512. });
  36513. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36514. // getters
  36515. get: function () {
  36516. return this._computeParticleRotation;
  36517. },
  36518. // Optimizer setters
  36519. /**
  36520. * Tells to `setParticles()` to compute the particle rotations or not.
  36521. * Default value : true. The SPS is faster when it's set to false.
  36522. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  36523. */
  36524. set: function (val) {
  36525. this._computeParticleRotation = val;
  36526. },
  36527. enumerable: true,
  36528. configurable: true
  36529. });
  36530. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36531. get: function () {
  36532. return this._computeParticleColor;
  36533. },
  36534. /**
  36535. * Tells to `setParticles()` to compute the particle colors or not.
  36536. * Default value : true. The SPS is faster when it's set to false.
  36537. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  36538. */
  36539. set: function (val) {
  36540. this._computeParticleColor = val;
  36541. },
  36542. enumerable: true,
  36543. configurable: true
  36544. });
  36545. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36546. get: function () {
  36547. return this._computeParticleTexture;
  36548. },
  36549. /**
  36550. * Tells to `setParticles()` to compute the particle textures or not.
  36551. * Default value : true. The SPS is faster when it's set to false.
  36552. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  36553. */
  36554. set: function (val) {
  36555. this._computeParticleTexture = val;
  36556. },
  36557. enumerable: true,
  36558. configurable: true
  36559. });
  36560. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36561. get: function () {
  36562. return this._computeParticleVertex;
  36563. },
  36564. /**
  36565. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  36566. * Default value : false. The SPS is faster when it's set to false.
  36567. * Note : the particle custom vertex positions aren't stored values.
  36568. */
  36569. set: function (val) {
  36570. this._computeParticleVertex = val;
  36571. },
  36572. enumerable: true,
  36573. configurable: true
  36574. });
  36575. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  36576. get: function () {
  36577. return this._computeBoundingBox;
  36578. },
  36579. /**
  36580. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  36581. */
  36582. set: function (val) {
  36583. this._computeBoundingBox = val;
  36584. },
  36585. enumerable: true,
  36586. configurable: true
  36587. });
  36588. // =======================================================================
  36589. // Particle behavior logic
  36590. // these following methods may be overwritten by the user to fit his needs
  36591. /**
  36592. * This function does nothing. It may be overwritten to set all the particle first values.
  36593. * The SPS doesn't call this function, you may have to call it by your own.
  36594. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  36595. */
  36596. SolidParticleSystem.prototype.initParticles = function () {
  36597. };
  36598. /**
  36599. * This function does nothing. It may be overwritten to recycle a particle.
  36600. * The SPS doesn't call this function, you may have to call it by your own.
  36601. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  36602. */
  36603. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36604. return particle;
  36605. };
  36606. /**
  36607. * Updates a particle : this function should be overwritten by the user.
  36608. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  36609. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  36610. * ex : just set a particle position or velocity and recycle conditions
  36611. */
  36612. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36613. return particle;
  36614. };
  36615. /**
  36616. * Updates a vertex of a particle : it can be overwritten by the user.
  36617. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  36618. * @param particle the current particle
  36619. * @param vertex the current index of the current particle
  36620. * @param pt the index of the current vertex in the particle shape
  36621. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  36622. * ex : just set a vertex particle position
  36623. */
  36624. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36625. return vertex;
  36626. };
  36627. /**
  36628. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  36629. * This does nothing and may be overwritten by the user.
  36630. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  36631. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  36632. * @param update the boolean update value actually passed to setParticles()
  36633. */
  36634. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36635. };
  36636. /**
  36637. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  36638. * This will be passed three parameters.
  36639. * This does nothing and may be overwritten by the user.
  36640. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  36641. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  36642. * @param update the boolean update value actually passed to setParticles()
  36643. */
  36644. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36645. };
  36646. return SolidParticleSystem;
  36647. }());
  36648. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36649. })(BABYLON || (BABYLON = {}));
  36650. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  36651. /// <reference path="babylon.mesh.ts" />
  36652. var BABYLON;
  36653. (function (BABYLON) {
  36654. var GroundMesh = (function (_super) {
  36655. __extends(GroundMesh, _super);
  36656. function GroundMesh(name, scene) {
  36657. var _this = _super.call(this, name, scene) || this;
  36658. _this.generateOctree = false;
  36659. _this._worldInverse = new BABYLON.Matrix();
  36660. return _this;
  36661. }
  36662. GroundMesh.prototype.getClassName = function () {
  36663. return "GroundMesh";
  36664. };
  36665. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  36666. get: function () {
  36667. return Math.min(this._subdivisionsX, this._subdivisionsY);
  36668. },
  36669. enumerable: true,
  36670. configurable: true
  36671. });
  36672. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  36673. get: function () {
  36674. return this._subdivisionsX;
  36675. },
  36676. enumerable: true,
  36677. configurable: true
  36678. });
  36679. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  36680. get: function () {
  36681. return this._subdivisionsY;
  36682. },
  36683. enumerable: true,
  36684. configurable: true
  36685. });
  36686. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  36687. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  36688. this._subdivisionsX = chunksCount;
  36689. this._subdivisionsY = chunksCount;
  36690. this.subdivide(chunksCount);
  36691. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  36692. };
  36693. /**
  36694. * Returns a height (y) value in the Worl system :
  36695. * the ground altitude at the coordinates (x, z) expressed in the World system.
  36696. * Returns the ground y position if (x, z) are outside the ground surface.
  36697. */
  36698. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  36699. var world = this.getWorldMatrix();
  36700. var invMat = BABYLON.Tmp.Matrix[5];
  36701. world.invertToRef(invMat);
  36702. var tmpVect = BABYLON.Tmp.Vector3[8];
  36703. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  36704. x = tmpVect.x;
  36705. z = tmpVect.z;
  36706. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  36707. return this.position.y;
  36708. }
  36709. if (!this._heightQuads || this._heightQuads.length == 0) {
  36710. this._initHeightQuads();
  36711. this._computeHeightQuads();
  36712. }
  36713. var facet = this._getFacetAt(x, z);
  36714. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  36715. // return y in the World system
  36716. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  36717. return tmpVect.y;
  36718. };
  36719. /**
  36720. * Returns a normalized vector (Vector3) orthogonal to the ground
  36721. * at the ground coordinates (x, z) expressed in the World system.
  36722. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  36723. */
  36724. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  36725. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  36726. this.getNormalAtCoordinatesToRef(x, z, normal);
  36727. return normal;
  36728. };
  36729. /**
  36730. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  36731. * at the ground coordinates (x, z) expressed in the World system.
  36732. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  36733. * Returns the GroundMesh.
  36734. */
  36735. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  36736. var world = this.getWorldMatrix();
  36737. var tmpMat = BABYLON.Tmp.Matrix[5];
  36738. world.invertToRef(tmpMat);
  36739. var tmpVect = BABYLON.Tmp.Vector3[8];
  36740. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  36741. x = tmpVect.x;
  36742. z = tmpVect.z;
  36743. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  36744. return this;
  36745. }
  36746. if (!this._heightQuads || this._heightQuads.length == 0) {
  36747. this._initHeightQuads();
  36748. this._computeHeightQuads();
  36749. }
  36750. var facet = this._getFacetAt(x, z);
  36751. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  36752. return this;
  36753. };
  36754. /**
  36755. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  36756. * if the ground has been updated.
  36757. * This can be used in the render loop.
  36758. * Returns the GroundMesh.
  36759. */
  36760. GroundMesh.prototype.updateCoordinateHeights = function () {
  36761. if (!this._heightQuads || this._heightQuads.length == 0) {
  36762. this._initHeightQuads();
  36763. }
  36764. this._computeHeightQuads();
  36765. return this;
  36766. };
  36767. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  36768. GroundMesh.prototype._getFacetAt = function (x, z) {
  36769. // retrieve col and row from x, z coordinates in the ground local system
  36770. var subdivisionsX = this._subdivisionsX;
  36771. var subdivisionsY = this._subdivisionsY;
  36772. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  36773. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  36774. var quad = this._heightQuads[row * this._subdivisionsX + col];
  36775. var facet;
  36776. if (z < quad.slope.x * x + quad.slope.y) {
  36777. facet = quad.facet1;
  36778. }
  36779. else {
  36780. facet = quad.facet2;
  36781. }
  36782. return facet;
  36783. };
  36784. // Creates and populates the heightMap array with "facet" elements :
  36785. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  36786. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36787. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36788. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36789. // Returns the GroundMesh.
  36790. GroundMesh.prototype._initHeightQuads = function () {
  36791. var subdivisionsX = this._subdivisionsX;
  36792. var subdivisionsY = this._subdivisionsY;
  36793. this._heightQuads = new Array();
  36794. for (var row = 0; row < subdivisionsY; row++) {
  36795. for (var col = 0; col < subdivisionsX; col++) {
  36796. 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) };
  36797. this._heightQuads[row * subdivisionsX + col] = quad;
  36798. }
  36799. }
  36800. return this;
  36801. };
  36802. // Compute each quad element values and update the the heightMap array :
  36803. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36804. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36805. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36806. // Returns the GroundMesh.
  36807. GroundMesh.prototype._computeHeightQuads = function () {
  36808. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36809. var v1 = BABYLON.Tmp.Vector3[3];
  36810. var v2 = BABYLON.Tmp.Vector3[2];
  36811. var v3 = BABYLON.Tmp.Vector3[1];
  36812. var v4 = BABYLON.Tmp.Vector3[0];
  36813. var v1v2 = BABYLON.Tmp.Vector3[4];
  36814. var v1v3 = BABYLON.Tmp.Vector3[5];
  36815. var v1v4 = BABYLON.Tmp.Vector3[6];
  36816. var norm1 = BABYLON.Tmp.Vector3[7];
  36817. var norm2 = BABYLON.Tmp.Vector3[8];
  36818. var i = 0;
  36819. var j = 0;
  36820. var k = 0;
  36821. var cd = 0; // 2D slope coefficient : z = cd * x + h
  36822. var h = 0;
  36823. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  36824. var d2 = 0;
  36825. var subdivisionsX = this._subdivisionsX;
  36826. var subdivisionsY = this._subdivisionsY;
  36827. for (var row = 0; row < subdivisionsY; row++) {
  36828. for (var col = 0; col < subdivisionsX; col++) {
  36829. i = col * 3;
  36830. j = row * (subdivisionsX + 1) * 3;
  36831. k = (row + 1) * (subdivisionsX + 1) * 3;
  36832. v1.x = positions[j + i];
  36833. v1.y = positions[j + i + 1];
  36834. v1.z = positions[j + i + 2];
  36835. v2.x = positions[j + i + 3];
  36836. v2.y = positions[j + i + 4];
  36837. v2.z = positions[j + i + 5];
  36838. v3.x = positions[k + i];
  36839. v3.y = positions[k + i + 1];
  36840. v3.z = positions[k + i + 2];
  36841. v4.x = positions[k + i + 3];
  36842. v4.y = positions[k + i + 4];
  36843. v4.z = positions[k + i + 5];
  36844. // 2D slope V1V4
  36845. cd = (v4.z - v1.z) / (v4.x - v1.x);
  36846. h = v1.z - cd * v1.x; // v1 belongs to the slope
  36847. // facet equations :
  36848. // we compute each facet normal vector
  36849. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  36850. // we compute the value d by applying the equation to v1 which belongs to the plane
  36851. // then we store the facet equation in a Vector4
  36852. v2.subtractToRef(v1, v1v2);
  36853. v3.subtractToRef(v1, v1v3);
  36854. v4.subtractToRef(v1, v1v4);
  36855. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  36856. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  36857. norm1.normalize();
  36858. norm2.normalize();
  36859. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  36860. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  36861. var quad = this._heightQuads[row * subdivisionsX + col];
  36862. quad.slope.copyFromFloats(cd, h);
  36863. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  36864. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  36865. }
  36866. }
  36867. return this;
  36868. };
  36869. GroundMesh.prototype.serialize = function (serializationObject) {
  36870. _super.prototype.serialize.call(this, serializationObject);
  36871. serializationObject.subdivisionsX = this._subdivisionsX;
  36872. serializationObject.subdivisionsY = this._subdivisionsY;
  36873. serializationObject.minX = this._minX;
  36874. serializationObject.maxX = this._maxX;
  36875. serializationObject.minZ = this._minZ;
  36876. serializationObject.maxZ = this._maxZ;
  36877. serializationObject.width = this._width;
  36878. serializationObject.height = this._height;
  36879. };
  36880. GroundMesh.Parse = function (parsedMesh, scene) {
  36881. var result = new GroundMesh(parsedMesh.name, scene);
  36882. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  36883. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  36884. result._minX = parsedMesh.minX;
  36885. result._maxX = parsedMesh.maxX;
  36886. result._minZ = parsedMesh.minZ;
  36887. result._maxZ = parsedMesh.maxZ;
  36888. result._width = parsedMesh.width;
  36889. result._height = parsedMesh.height;
  36890. return result;
  36891. };
  36892. return GroundMesh;
  36893. }(BABYLON.Mesh));
  36894. BABYLON.GroundMesh = GroundMesh;
  36895. })(BABYLON || (BABYLON = {}));
  36896. //# sourceMappingURL=babylon.groundMesh.js.map
  36897. var BABYLON;
  36898. (function (BABYLON) {
  36899. /**
  36900. * Creates an instance based on a source mesh.
  36901. */
  36902. var InstancedMesh = (function (_super) {
  36903. __extends(InstancedMesh, _super);
  36904. function InstancedMesh(name, source) {
  36905. var _this = _super.call(this, name, source.getScene()) || this;
  36906. source.instances.push(_this);
  36907. _this._sourceMesh = source;
  36908. _this.position.copyFrom(source.position);
  36909. _this.rotation.copyFrom(source.rotation);
  36910. _this.scaling.copyFrom(source.scaling);
  36911. if (source.rotationQuaternion) {
  36912. _this.rotationQuaternion = source.rotationQuaternion.clone();
  36913. }
  36914. _this.infiniteDistance = source.infiniteDistance;
  36915. _this.setPivotMatrix(source.getPivotMatrix());
  36916. _this.refreshBoundingInfo();
  36917. _this._syncSubMeshes();
  36918. return _this;
  36919. }
  36920. /**
  36921. * Returns the string "InstancedMesh".
  36922. */
  36923. InstancedMesh.prototype.getClassName = function () {
  36924. return "InstancedMesh";
  36925. };
  36926. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  36927. // Methods
  36928. get: function () {
  36929. return this._sourceMesh.receiveShadows;
  36930. },
  36931. enumerable: true,
  36932. configurable: true
  36933. });
  36934. Object.defineProperty(InstancedMesh.prototype, "material", {
  36935. get: function () {
  36936. return this._sourceMesh.material;
  36937. },
  36938. enumerable: true,
  36939. configurable: true
  36940. });
  36941. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  36942. get: function () {
  36943. return this._sourceMesh.visibility;
  36944. },
  36945. enumerable: true,
  36946. configurable: true
  36947. });
  36948. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  36949. get: function () {
  36950. return this._sourceMesh.skeleton;
  36951. },
  36952. enumerable: true,
  36953. configurable: true
  36954. });
  36955. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  36956. get: function () {
  36957. return this._sourceMesh.renderingGroupId;
  36958. },
  36959. enumerable: true,
  36960. configurable: true
  36961. });
  36962. /**
  36963. * Returns the total number of vertices (integer).
  36964. */
  36965. InstancedMesh.prototype.getTotalVertices = function () {
  36966. return this._sourceMesh.getTotalVertices();
  36967. };
  36968. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  36969. get: function () {
  36970. return this._sourceMesh;
  36971. },
  36972. enumerable: true,
  36973. configurable: true
  36974. });
  36975. /**
  36976. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  36977. */
  36978. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  36979. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  36980. };
  36981. /**
  36982. * Sets the vertex data of the mesh geometry for the requested `kind`.
  36983. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  36984. * The `data` are either a numeric array either a Float32Array.
  36985. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  36986. * 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).
  36987. * Note that a new underlying VertexBuffer object is created each call.
  36988. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  36989. *
  36990. * Possible `kind` values :
  36991. * - BABYLON.VertexBuffer.PositionKind
  36992. * - BABYLON.VertexBuffer.UVKind
  36993. * - BABYLON.VertexBuffer.UV2Kind
  36994. * - BABYLON.VertexBuffer.UV3Kind
  36995. * - BABYLON.VertexBuffer.UV4Kind
  36996. * - BABYLON.VertexBuffer.UV5Kind
  36997. * - BABYLON.VertexBuffer.UV6Kind
  36998. * - BABYLON.VertexBuffer.ColorKind
  36999. * - BABYLON.VertexBuffer.MatricesIndicesKind
  37000. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  37001. * - BABYLON.VertexBuffer.MatricesWeightsKind
  37002. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  37003. *
  37004. * Returns the Mesh.
  37005. */
  37006. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37007. if (this.sourceMesh) {
  37008. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  37009. }
  37010. return this.sourceMesh;
  37011. };
  37012. /**
  37013. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  37014. * If the mesh has no geometry, it is simply returned as it is.
  37015. * The `data` are either a numeric array either a Float32Array.
  37016. * No new underlying VertexBuffer object is created.
  37017. * 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.
  37018. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  37019. *
  37020. * Possible `kind` values :
  37021. * - BABYLON.VertexBuffer.PositionKind
  37022. * - BABYLON.VertexBuffer.UVKind
  37023. * - BABYLON.VertexBuffer.UV2Kind
  37024. * - BABYLON.VertexBuffer.UV3Kind
  37025. * - BABYLON.VertexBuffer.UV4Kind
  37026. * - BABYLON.VertexBuffer.UV5Kind
  37027. * - BABYLON.VertexBuffer.UV6Kind
  37028. * - BABYLON.VertexBuffer.ColorKind
  37029. * - BABYLON.VertexBuffer.MatricesIndicesKind
  37030. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  37031. * - BABYLON.VertexBuffer.MatricesWeightsKind
  37032. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  37033. *
  37034. * Returns the Mesh.
  37035. */
  37036. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  37037. if (this.sourceMesh) {
  37038. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  37039. }
  37040. return this.sourceMesh;
  37041. };
  37042. /**
  37043. * Sets the mesh indices.
  37044. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  37045. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  37046. * This method creates a new index buffer each call.
  37047. * Returns the Mesh.
  37048. */
  37049. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  37050. if (this.sourceMesh) {
  37051. this.sourceMesh.setIndices(indices, totalVertices);
  37052. }
  37053. return this.sourceMesh;
  37054. };
  37055. /**
  37056. * Boolean : True if the mesh owns the requested kind of data.
  37057. */
  37058. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  37059. return this._sourceMesh.isVerticesDataPresent(kind);
  37060. };
  37061. /**
  37062. * Returns an array of indices (IndicesArray).
  37063. */
  37064. InstancedMesh.prototype.getIndices = function () {
  37065. return this._sourceMesh.getIndices();
  37066. };
  37067. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  37068. get: function () {
  37069. return this._sourceMesh._positions;
  37070. },
  37071. enumerable: true,
  37072. configurable: true
  37073. });
  37074. /**
  37075. * Sets a new updated BoundingInfo to the mesh.
  37076. * Returns the mesh.
  37077. */
  37078. InstancedMesh.prototype.refreshBoundingInfo = function () {
  37079. var meshBB = this._sourceMesh.getBoundingInfo();
  37080. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  37081. this._updateBoundingInfo();
  37082. return this;
  37083. };
  37084. InstancedMesh.prototype._preActivate = function () {
  37085. if (this._currentLOD) {
  37086. this._currentLOD._preActivate();
  37087. }
  37088. return this;
  37089. };
  37090. InstancedMesh.prototype._activate = function (renderId) {
  37091. if (this._currentLOD) {
  37092. this._currentLOD._registerInstanceForRenderId(this, renderId);
  37093. }
  37094. return this;
  37095. };
  37096. /**
  37097. * Returns the current associated LOD AbstractMesh.
  37098. */
  37099. InstancedMesh.prototype.getLOD = function (camera) {
  37100. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  37101. if (this._currentLOD === this.sourceMesh) {
  37102. return this;
  37103. }
  37104. return this._currentLOD;
  37105. };
  37106. InstancedMesh.prototype._syncSubMeshes = function () {
  37107. this.releaseSubMeshes();
  37108. if (this._sourceMesh.subMeshes) {
  37109. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  37110. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  37111. }
  37112. }
  37113. return this;
  37114. };
  37115. InstancedMesh.prototype._generatePointsArray = function () {
  37116. return this._sourceMesh._generatePointsArray();
  37117. };
  37118. /**
  37119. * Creates a new InstancedMesh from the current mesh.
  37120. * - name (string) : the cloned mesh name
  37121. * - newParent (optional Node) : the optional Node to parent the clone to.
  37122. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  37123. *
  37124. * Returns the clone.
  37125. */
  37126. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37127. var result = this._sourceMesh.createInstance(name);
  37128. // Deep copy
  37129. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  37130. // Bounding info
  37131. this.refreshBoundingInfo();
  37132. // Parent
  37133. if (newParent) {
  37134. result.parent = newParent;
  37135. }
  37136. if (!doNotCloneChildren) {
  37137. // Children
  37138. for (var index = 0; index < this.getScene().meshes.length; index++) {
  37139. var mesh = this.getScene().meshes[index];
  37140. if (mesh.parent === this) {
  37141. mesh.clone(mesh.name, result);
  37142. }
  37143. }
  37144. }
  37145. result.computeWorldMatrix(true);
  37146. return result;
  37147. };
  37148. /**
  37149. * Disposes the InstancedMesh.
  37150. * Returns nothing.
  37151. */
  37152. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  37153. // Remove from mesh
  37154. var index = this._sourceMesh.instances.indexOf(this);
  37155. this._sourceMesh.instances.splice(index, 1);
  37156. _super.prototype.dispose.call(this, doNotRecurse);
  37157. };
  37158. return InstancedMesh;
  37159. }(BABYLON.AbstractMesh));
  37160. BABYLON.InstancedMesh = InstancedMesh;
  37161. })(BABYLON || (BABYLON = {}));
  37162. //# sourceMappingURL=babylon.instancedMesh.js.map
  37163. /// <reference path="babylon.mesh.ts" />
  37164. var BABYLON;
  37165. (function (BABYLON) {
  37166. var LinesMesh = (function (_super) {
  37167. __extends(LinesMesh, _super);
  37168. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  37169. if (parent === void 0) { parent = null; }
  37170. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  37171. _this.color = new BABYLON.Color3(1, 1, 1);
  37172. _this.alpha = 1;
  37173. _this._positionBuffer = {};
  37174. if (source) {
  37175. _this.color = source.color.clone();
  37176. _this.alpha = source.alpha;
  37177. }
  37178. _this._intersectionThreshold = 0.1;
  37179. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  37180. attributes: [BABYLON.VertexBuffer.PositionKind],
  37181. uniforms: ["worldViewProjection", "color"],
  37182. needAlphaBlending: true
  37183. });
  37184. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  37185. return _this;
  37186. }
  37187. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  37188. /**
  37189. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37190. * This margin is expressed in world space coordinates, so its value may vary.
  37191. * Default value is 0.1
  37192. * @returns the intersection Threshold value.
  37193. */
  37194. get: function () {
  37195. return this._intersectionThreshold;
  37196. },
  37197. /**
  37198. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37199. * This margin is expressed in world space coordinates, so its value may vary.
  37200. * @param value the new threshold to apply
  37201. */
  37202. set: function (value) {
  37203. if (this._intersectionThreshold === value) {
  37204. return;
  37205. }
  37206. this._intersectionThreshold = value;
  37207. if (this.geometry) {
  37208. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  37209. }
  37210. },
  37211. enumerable: true,
  37212. configurable: true
  37213. });
  37214. /**
  37215. * Returns the string "LineMesh"
  37216. */
  37217. LinesMesh.prototype.getClassName = function () {
  37218. return "LinesMesh";
  37219. };
  37220. Object.defineProperty(LinesMesh.prototype, "material", {
  37221. get: function () {
  37222. return this._colorShader;
  37223. },
  37224. enumerable: true,
  37225. configurable: true
  37226. });
  37227. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  37228. get: function () {
  37229. return false;
  37230. },
  37231. enumerable: true,
  37232. configurable: true
  37233. });
  37234. LinesMesh.prototype.createInstance = function (name) {
  37235. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  37236. return null;
  37237. };
  37238. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  37239. var engine = this.getScene().getEngine();
  37240. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  37241. // VBOs
  37242. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  37243. // Color
  37244. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  37245. return this;
  37246. };
  37247. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  37248. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  37249. return this;
  37250. }
  37251. var engine = this.getScene().getEngine();
  37252. // Draw order
  37253. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  37254. return this;
  37255. };
  37256. LinesMesh.prototype.dispose = function (doNotRecurse) {
  37257. this._colorShader.dispose();
  37258. _super.prototype.dispose.call(this, doNotRecurse);
  37259. };
  37260. /**
  37261. * Returns a new LineMesh object cloned from the current one.
  37262. */
  37263. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37264. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  37265. };
  37266. return LinesMesh;
  37267. }(BABYLON.Mesh));
  37268. BABYLON.LinesMesh = LinesMesh;
  37269. })(BABYLON || (BABYLON = {}));
  37270. //# sourceMappingURL=babylon.linesMesh.js.map
  37271. var BABYLON;
  37272. (function (BABYLON) {
  37273. var ShaderMaterial = (function (_super) {
  37274. __extends(ShaderMaterial, _super);
  37275. function ShaderMaterial(name, scene, shaderPath, options) {
  37276. var _this = _super.call(this, name, scene) || this;
  37277. _this._textures = {};
  37278. _this._textureArrays = {};
  37279. _this._floats = {};
  37280. _this._floatsArrays = {};
  37281. _this._colors3 = {};
  37282. _this._colors4 = {};
  37283. _this._vectors2 = {};
  37284. _this._vectors3 = {};
  37285. _this._vectors4 = {};
  37286. _this._matrices = {};
  37287. _this._matrices3x3 = {};
  37288. _this._matrices2x2 = {};
  37289. _this._vectors3Arrays = {};
  37290. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  37291. _this._shaderPath = shaderPath;
  37292. options.needAlphaBlending = options.needAlphaBlending || false;
  37293. options.needAlphaTesting = options.needAlphaTesting || false;
  37294. options.attributes = options.attributes || ["position", "normal", "uv"];
  37295. options.uniforms = options.uniforms || ["worldViewProjection"];
  37296. options.samplers = options.samplers || [];
  37297. options.defines = options.defines || [];
  37298. _this._options = options;
  37299. return _this;
  37300. }
  37301. ShaderMaterial.prototype.getClassName = function () {
  37302. return "ShaderMaterial";
  37303. };
  37304. ShaderMaterial.prototype.needAlphaBlending = function () {
  37305. return this._options.needAlphaBlending;
  37306. };
  37307. ShaderMaterial.prototype.needAlphaTesting = function () {
  37308. return this._options.needAlphaTesting;
  37309. };
  37310. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  37311. if (this._options.uniforms.indexOf(uniformName) === -1) {
  37312. this._options.uniforms.push(uniformName);
  37313. }
  37314. };
  37315. ShaderMaterial.prototype.setTexture = function (name, texture) {
  37316. if (this._options.samplers.indexOf(name) === -1) {
  37317. this._options.samplers.push(name);
  37318. }
  37319. this._textures[name] = texture;
  37320. return this;
  37321. };
  37322. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  37323. if (this._options.samplers.indexOf(name) === -1) {
  37324. this._options.samplers.push(name);
  37325. }
  37326. this._checkUniform(name);
  37327. this._textureArrays[name] = textures;
  37328. return this;
  37329. };
  37330. ShaderMaterial.prototype.setFloat = function (name, value) {
  37331. this._checkUniform(name);
  37332. this._floats[name] = value;
  37333. return this;
  37334. };
  37335. ShaderMaterial.prototype.setFloats = function (name, value) {
  37336. this._checkUniform(name);
  37337. this._floatsArrays[name] = value;
  37338. return this;
  37339. };
  37340. ShaderMaterial.prototype.setColor3 = function (name, value) {
  37341. this._checkUniform(name);
  37342. this._colors3[name] = value;
  37343. return this;
  37344. };
  37345. ShaderMaterial.prototype.setColor4 = function (name, value) {
  37346. this._checkUniform(name);
  37347. this._colors4[name] = value;
  37348. return this;
  37349. };
  37350. ShaderMaterial.prototype.setVector2 = function (name, value) {
  37351. this._checkUniform(name);
  37352. this._vectors2[name] = value;
  37353. return this;
  37354. };
  37355. ShaderMaterial.prototype.setVector3 = function (name, value) {
  37356. this._checkUniform(name);
  37357. this._vectors3[name] = value;
  37358. return this;
  37359. };
  37360. ShaderMaterial.prototype.setVector4 = function (name, value) {
  37361. this._checkUniform(name);
  37362. this._vectors4[name] = value;
  37363. return this;
  37364. };
  37365. ShaderMaterial.prototype.setMatrix = function (name, value) {
  37366. this._checkUniform(name);
  37367. this._matrices[name] = value;
  37368. return this;
  37369. };
  37370. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  37371. this._checkUniform(name);
  37372. this._matrices3x3[name] = value;
  37373. return this;
  37374. };
  37375. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  37376. this._checkUniform(name);
  37377. this._matrices2x2[name] = value;
  37378. return this;
  37379. };
  37380. ShaderMaterial.prototype.setArray3 = function (name, value) {
  37381. this._checkUniform(name);
  37382. this._vectors3Arrays[name] = value;
  37383. return this;
  37384. };
  37385. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  37386. if (!mesh) {
  37387. return true;
  37388. }
  37389. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  37390. return false;
  37391. }
  37392. return false;
  37393. };
  37394. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  37395. var scene = this.getScene();
  37396. var engine = scene.getEngine();
  37397. if (!this.checkReadyOnEveryCall) {
  37398. if (this._renderId === scene.getRenderId()) {
  37399. if (this._checkCache(scene, mesh, useInstances)) {
  37400. return true;
  37401. }
  37402. }
  37403. }
  37404. // Instances
  37405. var defines = [];
  37406. var fallbacks = new BABYLON.EffectFallbacks();
  37407. if (useInstances) {
  37408. defines.push("#define INSTANCES");
  37409. }
  37410. for (var index = 0; index < this._options.defines.length; index++) {
  37411. defines.push(this._options.defines[index]);
  37412. }
  37413. // Bones
  37414. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  37415. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37416. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37417. fallbacks.addCPUSkinningFallback(0, mesh);
  37418. }
  37419. // Textures
  37420. for (var name in this._textures) {
  37421. if (!this._textures[name].isReady()) {
  37422. return false;
  37423. }
  37424. }
  37425. // Alpha test
  37426. if (engine.getAlphaTesting()) {
  37427. defines.push("#define ALPHATEST");
  37428. }
  37429. var previousEffect = this._effect;
  37430. var join = defines.join("\n");
  37431. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  37432. if (!this._effect.isReady()) {
  37433. return false;
  37434. }
  37435. if (previousEffect !== this._effect) {
  37436. scene.resetCachedMaterial();
  37437. }
  37438. this._renderId = scene.getRenderId();
  37439. return true;
  37440. };
  37441. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37442. var scene = this.getScene();
  37443. if (this._options.uniforms.indexOf("world") !== -1) {
  37444. this._effect.setMatrix("world", world);
  37445. }
  37446. if (this._options.uniforms.indexOf("worldView") !== -1) {
  37447. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  37448. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  37449. }
  37450. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  37451. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  37452. }
  37453. };
  37454. ShaderMaterial.prototype.bind = function (world, mesh) {
  37455. // Std values
  37456. this.bindOnlyWorldMatrix(world);
  37457. if (this.getScene().getCachedMaterial() !== this) {
  37458. if (this._options.uniforms.indexOf("view") !== -1) {
  37459. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  37460. }
  37461. if (this._options.uniforms.indexOf("projection") !== -1) {
  37462. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  37463. }
  37464. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  37465. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  37466. }
  37467. // Bones
  37468. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  37469. var name;
  37470. // Texture
  37471. for (name in this._textures) {
  37472. this._effect.setTexture(name, this._textures[name]);
  37473. }
  37474. // Texture arrays
  37475. for (name in this._textureArrays) {
  37476. this._effect.setTextureArray(name, this._textureArrays[name]);
  37477. }
  37478. // Float
  37479. for (name in this._floats) {
  37480. this._effect.setFloat(name, this._floats[name]);
  37481. }
  37482. // Float s
  37483. for (name in this._floatsArrays) {
  37484. this._effect.setArray(name, this._floatsArrays[name]);
  37485. }
  37486. // Color3
  37487. for (name in this._colors3) {
  37488. this._effect.setColor3(name, this._colors3[name]);
  37489. }
  37490. // Color4
  37491. for (name in this._colors4) {
  37492. var color = this._colors4[name];
  37493. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  37494. }
  37495. // Vector2
  37496. for (name in this._vectors2) {
  37497. this._effect.setVector2(name, this._vectors2[name]);
  37498. }
  37499. // Vector3
  37500. for (name in this._vectors3) {
  37501. this._effect.setVector3(name, this._vectors3[name]);
  37502. }
  37503. // Vector4
  37504. for (name in this._vectors4) {
  37505. this._effect.setVector4(name, this._vectors4[name]);
  37506. }
  37507. // Matrix
  37508. for (name in this._matrices) {
  37509. this._effect.setMatrix(name, this._matrices[name]);
  37510. }
  37511. // Matrix 3x3
  37512. for (name in this._matrices3x3) {
  37513. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  37514. }
  37515. // Matrix 2x2
  37516. for (name in this._matrices2x2) {
  37517. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  37518. }
  37519. // Vector3Array
  37520. for (name in this._vectors3Arrays) {
  37521. this._effect.setArray3(name, this._vectors3Arrays[name]);
  37522. }
  37523. }
  37524. this._afterBind(mesh);
  37525. };
  37526. ShaderMaterial.prototype.clone = function (name) {
  37527. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  37528. return newShaderMaterial;
  37529. };
  37530. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37531. if (forceDisposeTextures) {
  37532. var name;
  37533. for (name in this._textures) {
  37534. this._textures[name].dispose();
  37535. }
  37536. for (name in this._textureArrays) {
  37537. var array = this._textureArrays[name];
  37538. for (var index = 0; index < array.length; index++) {
  37539. array[index].dispose();
  37540. }
  37541. }
  37542. }
  37543. this._textures = {};
  37544. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37545. };
  37546. ShaderMaterial.prototype.serialize = function () {
  37547. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37548. serializationObject.customType = "BABYLON.ShaderMaterial";
  37549. serializationObject.options = this._options;
  37550. serializationObject.shaderPath = this._shaderPath;
  37551. var name;
  37552. // Texture
  37553. serializationObject.textures = {};
  37554. for (name in this._textures) {
  37555. serializationObject.textures[name] = this._textures[name].serialize();
  37556. }
  37557. // Texture arrays
  37558. serializationObject.textureArrays = {};
  37559. for (name in this._textureArrays) {
  37560. serializationObject.textureArrays[name] = [];
  37561. var array = this._textureArrays[name];
  37562. for (var index = 0; index < array.length; index++) {
  37563. serializationObject.textureArrays[name].push(array[index].serialize());
  37564. }
  37565. }
  37566. // Float
  37567. serializationObject.floats = {};
  37568. for (name in this._floats) {
  37569. serializationObject.floats[name] = this._floats[name];
  37570. }
  37571. // Float s
  37572. serializationObject.floatArrays = {};
  37573. for (name in this._floatsArrays) {
  37574. serializationObject.floatArrays[name] = this._floatsArrays[name];
  37575. }
  37576. // Color3
  37577. serializationObject.colors3 = {};
  37578. for (name in this._colors3) {
  37579. serializationObject.colors3[name] = this._colors3[name].asArray();
  37580. }
  37581. // Color4
  37582. serializationObject.colors4 = {};
  37583. for (name in this._colors4) {
  37584. serializationObject.colors4[name] = this._colors4[name].asArray();
  37585. }
  37586. // Vector2
  37587. serializationObject.vectors2 = {};
  37588. for (name in this._vectors2) {
  37589. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  37590. }
  37591. // Vector3
  37592. serializationObject.vectors3 = {};
  37593. for (name in this._vectors3) {
  37594. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  37595. }
  37596. // Vector4
  37597. serializationObject.vectors4 = {};
  37598. for (name in this._vectors4) {
  37599. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  37600. }
  37601. // Matrix
  37602. serializationObject.matrices = {};
  37603. for (name in this._matrices) {
  37604. serializationObject.matrices[name] = this._matrices[name].asArray();
  37605. }
  37606. // Matrix 3x3
  37607. serializationObject.matrices3x3 = {};
  37608. for (name in this._matrices3x3) {
  37609. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  37610. }
  37611. // Matrix 2x2
  37612. serializationObject.matrices2x2 = {};
  37613. for (name in this._matrices2x2) {
  37614. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  37615. }
  37616. // Vector3Array
  37617. serializationObject.vectors3Arrays = {};
  37618. for (name in this._vectors3Arrays) {
  37619. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  37620. }
  37621. return serializationObject;
  37622. };
  37623. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  37624. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  37625. var name;
  37626. // Texture
  37627. for (name in source.textures) {
  37628. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  37629. }
  37630. // Texture arrays
  37631. for (name in source.textureArrays) {
  37632. var array = source.textureArrays[name];
  37633. var textureArray = new Array();
  37634. for (var index = 0; index < array.length; index++) {
  37635. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  37636. }
  37637. material.setTextureArray(name, textureArray);
  37638. }
  37639. // Float
  37640. for (name in source.floats) {
  37641. material.setFloat(name, source.floats[name]);
  37642. }
  37643. // Float s
  37644. for (name in source.floatsArrays) {
  37645. material.setFloats(name, source.floatsArrays[name]);
  37646. }
  37647. // Color3
  37648. for (name in source.colors3) {
  37649. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  37650. }
  37651. // Color4
  37652. for (name in source.colors4) {
  37653. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  37654. }
  37655. // Vector2
  37656. for (name in source.vectors2) {
  37657. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  37658. }
  37659. // Vector3
  37660. for (name in source.vectors3) {
  37661. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  37662. }
  37663. // Vector4
  37664. for (name in source.vectors4) {
  37665. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  37666. }
  37667. // Matrix
  37668. for (name in source.matrices) {
  37669. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  37670. }
  37671. // Matrix 3x3
  37672. for (name in source.matrices3x3) {
  37673. material.setMatrix3x3(name, source.matrices3x3[name]);
  37674. }
  37675. // Matrix 2x2
  37676. for (name in source.matrices2x2) {
  37677. material.setMatrix2x2(name, source.matrices2x2[name]);
  37678. }
  37679. // Vector3Array
  37680. for (name in source.vectors3Arrays) {
  37681. material.setArray3(name, source.vectors3Arrays[name]);
  37682. }
  37683. return material;
  37684. };
  37685. return ShaderMaterial;
  37686. }(BABYLON.Material));
  37687. BABYLON.ShaderMaterial = ShaderMaterial;
  37688. })(BABYLON || (BABYLON = {}));
  37689. //# sourceMappingURL=babylon.shaderMaterial.js.map
  37690. var BABYLON;
  37691. (function (BABYLON) {
  37692. var MeshBuilder = (function () {
  37693. function MeshBuilder() {
  37694. }
  37695. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  37696. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  37697. return BABYLON.Mesh.DOUBLESIDE;
  37698. }
  37699. if (orientation === undefined || orientation === null) {
  37700. return BABYLON.Mesh.FRONTSIDE;
  37701. }
  37702. return orientation;
  37703. };
  37704. /**
  37705. * Creates a box mesh.
  37706. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  37707. * The parameter `size` sets the size (float) of each box side (default 1).
  37708. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  37709. * 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).
  37710. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  37711. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37712. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37713. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37714. */
  37715. MeshBuilder.CreateBox = function (name, options, scene) {
  37716. var box = new BABYLON.Mesh(name, scene);
  37717. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37718. box.sideOrientation = options.sideOrientation;
  37719. var vertexData = BABYLON.VertexData.CreateBox(options);
  37720. vertexData.applyToMesh(box, options.updatable);
  37721. return box;
  37722. };
  37723. /**
  37724. * Creates a sphere mesh.
  37725. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  37726. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  37727. * 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`).
  37728. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  37729. * 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
  37730. * 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).
  37731. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37732. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37733. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37734. */
  37735. MeshBuilder.CreateSphere = function (name, options, scene) {
  37736. var sphere = new BABYLON.Mesh(name, scene);
  37737. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37738. sphere.sideOrientation = options.sideOrientation;
  37739. var vertexData = BABYLON.VertexData.CreateSphere(options);
  37740. vertexData.applyToMesh(sphere, options.updatable);
  37741. return sphere;
  37742. };
  37743. /**
  37744. * Creates a plane polygonal mesh. By default, this is a disc.
  37745. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  37746. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  37747. * 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.
  37748. * 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
  37749. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37750. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37752. */
  37753. MeshBuilder.CreateDisc = function (name, options, scene) {
  37754. var disc = new BABYLON.Mesh(name, scene);
  37755. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37756. disc.sideOrientation = options.sideOrientation;
  37757. var vertexData = BABYLON.VertexData.CreateDisc(options);
  37758. vertexData.applyToMesh(disc, options.updatable);
  37759. return disc;
  37760. };
  37761. /**
  37762. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  37763. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  37764. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  37765. * 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`).
  37766. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  37767. * 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.
  37768. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37769. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37770. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37771. */
  37772. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  37773. var sphere = new BABYLON.Mesh(name, scene);
  37774. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37775. sphere.sideOrientation = options.sideOrientation;
  37776. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  37777. vertexData.applyToMesh(sphere, options.updatable);
  37778. return sphere;
  37779. };
  37780. ;
  37781. /**
  37782. * Creates a ribbon mesh.
  37783. * 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.
  37784. *
  37785. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  37786. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  37787. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  37788. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  37789. * 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.
  37790. * 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.
  37791. * 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
  37792. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37793. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37794. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37795. * 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.
  37796. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  37797. * 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
  37798. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  37799. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  37800. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37801. */
  37802. MeshBuilder.CreateRibbon = function (name, options, scene) {
  37803. var pathArray = options.pathArray;
  37804. var closeArray = options.closeArray;
  37805. var closePath = options.closePath;
  37806. var offset = options.offset;
  37807. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37808. var instance = options.instance;
  37809. var updatable = options.updatable;
  37810. if (instance) {
  37811. // positionFunction : ribbon case
  37812. // only pathArray and sideOrientation parameters are taken into account for positions update
  37813. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  37814. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  37815. var positionFunction = function (positions) {
  37816. var minlg = pathArray[0].length;
  37817. var i = 0;
  37818. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  37819. for (var si = 1; si <= ns; si++) {
  37820. for (var p = 0; p < pathArray.length; p++) {
  37821. var path = pathArray[p];
  37822. var l = path.length;
  37823. minlg = (minlg < l) ? minlg : l;
  37824. var j = 0;
  37825. while (j < minlg) {
  37826. positions[i] = path[j].x;
  37827. positions[i + 1] = path[j].y;
  37828. positions[i + 2] = path[j].z;
  37829. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  37830. BABYLON.Tmp.Vector3[0].x = path[j].x;
  37831. }
  37832. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  37833. BABYLON.Tmp.Vector3[1].x = path[j].x;
  37834. }
  37835. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  37836. BABYLON.Tmp.Vector3[0].y = path[j].y;
  37837. }
  37838. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  37839. BABYLON.Tmp.Vector3[1].y = path[j].y;
  37840. }
  37841. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  37842. BABYLON.Tmp.Vector3[0].z = path[j].z;
  37843. }
  37844. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  37845. BABYLON.Tmp.Vector3[1].z = path[j].z;
  37846. }
  37847. j++;
  37848. i += 3;
  37849. }
  37850. if (instance._closePath) {
  37851. positions[i] = path[0].x;
  37852. positions[i + 1] = path[0].y;
  37853. positions[i + 2] = path[0].z;
  37854. i += 3;
  37855. }
  37856. }
  37857. }
  37858. };
  37859. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37860. positionFunction(positions);
  37861. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  37862. instance._boundingInfo.update(instance._worldMatrix);
  37863. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  37864. if (options.colors) {
  37865. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37866. for (var c = 0; c < options.colors.length; c++) {
  37867. colors[c * 4] = options.colors[c].r;
  37868. colors[c * 4 + 1] = options.colors[c].g;
  37869. colors[c * 4 + 2] = options.colors[c].b;
  37870. colors[c * 4 + 3] = options.colors[c].a;
  37871. }
  37872. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  37873. }
  37874. if (options.uvs) {
  37875. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37876. for (var i = 0; i < options.uvs.length; i++) {
  37877. uvs[i * 2] = options.uvs[i].x;
  37878. uvs[i * 2 + 1] = options.uvs[i].y;
  37879. }
  37880. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  37881. }
  37882. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  37883. var indices = instance.getIndices();
  37884. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37885. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  37886. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  37887. if (instance._closePath) {
  37888. var indexFirst = 0;
  37889. var indexLast = 0;
  37890. for (var p = 0; p < pathArray.length; p++) {
  37891. indexFirst = instance._idx[p] * 3;
  37892. if (p + 1 < pathArray.length) {
  37893. indexLast = (instance._idx[p + 1] - 1) * 3;
  37894. }
  37895. else {
  37896. indexLast = normals.length - 3;
  37897. }
  37898. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37899. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37900. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37901. normals[indexLast] = normals[indexFirst];
  37902. normals[indexLast + 1] = normals[indexFirst + 1];
  37903. normals[indexLast + 2] = normals[indexFirst + 2];
  37904. }
  37905. }
  37906. if (!(instance.areNormalsFrozen)) {
  37907. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  37908. }
  37909. }
  37910. return instance;
  37911. }
  37912. else {
  37913. var ribbon = new BABYLON.Mesh(name, scene);
  37914. ribbon.sideOrientation = sideOrientation;
  37915. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  37916. if (closePath) {
  37917. ribbon._idx = vertexData._idx;
  37918. }
  37919. ribbon._closePath = closePath;
  37920. ribbon._closeArray = closeArray;
  37921. vertexData.applyToMesh(ribbon, updatable);
  37922. return ribbon;
  37923. }
  37924. };
  37925. /**
  37926. * Creates a cylinder or a cone mesh.
  37927. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  37928. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  37929. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  37930. * 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.
  37931. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  37932. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  37933. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  37934. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  37935. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  37936. * 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).
  37937. * 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
  37938. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  37939. * 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
  37940. * 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.
  37941. * If `enclose` is false, a ring surface is one element.
  37942. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  37943. * 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
  37944. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37945. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37946. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37947. */
  37948. MeshBuilder.CreateCylinder = function (name, options, scene) {
  37949. var cylinder = new BABYLON.Mesh(name, scene);
  37950. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37951. cylinder.sideOrientation = options.sideOrientation;
  37952. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  37953. vertexData.applyToMesh(cylinder, options.updatable);
  37954. return cylinder;
  37955. };
  37956. /**
  37957. * Creates a torus mesh.
  37958. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  37959. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  37960. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  37961. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  37962. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37963. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37964. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37965. */
  37966. MeshBuilder.CreateTorus = function (name, options, scene) {
  37967. var torus = new BABYLON.Mesh(name, scene);
  37968. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37969. torus.sideOrientation = options.sideOrientation;
  37970. var vertexData = BABYLON.VertexData.CreateTorus(options);
  37971. vertexData.applyToMesh(torus, options.updatable);
  37972. return torus;
  37973. };
  37974. /**
  37975. * Creates a torus knot mesh.
  37976. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  37977. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  37978. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  37979. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  37980. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  37981. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37982. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37984. */
  37985. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  37986. var torusKnot = new BABYLON.Mesh(name, scene);
  37987. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37988. torusKnot.sideOrientation = options.sideOrientation;
  37989. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  37990. vertexData.applyToMesh(torusKnot, options.updatable);
  37991. return torusKnot;
  37992. };
  37993. /**
  37994. * Creates a line system mesh.
  37995. * A line system is a pool of many lines gathered in a single mesh.
  37996. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  37997. * 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.
  37998. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  37999. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  38000. * 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
  38001. * 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
  38002. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  38003. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38004. */
  38005. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  38006. var instance = options.instance;
  38007. var lines = options.lines;
  38008. if (instance) {
  38009. var positionFunction = function (positions) {
  38010. var i = 0;
  38011. for (var l = 0; l < lines.length; l++) {
  38012. var points = lines[l];
  38013. for (var p = 0; p < points.length; p++) {
  38014. positions[i] = points[p].x;
  38015. positions[i + 1] = points[p].y;
  38016. positions[i + 2] = points[p].z;
  38017. i += 3;
  38018. }
  38019. }
  38020. };
  38021. instance.updateMeshPositions(positionFunction, false);
  38022. return instance;
  38023. }
  38024. // line system creation
  38025. var lineSystem = new BABYLON.LinesMesh(name, scene);
  38026. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  38027. vertexData.applyToMesh(lineSystem, options.updatable);
  38028. return lineSystem;
  38029. };
  38030. /**
  38031. * Creates a line mesh.
  38032. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  38033. * 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.
  38034. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  38035. * The parameter `points` is an array successive Vector3.
  38036. * 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
  38037. * When updating an instance, remember that only point positions can change, not the number of points.
  38038. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38039. */
  38040. MeshBuilder.CreateLines = function (name, options, scene) {
  38041. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  38042. return lines;
  38043. };
  38044. /**
  38045. * Creates a dashed line mesh.
  38046. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  38047. * 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.
  38048. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  38049. * The parameter `points` is an array successive Vector3.
  38050. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  38051. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  38052. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  38053. * 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
  38054. * When updating an instance, remember that only point positions can change, not the number of points.
  38055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38056. */
  38057. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  38058. var points = options.points;
  38059. var instance = options.instance;
  38060. var gapSize = options.gapSize;
  38061. var dashNb = options.dashNb;
  38062. var dashSize = options.dashSize;
  38063. if (instance) {
  38064. var positionFunction = function (positions) {
  38065. var curvect = BABYLON.Vector3.Zero();
  38066. var nbSeg = positions.length / 6;
  38067. var lg = 0;
  38068. var nb = 0;
  38069. var shft = 0;
  38070. var dashshft = 0;
  38071. var curshft = 0;
  38072. var p = 0;
  38073. var i = 0;
  38074. var j = 0;
  38075. for (i = 0; i < points.length - 1; i++) {
  38076. points[i + 1].subtractToRef(points[i], curvect);
  38077. lg += curvect.length();
  38078. }
  38079. shft = lg / nbSeg;
  38080. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  38081. for (i = 0; i < points.length - 1; i++) {
  38082. points[i + 1].subtractToRef(points[i], curvect);
  38083. nb = Math.floor(curvect.length() / shft);
  38084. curvect.normalize();
  38085. j = 0;
  38086. while (j < nb && p < positions.length) {
  38087. curshft = shft * j;
  38088. positions[p] = points[i].x + curshft * curvect.x;
  38089. positions[p + 1] = points[i].y + curshft * curvect.y;
  38090. positions[p + 2] = points[i].z + curshft * curvect.z;
  38091. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  38092. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  38093. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  38094. p += 6;
  38095. j++;
  38096. }
  38097. }
  38098. while (p < positions.length) {
  38099. positions[p] = points[i].x;
  38100. positions[p + 1] = points[i].y;
  38101. positions[p + 2] = points[i].z;
  38102. p += 3;
  38103. }
  38104. };
  38105. instance.updateMeshPositions(positionFunction, false);
  38106. return instance;
  38107. }
  38108. // dashed lines creation
  38109. var dashedLines = new BABYLON.LinesMesh(name, scene);
  38110. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  38111. vertexData.applyToMesh(dashedLines, options.updatable);
  38112. dashedLines.dashSize = dashSize;
  38113. dashedLines.gapSize = gapSize;
  38114. return dashedLines;
  38115. };
  38116. /**
  38117. * Creates an extruded shape mesh.
  38118. * 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.
  38119. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  38120. *
  38121. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  38122. * 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
  38123. * extruded along the Z axis.
  38124. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  38125. * 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.
  38126. * The parameter `scale` (float, default 1) is the value to scale the shape.
  38127. * 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
  38128. * 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
  38129. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  38130. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38131. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38132. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38133. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38134. */
  38135. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  38136. var path = options.path;
  38137. var shape = options.shape;
  38138. var scale = options.scale || 1;
  38139. var rotation = options.rotation || 0;
  38140. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  38141. var updatable = options.updatable;
  38142. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38143. var instance = options.instance;
  38144. var invertUV = options.invertUV || false;
  38145. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  38146. };
  38147. /**
  38148. * Creates an custom extruded shape mesh.
  38149. * 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.
  38150. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  38151. *
  38152. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  38153. * 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
  38154. * extruded along the Z axis.
  38155. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  38156. * 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
  38157. * and the distance of this point from the begining of the path :
  38158. * ```javascript
  38159. * var rotationFunction = function(i, distance) {
  38160. * // do things
  38161. * return rotationValue; }
  38162. * ```
  38163. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  38164. * 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
  38165. * and the distance of this point from the begining of the path :
  38166. * ```javascript
  38167. * var scaleFunction = function(i, distance) {
  38168. * // do things
  38169. * return scaleValue;}
  38170. * ```
  38171. * It must returns a float value that will be the scale value applied to the shape on each path point.
  38172. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  38173. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  38174. * 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
  38175. * 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
  38176. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  38177. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38178. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38179. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38181. */
  38182. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  38183. var path = options.path;
  38184. var shape = options.shape;
  38185. var scaleFunction = options.scaleFunction || (function () { return 1; });
  38186. var rotationFunction = options.rotationFunction || (function () { return 0; });
  38187. var ribbonCloseArray = options.ribbonCloseArray || false;
  38188. var ribbonClosePath = options.ribbonClosePath || false;
  38189. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  38190. var updatable = options.updatable;
  38191. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38192. var instance = options.instance;
  38193. var invertUV = options.invertUV || false;
  38194. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  38195. };
  38196. /**
  38197. * Creates lathe mesh.
  38198. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  38199. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  38200. *
  38201. * 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
  38202. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  38203. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  38204. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  38205. * 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.
  38206. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  38207. * 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
  38208. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38209. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38210. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38211. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38212. */
  38213. MeshBuilder.CreateLathe = function (name, options, scene) {
  38214. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  38215. var closed = (options.closed === undefined) ? true : options.closed;
  38216. var shape = options.shape;
  38217. var radius = options.radius || 1;
  38218. var tessellation = options.tessellation || 64;
  38219. var updatable = options.updatable;
  38220. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38221. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  38222. var pi2 = Math.PI * 2;
  38223. var paths = new Array();
  38224. var invertUV = options.invertUV || false;
  38225. var i = 0;
  38226. var p = 0;
  38227. var step = pi2 / tessellation * arc;
  38228. var rotated;
  38229. var path = new Array();
  38230. ;
  38231. for (i = 0; i <= tessellation; i++) {
  38232. var path = [];
  38233. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  38234. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  38235. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  38236. }
  38237. for (p = 0; p < shape.length; p++) {
  38238. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  38239. path.push(rotated);
  38240. }
  38241. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  38242. 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));
  38243. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  38244. }
  38245. paths.push(path);
  38246. }
  38247. // lathe ribbon
  38248. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  38249. return lathe;
  38250. };
  38251. /**
  38252. * Creates a plane mesh.
  38253. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  38254. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  38255. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  38256. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  38257. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38258. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38259. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38260. */
  38261. MeshBuilder.CreatePlane = function (name, options, scene) {
  38262. var plane = new BABYLON.Mesh(name, scene);
  38263. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38264. plane.sideOrientation = options.sideOrientation;
  38265. var vertexData = BABYLON.VertexData.CreatePlane(options);
  38266. vertexData.applyToMesh(plane, options.updatable);
  38267. if (options.sourcePlane) {
  38268. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  38269. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  38270. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  38271. plane.rotate(vectorProduct, product);
  38272. }
  38273. return plane;
  38274. };
  38275. /**
  38276. * Creates a ground mesh.
  38277. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  38278. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  38279. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  38280. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38281. */
  38282. MeshBuilder.CreateGround = function (name, options, scene) {
  38283. var ground = new BABYLON.GroundMesh(name, scene);
  38284. ground._setReady(false);
  38285. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38286. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38287. ground._width = options.width || 1;
  38288. ground._height = options.height || 1;
  38289. ground._maxX = ground._width / 2;
  38290. ground._maxZ = ground._height / 2;
  38291. ground._minX = -ground._maxX;
  38292. ground._minZ = -ground._maxZ;
  38293. var vertexData = BABYLON.VertexData.CreateGround(options);
  38294. vertexData.applyToMesh(ground, options.updatable);
  38295. ground._setReady(true);
  38296. return ground;
  38297. };
  38298. /**
  38299. * Creates a tiled ground mesh.
  38300. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  38301. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  38302. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  38303. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  38304. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  38305. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  38306. * numbers of subdivisions on the ground width and height of each tile.
  38307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38308. */
  38309. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  38310. var tiledGround = new BABYLON.Mesh(name, scene);
  38311. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  38312. vertexData.applyToMesh(tiledGround, options.updatable);
  38313. return tiledGround;
  38314. };
  38315. /**
  38316. * Creates a ground mesh from a height map.
  38317. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  38318. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  38319. * The parameter `url` sets the URL of the height map image resource.
  38320. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  38321. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  38322. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  38323. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  38324. * 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.
  38325. * 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).
  38326. * This function is passed the newly built mesh :
  38327. * ```javascript
  38328. * function(mesh) { // do things
  38329. * return; }
  38330. * ```
  38331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38332. */
  38333. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  38334. var width = options.width || 10.0;
  38335. var height = options.height || 10.0;
  38336. var subdivisions = options.subdivisions || 1 | 0;
  38337. var minHeight = options.minHeight || 0.0;
  38338. var maxHeight = options.maxHeight || 10.0;
  38339. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38340. var updatable = options.updatable;
  38341. var onReady = options.onReady;
  38342. var ground = new BABYLON.GroundMesh(name, scene);
  38343. ground._subdivisionsX = subdivisions;
  38344. ground._subdivisionsY = subdivisions;
  38345. ground._width = width;
  38346. ground._height = height;
  38347. ground._maxX = ground._width / 2.0;
  38348. ground._maxZ = ground._height / 2.0;
  38349. ground._minX = -ground._maxX;
  38350. ground._minZ = -ground._maxZ;
  38351. ground._setReady(false);
  38352. var onload = function (img) {
  38353. // Getting height map data
  38354. var canvas = document.createElement("canvas");
  38355. var context = canvas.getContext("2d");
  38356. var bufferWidth = img.width;
  38357. var bufferHeight = img.height;
  38358. canvas.width = bufferWidth;
  38359. canvas.height = bufferHeight;
  38360. context.drawImage(img, 0, 0);
  38361. // Create VertexData from map data
  38362. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  38363. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  38364. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  38365. width: width, height: height,
  38366. subdivisions: subdivisions,
  38367. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  38368. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  38369. });
  38370. vertexData.applyToMesh(ground, updatable);
  38371. ground._setReady(true);
  38372. //execute ready callback, if set
  38373. if (onReady) {
  38374. onReady(ground);
  38375. }
  38376. };
  38377. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  38378. return ground;
  38379. };
  38380. /**
  38381. * Creates a tube mesh.
  38382. * 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.
  38383. *
  38384. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  38385. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  38386. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  38387. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  38388. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  38389. * 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.
  38390. * It must return a radius value (positive float) :
  38391. * ```javascript
  38392. * var radiusFunction = function(i, distance) {
  38393. * // do things
  38394. * return radius; }
  38395. * ```
  38396. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  38397. * 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
  38398. * 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
  38399. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38400. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38401. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38402. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38403. */
  38404. MeshBuilder.CreateTube = function (name, options, scene) {
  38405. var path = options.path;
  38406. var radius = options.radius || 1.0;
  38407. var tessellation = options.tessellation || 64 | 0;
  38408. var radiusFunction = options.radiusFunction;
  38409. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  38410. var invertUV = options.invertUV || false;
  38411. var updatable = options.updatable;
  38412. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38413. var instance = options.instance;
  38414. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  38415. // tube geometry
  38416. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  38417. var tangents = path3D.getTangents();
  38418. var normals = path3D.getNormals();
  38419. var distances = path3D.getDistances();
  38420. var pi2 = Math.PI * 2;
  38421. var step = pi2 / tessellation * arc;
  38422. var returnRadius = function () { return radius; };
  38423. var radiusFunctionFinal = radiusFunction || returnRadius;
  38424. var circlePath;
  38425. var rad;
  38426. var normal;
  38427. var rotated;
  38428. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  38429. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  38430. for (var i = 0; i < path.length; i++) {
  38431. rad = radiusFunctionFinal(i, distances[i]); // current radius
  38432. circlePath = Array(); // current circle array
  38433. normal = normals[i]; // current normal
  38434. for (var t = 0; t < tessellation; t++) {
  38435. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  38436. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  38437. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  38438. rotated.scaleInPlace(rad).addInPlace(path[i]);
  38439. circlePath[t] = rotated;
  38440. }
  38441. circlePaths[index] = circlePath;
  38442. index++;
  38443. }
  38444. // cap
  38445. var capPath = function (nbPoints, pathIndex) {
  38446. var pointCap = Array();
  38447. for (var i = 0; i < nbPoints; i++) {
  38448. pointCap.push(path[pathIndex]);
  38449. }
  38450. return pointCap;
  38451. };
  38452. switch (cap) {
  38453. case BABYLON.Mesh.NO_CAP:
  38454. break;
  38455. case BABYLON.Mesh.CAP_START:
  38456. circlePaths[0] = capPath(tessellation, 0);
  38457. circlePaths[1] = circlePaths[2].slice(0);
  38458. break;
  38459. case BABYLON.Mesh.CAP_END:
  38460. circlePaths[index] = circlePaths[index - 1].slice(0);
  38461. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  38462. break;
  38463. case BABYLON.Mesh.CAP_ALL:
  38464. circlePaths[0] = capPath(tessellation, 0);
  38465. circlePaths[1] = circlePaths[2].slice(0);
  38466. circlePaths[index] = circlePaths[index - 1].slice(0);
  38467. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  38468. break;
  38469. default:
  38470. break;
  38471. }
  38472. return circlePaths;
  38473. };
  38474. var path3D;
  38475. var pathArray;
  38476. if (instance) {
  38477. var arc = options.arc || instance.arc;
  38478. path3D = (instance.path3D).update(path);
  38479. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  38480. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  38481. instance.path3D = path3D;
  38482. instance.pathArray = pathArray;
  38483. instance.arc = arc;
  38484. return instance;
  38485. }
  38486. // tube creation
  38487. path3D = new BABYLON.Path3D(path);
  38488. var newPathArray = new Array();
  38489. cap = (cap < 0 || cap > 3) ? 0 : cap;
  38490. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  38491. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  38492. tube.pathArray = pathArray;
  38493. tube.path3D = path3D;
  38494. tube.tessellation = tessellation;
  38495. tube.cap = cap;
  38496. tube.arc = options.arc;
  38497. return tube;
  38498. };
  38499. /**
  38500. * Creates a polyhedron mesh.
  38501. *
  38502. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  38503. * 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
  38504. * to choose the wanted type.
  38505. * The parameter `size` (positive float, default 1) sets the polygon size.
  38506. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  38507. * 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`.
  38508. * 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
  38509. * 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)`).
  38510. * 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
  38511. * 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.
  38512. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38513. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38514. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38515. */
  38516. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  38517. var polyhedron = new BABYLON.Mesh(name, scene);
  38518. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38519. polyhedron.sideOrientation = options.sideOrientation;
  38520. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  38521. vertexData.applyToMesh(polyhedron, options.updatable);
  38522. return polyhedron;
  38523. };
  38524. /**
  38525. * Creates a decal mesh.
  38526. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  38527. * 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.
  38528. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  38529. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  38530. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  38531. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  38532. */
  38533. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  38534. var indices = sourceMesh.getIndices();
  38535. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38536. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38537. var position = options.position || BABYLON.Vector3.Zero();
  38538. var normal = options.normal || BABYLON.Vector3.Up();
  38539. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  38540. var angle = options.angle || 0;
  38541. // Getting correct rotation
  38542. if (!normal) {
  38543. var target = new BABYLON.Vector3(0, 0, 1);
  38544. var camera = sourceMesh.getScene().activeCamera;
  38545. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  38546. normal = camera.globalPosition.subtract(cameraWorldTarget);
  38547. }
  38548. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  38549. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  38550. var pitch = Math.atan2(normal.y, len);
  38551. // Matrix
  38552. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  38553. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  38554. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  38555. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  38556. var vertexData = new BABYLON.VertexData();
  38557. vertexData.indices = [];
  38558. vertexData.positions = [];
  38559. vertexData.normals = [];
  38560. vertexData.uvs = [];
  38561. var currentVertexDataIndex = 0;
  38562. var extractDecalVector3 = function (indexId) {
  38563. var vertexId = indices[indexId];
  38564. var result = new BABYLON.PositionNormalVertex();
  38565. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  38566. // Send vector to decal local world
  38567. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  38568. // Get normal
  38569. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  38570. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  38571. return result;
  38572. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  38573. var clip = function (vertices, axis) {
  38574. if (vertices.length === 0) {
  38575. return vertices;
  38576. }
  38577. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  38578. var clipVertices = function (v0, v1) {
  38579. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  38580. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  38581. };
  38582. var result = new Array();
  38583. for (var index = 0; index < vertices.length; index += 3) {
  38584. var v1Out;
  38585. var v2Out;
  38586. var v3Out;
  38587. var total = 0;
  38588. var nV1, nV2, nV3, nV4;
  38589. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  38590. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  38591. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  38592. v1Out = d1 > 0;
  38593. v2Out = d2 > 0;
  38594. v3Out = d3 > 0;
  38595. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  38596. switch (total) {
  38597. case 0:
  38598. result.push(vertices[index]);
  38599. result.push(vertices[index + 1]);
  38600. result.push(vertices[index + 2]);
  38601. break;
  38602. case 1:
  38603. if (v1Out) {
  38604. nV1 = vertices[index + 1];
  38605. nV2 = vertices[index + 2];
  38606. nV3 = clipVertices(vertices[index], nV1);
  38607. nV4 = clipVertices(vertices[index], nV2);
  38608. }
  38609. if (v2Out) {
  38610. nV1 = vertices[index];
  38611. nV2 = vertices[index + 2];
  38612. nV3 = clipVertices(vertices[index + 1], nV1);
  38613. nV4 = clipVertices(vertices[index + 1], nV2);
  38614. result.push(nV3);
  38615. result.push(nV2.clone());
  38616. result.push(nV1.clone());
  38617. result.push(nV2.clone());
  38618. result.push(nV3.clone());
  38619. result.push(nV4);
  38620. break;
  38621. }
  38622. if (v3Out) {
  38623. nV1 = vertices[index];
  38624. nV2 = vertices[index + 1];
  38625. nV3 = clipVertices(vertices[index + 2], nV1);
  38626. nV4 = clipVertices(vertices[index + 2], nV2);
  38627. }
  38628. result.push(nV1.clone());
  38629. result.push(nV2.clone());
  38630. result.push(nV3);
  38631. result.push(nV4);
  38632. result.push(nV3.clone());
  38633. result.push(nV2.clone());
  38634. break;
  38635. case 2:
  38636. if (!v1Out) {
  38637. nV1 = vertices[index].clone();
  38638. nV2 = clipVertices(nV1, vertices[index + 1]);
  38639. nV3 = clipVertices(nV1, vertices[index + 2]);
  38640. result.push(nV1);
  38641. result.push(nV2);
  38642. result.push(nV3);
  38643. }
  38644. if (!v2Out) {
  38645. nV1 = vertices[index + 1].clone();
  38646. nV2 = clipVertices(nV1, vertices[index + 2]);
  38647. nV3 = clipVertices(nV1, vertices[index]);
  38648. result.push(nV1);
  38649. result.push(nV2);
  38650. result.push(nV3);
  38651. }
  38652. if (!v3Out) {
  38653. nV1 = vertices[index + 2].clone();
  38654. nV2 = clipVertices(nV1, vertices[index]);
  38655. nV3 = clipVertices(nV1, vertices[index + 1]);
  38656. result.push(nV1);
  38657. result.push(nV2);
  38658. result.push(nV3);
  38659. }
  38660. break;
  38661. case 3:
  38662. break;
  38663. }
  38664. }
  38665. return result;
  38666. };
  38667. for (var index = 0; index < indices.length; index += 3) {
  38668. var faceVertices = new Array();
  38669. faceVertices.push(extractDecalVector3(index));
  38670. faceVertices.push(extractDecalVector3(index + 1));
  38671. faceVertices.push(extractDecalVector3(index + 2));
  38672. // Clip
  38673. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  38674. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  38675. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  38676. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  38677. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  38678. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  38679. if (faceVertices.length === 0) {
  38680. continue;
  38681. }
  38682. // Add UVs and get back to world
  38683. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  38684. var vertex = faceVertices[vIndex];
  38685. //TODO check for Int32Array | Uint32Array | Uint16Array
  38686. vertexData.indices.push(currentVertexDataIndex);
  38687. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  38688. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  38689. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  38690. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  38691. currentVertexDataIndex++;
  38692. }
  38693. }
  38694. // Return mesh
  38695. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  38696. vertexData.applyToMesh(decal);
  38697. decal.position = position.clone();
  38698. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  38699. return decal;
  38700. };
  38701. // Privates
  38702. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  38703. // extrusion geometry
  38704. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  38705. var tangents = path3D.getTangents();
  38706. var normals = path3D.getNormals();
  38707. var binormals = path3D.getBinormals();
  38708. var distances = path3D.getDistances();
  38709. var angle = 0;
  38710. var returnScale = function () { return scale; };
  38711. var returnRotation = function () { return rotation; };
  38712. var rotate = custom ? rotateFunction : returnRotation;
  38713. var scl = custom ? scaleFunction : returnScale;
  38714. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  38715. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  38716. for (var i = 0; i < curve.length; i++) {
  38717. var shapePath = new Array();
  38718. var angleStep = rotate(i, distances[i]);
  38719. var scaleRatio = scl(i, distances[i]);
  38720. for (var p = 0; p < shape.length; p++) {
  38721. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  38722. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  38723. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  38724. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  38725. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  38726. shapePath[p] = rotated;
  38727. }
  38728. shapePaths[index] = shapePath;
  38729. angle += angleStep;
  38730. index++;
  38731. }
  38732. // cap
  38733. var capPath = function (shapePath) {
  38734. var pointCap = Array();
  38735. var barycenter = BABYLON.Vector3.Zero();
  38736. var i;
  38737. for (i = 0; i < shapePath.length; i++) {
  38738. barycenter.addInPlace(shapePath[i]);
  38739. }
  38740. barycenter.scaleInPlace(1.0 / shapePath.length);
  38741. for (i = 0; i < shapePath.length; i++) {
  38742. pointCap.push(barycenter);
  38743. }
  38744. return pointCap;
  38745. };
  38746. switch (cap) {
  38747. case BABYLON.Mesh.NO_CAP:
  38748. break;
  38749. case BABYLON.Mesh.CAP_START:
  38750. shapePaths[0] = capPath(shapePaths[2]);
  38751. shapePaths[1] = shapePaths[2];
  38752. break;
  38753. case BABYLON.Mesh.CAP_END:
  38754. shapePaths[index] = shapePaths[index - 1];
  38755. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  38756. break;
  38757. case BABYLON.Mesh.CAP_ALL:
  38758. shapePaths[0] = capPath(shapePaths[2]);
  38759. shapePaths[1] = shapePaths[2];
  38760. shapePaths[index] = shapePaths[index - 1];
  38761. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  38762. break;
  38763. default:
  38764. break;
  38765. }
  38766. return shapePaths;
  38767. };
  38768. var path3D;
  38769. var pathArray;
  38770. if (instance) {
  38771. path3D = (instance.path3D).update(curve);
  38772. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  38773. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  38774. return instance;
  38775. }
  38776. // extruded shape creation
  38777. path3D = new BABYLON.Path3D(curve);
  38778. var newShapePaths = new Array();
  38779. cap = (cap < 0 || cap > 3) ? 0 : cap;
  38780. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  38781. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  38782. extrudedGeneric.pathArray = pathArray;
  38783. extrudedGeneric.path3D = path3D;
  38784. extrudedGeneric.cap = cap;
  38785. return extrudedGeneric;
  38786. };
  38787. return MeshBuilder;
  38788. }());
  38789. BABYLON.MeshBuilder = MeshBuilder;
  38790. })(BABYLON || (BABYLON = {}));
  38791. //# sourceMappingURL=babylon.meshBuilder.js.map
  38792. var BABYLON;
  38793. (function (BABYLON) {
  38794. var AudioEngine = (function () {
  38795. function AudioEngine() {
  38796. this._audioContext = null;
  38797. this._audioContextInitialized = false;
  38798. this.canUseWebAudio = false;
  38799. this.WarnedWebAudioUnsupported = false;
  38800. this.unlocked = false;
  38801. this.isMP3supported = false;
  38802. this.isOGGsupported = false;
  38803. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  38804. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  38805. this.canUseWebAudio = true;
  38806. }
  38807. var audioElem = document.createElement('audio');
  38808. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  38809. this.isMP3supported = true;
  38810. }
  38811. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  38812. this.isOGGsupported = true;
  38813. }
  38814. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  38815. this._unlockiOSaudio();
  38816. }
  38817. else {
  38818. this.unlocked = true;
  38819. }
  38820. }
  38821. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  38822. get: function () {
  38823. if (!this._audioContextInitialized) {
  38824. this._initializeAudioContext();
  38825. }
  38826. return this._audioContext;
  38827. },
  38828. enumerable: true,
  38829. configurable: true
  38830. });
  38831. AudioEngine.prototype._unlockiOSaudio = function () {
  38832. var _this = this;
  38833. var unlockaudio = function () {
  38834. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  38835. var source = _this.audioContext.createBufferSource();
  38836. source.buffer = buffer;
  38837. source.connect(_this.audioContext.destination);
  38838. source.start(0);
  38839. setTimeout(function () {
  38840. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  38841. _this.unlocked = true;
  38842. window.removeEventListener('touchend', unlockaudio, false);
  38843. if (_this.onAudioUnlocked) {
  38844. _this.onAudioUnlocked();
  38845. }
  38846. }
  38847. }, 0);
  38848. };
  38849. window.addEventListener('touchend', unlockaudio, false);
  38850. };
  38851. AudioEngine.prototype._initializeAudioContext = function () {
  38852. try {
  38853. if (this.canUseWebAudio) {
  38854. this._audioContext = new AudioContext();
  38855. // create a global volume gain node
  38856. this.masterGain = this._audioContext.createGain();
  38857. this.masterGain.gain.value = 1;
  38858. this.masterGain.connect(this._audioContext.destination);
  38859. this._audioContextInitialized = true;
  38860. }
  38861. }
  38862. catch (e) {
  38863. this.canUseWebAudio = false;
  38864. BABYLON.Tools.Error("Web Audio: " + e.message);
  38865. }
  38866. };
  38867. AudioEngine.prototype.dispose = function () {
  38868. if (this.canUseWebAudio && this._audioContextInitialized) {
  38869. if (this._connectedAnalyser) {
  38870. this._connectedAnalyser.stopDebugCanvas();
  38871. this._connectedAnalyser.dispose();
  38872. this.masterGain.disconnect();
  38873. this.masterGain.connect(this._audioContext.destination);
  38874. this._connectedAnalyser = null;
  38875. }
  38876. this.masterGain.gain.value = 1;
  38877. }
  38878. this.WarnedWebAudioUnsupported = false;
  38879. };
  38880. AudioEngine.prototype.getGlobalVolume = function () {
  38881. if (this.canUseWebAudio && this._audioContextInitialized) {
  38882. return this.masterGain.gain.value;
  38883. }
  38884. else {
  38885. return -1;
  38886. }
  38887. };
  38888. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  38889. if (this.canUseWebAudio && this._audioContextInitialized) {
  38890. this.masterGain.gain.value = newVolume;
  38891. }
  38892. };
  38893. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  38894. if (this._connectedAnalyser) {
  38895. this._connectedAnalyser.stopDebugCanvas();
  38896. }
  38897. if (this.canUseWebAudio && this._audioContextInitialized) {
  38898. this._connectedAnalyser = analyser;
  38899. this.masterGain.disconnect();
  38900. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  38901. }
  38902. };
  38903. return AudioEngine;
  38904. }());
  38905. BABYLON.AudioEngine = AudioEngine;
  38906. })(BABYLON || (BABYLON = {}));
  38907. //# sourceMappingURL=babylon.audioEngine.js.map
  38908. var BABYLON;
  38909. (function (BABYLON) {
  38910. var Sound = (function () {
  38911. /**
  38912. * Create a sound and attach it to a scene
  38913. * @param name Name of your sound
  38914. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  38915. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  38916. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  38917. */
  38918. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  38919. var _this = this;
  38920. this.autoplay = false;
  38921. this.loop = false;
  38922. this.useCustomAttenuation = false;
  38923. this.spatialSound = false;
  38924. this.refDistance = 1;
  38925. this.rolloffFactor = 1;
  38926. this.maxDistance = 100;
  38927. this.distanceModel = "linear";
  38928. this._panningModel = "equalpower";
  38929. this._playbackRate = 1;
  38930. this._streaming = false;
  38931. this._startTime = 0;
  38932. this._startOffset = 0;
  38933. this._position = BABYLON.Vector3.Zero();
  38934. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  38935. this._volume = 1;
  38936. this._isLoaded = false;
  38937. this._isReadyToPlay = false;
  38938. this.isPlaying = false;
  38939. this.isPaused = false;
  38940. this._isDirectional = false;
  38941. // Used if you'd like to create a directional sound.
  38942. // If not set, the sound will be omnidirectional
  38943. this._coneInnerAngle = 360;
  38944. this._coneOuterAngle = 360;
  38945. this._coneOuterGain = 0;
  38946. this._isOutputConnected = false;
  38947. this._urlType = "Unknown";
  38948. this.name = name;
  38949. this._scene = scene;
  38950. this._readyToPlayCallback = readyToPlayCallback;
  38951. // Default custom attenuation function is a linear attenuation
  38952. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  38953. if (currentDistance < maxDistance) {
  38954. return currentVolume * (1 - currentDistance / maxDistance);
  38955. }
  38956. else {
  38957. return 0;
  38958. }
  38959. };
  38960. if (options) {
  38961. this.autoplay = options.autoplay || false;
  38962. this.loop = options.loop || false;
  38963. // if volume === 0, we need another way to check this option
  38964. if (options.volume !== undefined) {
  38965. this._volume = options.volume;
  38966. }
  38967. this.spatialSound = options.spatialSound || false;
  38968. this.maxDistance = options.maxDistance || 100;
  38969. this.useCustomAttenuation = options.useCustomAttenuation || false;
  38970. this.rolloffFactor = options.rolloffFactor || 1;
  38971. this.refDistance = options.refDistance || 1;
  38972. this.distanceModel = options.distanceModel || "linear";
  38973. this._playbackRate = options.playbackRate || 1;
  38974. this._streaming = options.streaming || false;
  38975. }
  38976. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38977. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  38978. this._soundGain.gain.value = this._volume;
  38979. this._inputAudioNode = this._soundGain;
  38980. this._ouputAudioNode = this._soundGain;
  38981. if (this.spatialSound) {
  38982. this._createSpatialParameters();
  38983. }
  38984. this._scene.mainSoundTrack.AddSound(this);
  38985. var validParameter = true;
  38986. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  38987. if (urlOrArrayBuffer) {
  38988. if (typeof (urlOrArrayBuffer) === "string")
  38989. this._urlType = "String";
  38990. if (Array.isArray(urlOrArrayBuffer))
  38991. this._urlType = "Array";
  38992. if (urlOrArrayBuffer instanceof ArrayBuffer)
  38993. this._urlType = "ArrayBuffer";
  38994. var urls = [];
  38995. var codecSupportedFound = false;
  38996. switch (this._urlType) {
  38997. case "ArrayBuffer":
  38998. if (urlOrArrayBuffer.byteLength > 0) {
  38999. codecSupportedFound = true;
  39000. this._soundLoaded(urlOrArrayBuffer);
  39001. }
  39002. break;
  39003. case "String":
  39004. urls.push(urlOrArrayBuffer);
  39005. case "Array":
  39006. if (urls.length === 0)
  39007. urls = urlOrArrayBuffer;
  39008. // If we found a supported format, we load it immediately and stop the loop
  39009. for (var i = 0; i < urls.length; i++) {
  39010. var url = urls[i];
  39011. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  39012. codecSupportedFound = true;
  39013. }
  39014. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  39015. codecSupportedFound = true;
  39016. }
  39017. if (url.indexOf(".wav", url.length - 4) !== -1) {
  39018. codecSupportedFound = true;
  39019. }
  39020. if (codecSupportedFound) {
  39021. // Loading sound using XHR2
  39022. if (!this._streaming) {
  39023. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  39024. }
  39025. else {
  39026. this._htmlAudioElement = new Audio(url);
  39027. this._htmlAudioElement.controls = false;
  39028. this._htmlAudioElement.loop = this.loop;
  39029. this._htmlAudioElement.crossOrigin = "anonymous";
  39030. this._htmlAudioElement.preload = "auto";
  39031. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  39032. _this._isReadyToPlay = true;
  39033. if (_this.autoplay) {
  39034. _this.play();
  39035. }
  39036. if (_this._readyToPlayCallback) {
  39037. _this._readyToPlayCallback();
  39038. }
  39039. });
  39040. document.body.appendChild(this._htmlAudioElement);
  39041. }
  39042. break;
  39043. }
  39044. }
  39045. break;
  39046. default:
  39047. validParameter = false;
  39048. break;
  39049. }
  39050. if (!validParameter) {
  39051. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  39052. }
  39053. else {
  39054. if (!codecSupportedFound) {
  39055. this._isReadyToPlay = true;
  39056. // Simulating a ready to play event to avoid breaking code path
  39057. if (this._readyToPlayCallback) {
  39058. window.setTimeout(function () {
  39059. _this._readyToPlayCallback();
  39060. }, 1000);
  39061. }
  39062. }
  39063. }
  39064. }
  39065. }
  39066. else {
  39067. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  39068. this._scene.mainSoundTrack.AddSound(this);
  39069. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  39070. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  39071. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  39072. }
  39073. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  39074. if (this._readyToPlayCallback) {
  39075. window.setTimeout(function () {
  39076. _this._readyToPlayCallback();
  39077. }, 1000);
  39078. }
  39079. }
  39080. }
  39081. Sound.prototype.dispose = function () {
  39082. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  39083. if (this.isPlaying) {
  39084. this.stop();
  39085. }
  39086. this._isReadyToPlay = false;
  39087. if (this.soundTrackId === -1) {
  39088. this._scene.mainSoundTrack.RemoveSound(this);
  39089. }
  39090. else {
  39091. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  39092. }
  39093. if (this._soundGain) {
  39094. this._soundGain.disconnect();
  39095. this._soundGain = null;
  39096. }
  39097. if (this._soundPanner) {
  39098. this._soundPanner.disconnect();
  39099. this._soundPanner = null;
  39100. }
  39101. if (this._soundSource) {
  39102. this._soundSource.disconnect();
  39103. this._soundSource = null;
  39104. }
  39105. this._audioBuffer = null;
  39106. if (this._htmlAudioElement) {
  39107. this._htmlAudioElement.pause();
  39108. this._htmlAudioElement.src = "";
  39109. document.body.removeChild(this._htmlAudioElement);
  39110. }
  39111. if (this._connectedMesh) {
  39112. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39113. this._connectedMesh = null;
  39114. }
  39115. }
  39116. };
  39117. Sound.prototype.isReady = function () {
  39118. return this._isReadyToPlay;
  39119. };
  39120. Sound.prototype._soundLoaded = function (audioData) {
  39121. var _this = this;
  39122. this._isLoaded = true;
  39123. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  39124. _this._audioBuffer = buffer;
  39125. _this._isReadyToPlay = true;
  39126. if (_this.autoplay) {
  39127. _this.play();
  39128. }
  39129. if (_this._readyToPlayCallback) {
  39130. _this._readyToPlayCallback();
  39131. }
  39132. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  39133. };
  39134. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  39135. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39136. this._audioBuffer = audioBuffer;
  39137. this._isReadyToPlay = true;
  39138. }
  39139. };
  39140. Sound.prototype.updateOptions = function (options) {
  39141. if (options) {
  39142. this.loop = options.loop || this.loop;
  39143. this.maxDistance = options.maxDistance || this.maxDistance;
  39144. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  39145. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  39146. this.refDistance = options.refDistance || this.refDistance;
  39147. this.distanceModel = options.distanceModel || this.distanceModel;
  39148. this._playbackRate = options.playbackRate || this._playbackRate;
  39149. this._updateSpatialParameters();
  39150. if (this.isPlaying) {
  39151. if (this._streaming) {
  39152. this._htmlAudioElement.playbackRate = this._playbackRate;
  39153. }
  39154. else {
  39155. this._soundSource.playbackRate.value = this._playbackRate;
  39156. }
  39157. }
  39158. }
  39159. };
  39160. Sound.prototype._createSpatialParameters = function () {
  39161. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39162. if (this._scene.headphone) {
  39163. this._panningModel = "HRTF";
  39164. }
  39165. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  39166. this._updateSpatialParameters();
  39167. this._soundPanner.connect(this._ouputAudioNode);
  39168. this._inputAudioNode = this._soundPanner;
  39169. }
  39170. };
  39171. Sound.prototype._updateSpatialParameters = function () {
  39172. if (this.spatialSound) {
  39173. if (this.useCustomAttenuation) {
  39174. // Tricks to disable in a way embedded Web Audio attenuation
  39175. this._soundPanner.distanceModel = "linear";
  39176. this._soundPanner.maxDistance = Number.MAX_VALUE;
  39177. this._soundPanner.refDistance = 1;
  39178. this._soundPanner.rolloffFactor = 1;
  39179. this._soundPanner.panningModel = this._panningModel;
  39180. }
  39181. else {
  39182. this._soundPanner.distanceModel = this.distanceModel;
  39183. this._soundPanner.maxDistance = this.maxDistance;
  39184. this._soundPanner.refDistance = this.refDistance;
  39185. this._soundPanner.rolloffFactor = this.rolloffFactor;
  39186. this._soundPanner.panningModel = this._panningModel;
  39187. }
  39188. }
  39189. };
  39190. Sound.prototype.switchPanningModelToHRTF = function () {
  39191. this._panningModel = "HRTF";
  39192. this._switchPanningModel();
  39193. };
  39194. Sound.prototype.switchPanningModelToEqualPower = function () {
  39195. this._panningModel = "equalpower";
  39196. this._switchPanningModel();
  39197. };
  39198. Sound.prototype._switchPanningModel = function () {
  39199. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  39200. this._soundPanner.panningModel = this._panningModel;
  39201. }
  39202. };
  39203. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  39204. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39205. if (this._isOutputConnected) {
  39206. this._ouputAudioNode.disconnect();
  39207. }
  39208. this._ouputAudioNode.connect(soundTrackAudioNode);
  39209. this._isOutputConnected = true;
  39210. }
  39211. };
  39212. /**
  39213. * Transform this sound into a directional source
  39214. * @param coneInnerAngle Size of the inner cone in degree
  39215. * @param coneOuterAngle Size of the outer cone in degree
  39216. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  39217. */
  39218. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  39219. if (coneOuterAngle < coneInnerAngle) {
  39220. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  39221. return;
  39222. }
  39223. this._coneInnerAngle = coneInnerAngle;
  39224. this._coneOuterAngle = coneOuterAngle;
  39225. this._coneOuterGain = coneOuterGain;
  39226. this._isDirectional = true;
  39227. if (this.isPlaying && this.loop) {
  39228. this.stop();
  39229. this.play();
  39230. }
  39231. };
  39232. Sound.prototype.setPosition = function (newPosition) {
  39233. this._position = newPosition;
  39234. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  39235. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39236. }
  39237. };
  39238. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  39239. this._localDirection = newLocalDirection;
  39240. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  39241. this._updateDirection();
  39242. }
  39243. };
  39244. Sound.prototype._updateDirection = function () {
  39245. var mat = this._connectedMesh.getWorldMatrix();
  39246. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  39247. direction.normalize();
  39248. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  39249. };
  39250. Sound.prototype.updateDistanceFromListener = function () {
  39251. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  39252. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  39253. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  39254. }
  39255. };
  39256. Sound.prototype.setAttenuationFunction = function (callback) {
  39257. this._customAttenuationFunction = callback;
  39258. };
  39259. /**
  39260. * Play the sound
  39261. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  39262. * @param offset (optional) Start the sound setting it at a specific time
  39263. */
  39264. Sound.prototype.play = function (time, offset) {
  39265. var _this = this;
  39266. if (this._isReadyToPlay && this._scene.audioEnabled) {
  39267. try {
  39268. if (this._startOffset < 0) {
  39269. time = -this._startOffset;
  39270. this._startOffset = 0;
  39271. }
  39272. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39273. if (!this._soundSource || !this._streamingSource) {
  39274. if (this.spatialSound) {
  39275. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39276. if (this._isDirectional) {
  39277. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  39278. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  39279. this._soundPanner.coneOuterGain = this._coneOuterGain;
  39280. if (this._connectedMesh) {
  39281. this._updateDirection();
  39282. }
  39283. else {
  39284. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  39285. }
  39286. }
  39287. }
  39288. }
  39289. if (this._streaming) {
  39290. if (!this._streamingSource) {
  39291. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  39292. this._htmlAudioElement.onended = function () { _this._onended(); };
  39293. this._htmlAudioElement.playbackRate = this._playbackRate;
  39294. }
  39295. this._streamingSource.disconnect();
  39296. this._streamingSource.connect(this._inputAudioNode);
  39297. this._htmlAudioElement.play();
  39298. }
  39299. else {
  39300. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  39301. this._soundSource.buffer = this._audioBuffer;
  39302. this._soundSource.connect(this._inputAudioNode);
  39303. this._soundSource.loop = this.loop;
  39304. this._soundSource.playbackRate.value = this._playbackRate;
  39305. this._soundSource.onended = function () { _this._onended(); };
  39306. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  39307. }
  39308. this._startTime = startTime;
  39309. this.isPlaying = true;
  39310. this.isPaused = false;
  39311. }
  39312. catch (ex) {
  39313. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  39314. }
  39315. }
  39316. };
  39317. Sound.prototype._onended = function () {
  39318. this.isPlaying = false;
  39319. if (this.onended) {
  39320. this.onended();
  39321. }
  39322. };
  39323. /**
  39324. * Stop the sound
  39325. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  39326. */
  39327. Sound.prototype.stop = function (time) {
  39328. if (this.isPlaying) {
  39329. if (this._streaming) {
  39330. this._htmlAudioElement.pause();
  39331. // Test needed for Firefox or it will generate an Invalid State Error
  39332. if (this._htmlAudioElement.currentTime > 0) {
  39333. this._htmlAudioElement.currentTime = 0;
  39334. }
  39335. }
  39336. else {
  39337. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39338. this._soundSource.stop(stopTime);
  39339. this._soundSource.onended = null;
  39340. if (!this.isPaused) {
  39341. this._startOffset = 0;
  39342. }
  39343. }
  39344. this.isPlaying = false;
  39345. }
  39346. };
  39347. Sound.prototype.pause = function () {
  39348. if (this.isPlaying) {
  39349. this.isPaused = true;
  39350. if (this._streaming) {
  39351. this._htmlAudioElement.pause();
  39352. }
  39353. else {
  39354. this.stop(0);
  39355. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  39356. }
  39357. }
  39358. };
  39359. Sound.prototype.setVolume = function (newVolume, time) {
  39360. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39361. if (time) {
  39362. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  39363. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  39364. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  39365. }
  39366. else {
  39367. this._soundGain.gain.value = newVolume;
  39368. }
  39369. }
  39370. this._volume = newVolume;
  39371. };
  39372. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  39373. this._playbackRate = newPlaybackRate;
  39374. if (this.isPlaying) {
  39375. if (this._streaming) {
  39376. this._htmlAudioElement.playbackRate = this._playbackRate;
  39377. }
  39378. else {
  39379. this._soundSource.playbackRate.value = this._playbackRate;
  39380. }
  39381. }
  39382. };
  39383. Sound.prototype.getVolume = function () {
  39384. return this._volume;
  39385. };
  39386. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  39387. var _this = this;
  39388. if (this._connectedMesh) {
  39389. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39390. this._registerFunc = null;
  39391. }
  39392. this._connectedMesh = meshToConnectTo;
  39393. if (!this.spatialSound) {
  39394. this.spatialSound = true;
  39395. this._createSpatialParameters();
  39396. if (this.isPlaying && this.loop) {
  39397. this.stop();
  39398. this.play();
  39399. }
  39400. }
  39401. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  39402. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  39403. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  39404. };
  39405. Sound.prototype.detachFromMesh = function () {
  39406. if (this._connectedMesh) {
  39407. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39408. this._registerFunc = null;
  39409. this._connectedMesh = null;
  39410. }
  39411. };
  39412. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  39413. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  39414. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  39415. this._updateDirection();
  39416. }
  39417. };
  39418. Sound.prototype.clone = function () {
  39419. var _this = this;
  39420. if (!this._streaming) {
  39421. var setBufferAndRun = function () {
  39422. if (_this._isReadyToPlay) {
  39423. clonedSound._audioBuffer = _this.getAudioBuffer();
  39424. clonedSound._isReadyToPlay = true;
  39425. if (clonedSound.autoplay) {
  39426. clonedSound.play();
  39427. }
  39428. }
  39429. else {
  39430. window.setTimeout(setBufferAndRun, 300);
  39431. }
  39432. };
  39433. var currentOptions = {
  39434. autoplay: this.autoplay, loop: this.loop,
  39435. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  39436. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  39437. refDistance: this.refDistance, distanceModel: this.distanceModel
  39438. };
  39439. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  39440. if (this.useCustomAttenuation) {
  39441. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  39442. }
  39443. clonedSound.setPosition(this._position);
  39444. clonedSound.setPlaybackRate(this._playbackRate);
  39445. setBufferAndRun();
  39446. return clonedSound;
  39447. }
  39448. else {
  39449. return null;
  39450. }
  39451. };
  39452. Sound.prototype.getAudioBuffer = function () {
  39453. return this._audioBuffer;
  39454. };
  39455. Sound.prototype.serialize = function () {
  39456. var serializationObject = {
  39457. name: this.name,
  39458. url: this.name,
  39459. autoplay: this.autoplay,
  39460. loop: this.loop,
  39461. volume: this._volume,
  39462. spatialSound: this.spatialSound,
  39463. maxDistance: this.maxDistance,
  39464. rolloffFactor: this.rolloffFactor,
  39465. refDistance: this.refDistance,
  39466. distanceModel: this.distanceModel,
  39467. playbackRate: this._playbackRate,
  39468. panningModel: this._panningModel,
  39469. soundTrackId: this.soundTrackId
  39470. };
  39471. if (this.spatialSound) {
  39472. if (this._connectedMesh)
  39473. serializationObject.connectedMeshId = this._connectedMesh.id;
  39474. serializationObject.position = this._position.asArray();
  39475. serializationObject.refDistance = this.refDistance;
  39476. serializationObject.distanceModel = this.distanceModel;
  39477. serializationObject.isDirectional = this._isDirectional;
  39478. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  39479. serializationObject.coneInnerAngle = this._coneInnerAngle;
  39480. serializationObject.coneOuterAngle = this._coneOuterAngle;
  39481. serializationObject.coneOuterGain = this._coneOuterGain;
  39482. }
  39483. return serializationObject;
  39484. };
  39485. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  39486. var soundName = parsedSound.name;
  39487. var soundUrl;
  39488. if (parsedSound.url) {
  39489. soundUrl = rootUrl + parsedSound.url;
  39490. }
  39491. else {
  39492. soundUrl = rootUrl + soundName;
  39493. }
  39494. var options = {
  39495. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  39496. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  39497. rolloffFactor: parsedSound.rolloffFactor,
  39498. refDistance: parsedSound.refDistance,
  39499. distanceModel: parsedSound.distanceModel,
  39500. playbackRate: parsedSound.playbackRate
  39501. };
  39502. var newSound;
  39503. if (!sourceSound) {
  39504. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  39505. scene._addPendingData(newSound);
  39506. }
  39507. else {
  39508. var setBufferAndRun = function () {
  39509. if (sourceSound._isReadyToPlay) {
  39510. newSound._audioBuffer = sourceSound.getAudioBuffer();
  39511. newSound._isReadyToPlay = true;
  39512. if (newSound.autoplay) {
  39513. newSound.play();
  39514. }
  39515. }
  39516. else {
  39517. window.setTimeout(setBufferAndRun, 300);
  39518. }
  39519. };
  39520. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  39521. setBufferAndRun();
  39522. }
  39523. if (parsedSound.position) {
  39524. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  39525. newSound.setPosition(soundPosition);
  39526. }
  39527. if (parsedSound.isDirectional) {
  39528. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  39529. if (parsedSound.localDirectionToMesh) {
  39530. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  39531. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  39532. }
  39533. }
  39534. if (parsedSound.connectedMeshId) {
  39535. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  39536. if (connectedMesh) {
  39537. newSound.attachToMesh(connectedMesh);
  39538. }
  39539. }
  39540. return newSound;
  39541. };
  39542. return Sound;
  39543. }());
  39544. BABYLON.Sound = Sound;
  39545. })(BABYLON || (BABYLON = {}));
  39546. //# sourceMappingURL=babylon.sound.js.map
  39547. var BABYLON;
  39548. (function (BABYLON) {
  39549. var SoundTrack = (function () {
  39550. function SoundTrack(scene, options) {
  39551. this.id = -1;
  39552. this._isMainTrack = false;
  39553. this._isInitialized = false;
  39554. this._scene = scene;
  39555. this.soundCollection = new Array();
  39556. this._options = options;
  39557. if (!this._isMainTrack) {
  39558. this._scene.soundTracks.push(this);
  39559. this.id = this._scene.soundTracks.length - 1;
  39560. }
  39561. }
  39562. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  39563. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39564. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  39565. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  39566. if (this._options) {
  39567. if (this._options.volume) {
  39568. this._outputAudioNode.gain.value = this._options.volume;
  39569. }
  39570. if (this._options.mainTrack) {
  39571. this._isMainTrack = this._options.mainTrack;
  39572. }
  39573. }
  39574. this._isInitialized = true;
  39575. }
  39576. };
  39577. SoundTrack.prototype.dispose = function () {
  39578. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39579. if (this._connectedAnalyser) {
  39580. this._connectedAnalyser.stopDebugCanvas();
  39581. }
  39582. while (this.soundCollection.length) {
  39583. this.soundCollection[0].dispose();
  39584. }
  39585. if (this._outputAudioNode) {
  39586. this._outputAudioNode.disconnect();
  39587. }
  39588. this._outputAudioNode = null;
  39589. }
  39590. };
  39591. SoundTrack.prototype.AddSound = function (sound) {
  39592. if (!this._isInitialized) {
  39593. this._initializeSoundTrackAudioGraph();
  39594. }
  39595. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39596. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  39597. }
  39598. if (sound.soundTrackId) {
  39599. if (sound.soundTrackId === -1) {
  39600. this._scene.mainSoundTrack.RemoveSound(sound);
  39601. }
  39602. else {
  39603. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  39604. }
  39605. }
  39606. this.soundCollection.push(sound);
  39607. sound.soundTrackId = this.id;
  39608. };
  39609. SoundTrack.prototype.RemoveSound = function (sound) {
  39610. var index = this.soundCollection.indexOf(sound);
  39611. if (index !== -1) {
  39612. this.soundCollection.splice(index, 1);
  39613. }
  39614. };
  39615. SoundTrack.prototype.setVolume = function (newVolume) {
  39616. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39617. this._outputAudioNode.gain.value = newVolume;
  39618. }
  39619. };
  39620. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  39621. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39622. for (var i = 0; i < this.soundCollection.length; i++) {
  39623. this.soundCollection[i].switchPanningModelToHRTF();
  39624. }
  39625. }
  39626. };
  39627. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  39628. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39629. for (var i = 0; i < this.soundCollection.length; i++) {
  39630. this.soundCollection[i].switchPanningModelToEqualPower();
  39631. }
  39632. }
  39633. };
  39634. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  39635. if (this._connectedAnalyser) {
  39636. this._connectedAnalyser.stopDebugCanvas();
  39637. }
  39638. this._connectedAnalyser = analyser;
  39639. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39640. this._outputAudioNode.disconnect();
  39641. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  39642. }
  39643. };
  39644. return SoundTrack;
  39645. }());
  39646. BABYLON.SoundTrack = SoundTrack;
  39647. })(BABYLON || (BABYLON = {}));
  39648. //# sourceMappingURL=babylon.soundtrack.js.map
  39649. var BABYLON;
  39650. (function (BABYLON) {
  39651. var Analyser = (function () {
  39652. function Analyser(scene) {
  39653. this.SMOOTHING = 0.75;
  39654. this.FFT_SIZE = 512;
  39655. this.BARGRAPHAMPLITUDE = 256;
  39656. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  39657. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  39658. this._scene = scene;
  39659. this._audioEngine = BABYLON.Engine.audioEngine;
  39660. if (this._audioEngine.canUseWebAudio) {
  39661. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  39662. this._webAudioAnalyser.minDecibels = -140;
  39663. this._webAudioAnalyser.maxDecibels = 0;
  39664. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39665. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39666. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  39667. }
  39668. }
  39669. Analyser.prototype.getFrequencyBinCount = function () {
  39670. if (this._audioEngine.canUseWebAudio) {
  39671. return this._webAudioAnalyser.frequencyBinCount;
  39672. }
  39673. else {
  39674. return 0;
  39675. }
  39676. };
  39677. Analyser.prototype.getByteFrequencyData = function () {
  39678. if (this._audioEngine.canUseWebAudio) {
  39679. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39680. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39681. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  39682. }
  39683. return this._byteFreqs;
  39684. };
  39685. Analyser.prototype.getByteTimeDomainData = function () {
  39686. if (this._audioEngine.canUseWebAudio) {
  39687. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39688. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39689. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  39690. }
  39691. return this._byteTime;
  39692. };
  39693. Analyser.prototype.getFloatFrequencyData = function () {
  39694. if (this._audioEngine.canUseWebAudio) {
  39695. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39696. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39697. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  39698. }
  39699. return this._floatFreqs;
  39700. };
  39701. Analyser.prototype.drawDebugCanvas = function () {
  39702. var _this = this;
  39703. if (this._audioEngine.canUseWebAudio) {
  39704. if (!this._debugCanvas) {
  39705. this._debugCanvas = document.createElement("canvas");
  39706. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  39707. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  39708. this._debugCanvas.style.position = "absolute";
  39709. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  39710. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  39711. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  39712. document.body.appendChild(this._debugCanvas);
  39713. this._registerFunc = function () {
  39714. _this.drawDebugCanvas();
  39715. };
  39716. this._scene.registerBeforeRender(this._registerFunc);
  39717. }
  39718. if (this._registerFunc) {
  39719. var workingArray = this.getByteFrequencyData();
  39720. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  39721. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  39722. // Draw the frequency domain chart.
  39723. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  39724. var value = workingArray[i];
  39725. var percent = value / this.BARGRAPHAMPLITUDE;
  39726. var height = this.DEBUGCANVASSIZE.height * percent;
  39727. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  39728. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  39729. var hue = i / this.getFrequencyBinCount() * 360;
  39730. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  39731. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  39732. }
  39733. }
  39734. }
  39735. };
  39736. Analyser.prototype.stopDebugCanvas = function () {
  39737. if (this._debugCanvas) {
  39738. this._scene.unregisterBeforeRender(this._registerFunc);
  39739. this._registerFunc = null;
  39740. document.body.removeChild(this._debugCanvas);
  39741. this._debugCanvas = null;
  39742. this._debugCanvasContext = null;
  39743. }
  39744. };
  39745. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  39746. if (this._audioEngine.canUseWebAudio) {
  39747. inputAudioNode.connect(this._webAudioAnalyser);
  39748. this._webAudioAnalyser.connect(outputAudioNode);
  39749. }
  39750. };
  39751. Analyser.prototype.dispose = function () {
  39752. if (this._audioEngine.canUseWebAudio) {
  39753. this._webAudioAnalyser.disconnect();
  39754. }
  39755. };
  39756. return Analyser;
  39757. }());
  39758. BABYLON.Analyser = Analyser;
  39759. })(BABYLON || (BABYLON = {}));
  39760. //# sourceMappingURL=babylon.analyser.js.map
  39761. var BABYLON;
  39762. (function (BABYLON) {
  39763. var CubeTexture = (function (_super) {
  39764. __extends(CubeTexture, _super);
  39765. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  39766. if (onLoad === void 0) { onLoad = null; }
  39767. if (onError === void 0) { onError = null; }
  39768. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  39769. var _this = _super.call(this, scene) || this;
  39770. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  39771. _this.name = rootUrl;
  39772. _this.url = rootUrl;
  39773. _this._noMipmap = noMipmap;
  39774. _this.hasAlpha = false;
  39775. _this._format = format;
  39776. if (!rootUrl && !files) {
  39777. return _this;
  39778. }
  39779. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  39780. if (!files) {
  39781. if (!extensions) {
  39782. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  39783. }
  39784. files = [];
  39785. for (var index = 0; index < extensions.length; index++) {
  39786. files.push(rootUrl + extensions[index]);
  39787. }
  39788. _this._extensions = extensions;
  39789. }
  39790. _this._files = files;
  39791. if (!_this._texture) {
  39792. if (!scene.useDelayedTextureLoading) {
  39793. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  39794. }
  39795. else {
  39796. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39797. }
  39798. }
  39799. else if (onLoad) {
  39800. if (_this._texture.isReady) {
  39801. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  39802. }
  39803. else {
  39804. _this._texture.onLoadedCallbacks.push(onLoad);
  39805. }
  39806. }
  39807. _this.isCube = true;
  39808. _this._textureMatrix = BABYLON.Matrix.Identity();
  39809. return _this;
  39810. }
  39811. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  39812. return new CubeTexture("", scene, null, noMipmap, files);
  39813. };
  39814. // Methods
  39815. CubeTexture.prototype.delayLoad = function () {
  39816. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  39817. return;
  39818. }
  39819. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39820. this._texture = this._getFromCache(this.url, this._noMipmap);
  39821. if (!this._texture) {
  39822. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  39823. }
  39824. };
  39825. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  39826. return this._textureMatrix;
  39827. };
  39828. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  39829. var texture = BABYLON.SerializationHelper.Parse(function () {
  39830. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  39831. }, parsedTexture, scene);
  39832. // Animations
  39833. if (parsedTexture.animations) {
  39834. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  39835. var parsedAnimation = parsedTexture.animations[animationIndex];
  39836. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  39837. }
  39838. }
  39839. return texture;
  39840. };
  39841. CubeTexture.prototype.clone = function () {
  39842. var _this = this;
  39843. return BABYLON.SerializationHelper.Clone(function () {
  39844. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  39845. }, this);
  39846. };
  39847. return CubeTexture;
  39848. }(BABYLON.BaseTexture));
  39849. BABYLON.CubeTexture = CubeTexture;
  39850. })(BABYLON || (BABYLON = {}));
  39851. //# sourceMappingURL=babylon.cubeTexture.js.map
  39852. var BABYLON;
  39853. (function (BABYLON) {
  39854. var RenderTargetTexture = (function (_super) {
  39855. __extends(RenderTargetTexture, _super);
  39856. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  39857. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  39858. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  39859. if (isCube === void 0) { isCube = false; }
  39860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39861. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  39862. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  39863. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  39864. _this.isCube = isCube;
  39865. /**
  39866. * Use this list to define the list of mesh you want to render.
  39867. */
  39868. _this.renderList = new Array();
  39869. _this.renderParticles = true;
  39870. _this.renderSprites = false;
  39871. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  39872. // Events
  39873. /**
  39874. * An event triggered when the texture is unbind.
  39875. * @type {BABYLON.Observable}
  39876. */
  39877. _this.onAfterUnbindObservable = new BABYLON.Observable();
  39878. /**
  39879. * An event triggered before rendering the texture
  39880. * @type {BABYLON.Observable}
  39881. */
  39882. _this.onBeforeRenderObservable = new BABYLON.Observable();
  39883. /**
  39884. * An event triggered after rendering the texture
  39885. * @type {BABYLON.Observable}
  39886. */
  39887. _this.onAfterRenderObservable = new BABYLON.Observable();
  39888. /**
  39889. * An event triggered after the texture clear
  39890. * @type {BABYLON.Observable}
  39891. */
  39892. _this.onClearObservable = new BABYLON.Observable();
  39893. _this._currentRefreshId = -1;
  39894. _this._refreshRate = 1;
  39895. _this._samples = 1;
  39896. _this.name = name;
  39897. _this.isRenderTarget = true;
  39898. _this._size = size;
  39899. _this._generateMipMaps = generateMipMaps;
  39900. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  39901. _this._renderTargetOptions = {
  39902. generateMipMaps: generateMipMaps,
  39903. type: type,
  39904. samplingMode: samplingMode,
  39905. generateDepthBuffer: generateDepthBuffer,
  39906. generateStencilBuffer: generateStencilBuffer
  39907. };
  39908. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  39909. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39910. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39911. }
  39912. if (isCube) {
  39913. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  39914. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  39915. _this._textureMatrix = BABYLON.Matrix.Identity();
  39916. }
  39917. else {
  39918. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  39919. }
  39920. // Rendering groups
  39921. _this._renderingManager = new BABYLON.RenderingManager(scene);
  39922. return _this;
  39923. }
  39924. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  39925. get: function () {
  39926. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  39927. },
  39928. enumerable: true,
  39929. configurable: true
  39930. });
  39931. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  39932. get: function () {
  39933. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  39934. },
  39935. enumerable: true,
  39936. configurable: true
  39937. });
  39938. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  39939. get: function () {
  39940. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  39941. },
  39942. enumerable: true,
  39943. configurable: true
  39944. });
  39945. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  39946. set: function (callback) {
  39947. if (this._onAfterUnbindObserver) {
  39948. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  39949. }
  39950. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  39951. },
  39952. enumerable: true,
  39953. configurable: true
  39954. });
  39955. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  39956. set: function (callback) {
  39957. if (this._onBeforeRenderObserver) {
  39958. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  39959. }
  39960. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  39961. },
  39962. enumerable: true,
  39963. configurable: true
  39964. });
  39965. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  39966. set: function (callback) {
  39967. if (this._onAfterRenderObserver) {
  39968. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  39969. }
  39970. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  39971. },
  39972. enumerable: true,
  39973. configurable: true
  39974. });
  39975. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  39976. set: function (callback) {
  39977. if (this._onClearObserver) {
  39978. this.onClearObservable.remove(this._onClearObserver);
  39979. }
  39980. this._onClearObserver = this.onClearObservable.add(callback);
  39981. },
  39982. enumerable: true,
  39983. configurable: true
  39984. });
  39985. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  39986. get: function () {
  39987. return this._samples;
  39988. },
  39989. set: function (value) {
  39990. if (this._samples === value) {
  39991. return;
  39992. }
  39993. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  39994. },
  39995. enumerable: true,
  39996. configurable: true
  39997. });
  39998. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  39999. this._currentRefreshId = -1;
  40000. };
  40001. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  40002. get: function () {
  40003. return this._refreshRate;
  40004. },
  40005. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  40006. set: function (value) {
  40007. this._refreshRate = value;
  40008. this.resetRefreshCounter();
  40009. },
  40010. enumerable: true,
  40011. configurable: true
  40012. });
  40013. RenderTargetTexture.prototype._shouldRender = function () {
  40014. if (this._currentRefreshId === -1) {
  40015. this._currentRefreshId = 1;
  40016. return true;
  40017. }
  40018. if (this.refreshRate === this._currentRefreshId) {
  40019. this._currentRefreshId = 1;
  40020. return true;
  40021. }
  40022. this._currentRefreshId++;
  40023. return false;
  40024. };
  40025. RenderTargetTexture.prototype.isReady = function () {
  40026. if (!this.getScene().renderTargetsEnabled) {
  40027. return false;
  40028. }
  40029. return _super.prototype.isReady.call(this);
  40030. };
  40031. RenderTargetTexture.prototype.getRenderSize = function () {
  40032. return this._size;
  40033. };
  40034. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  40035. get: function () {
  40036. return true;
  40037. },
  40038. enumerable: true,
  40039. configurable: true
  40040. });
  40041. RenderTargetTexture.prototype.scale = function (ratio) {
  40042. var newSize = this._size * ratio;
  40043. this.resize(newSize);
  40044. };
  40045. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  40046. if (this.isCube) {
  40047. return this._textureMatrix;
  40048. }
  40049. return _super.prototype.getReflectionTextureMatrix.call(this);
  40050. };
  40051. RenderTargetTexture.prototype.resize = function (size) {
  40052. this.releaseInternalTexture();
  40053. if (this.isCube) {
  40054. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  40055. }
  40056. else {
  40057. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  40058. }
  40059. };
  40060. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  40061. var scene = this.getScene();
  40062. var engine = scene.getEngine();
  40063. if (this.useCameraPostProcesses !== undefined) {
  40064. useCameraPostProcess = this.useCameraPostProcesses;
  40065. }
  40066. if (this._waitingRenderList) {
  40067. this.renderList = [];
  40068. for (var index = 0; index < this._waitingRenderList.length; index++) {
  40069. var id = this._waitingRenderList[index];
  40070. this.renderList.push(scene.getMeshByID(id));
  40071. }
  40072. delete this._waitingRenderList;
  40073. }
  40074. // Is predicate defined?
  40075. if (this.renderListPredicate) {
  40076. this.renderList.splice(0); // Clear previous renderList
  40077. var sceneMeshes = this.getScene().meshes;
  40078. for (var index = 0; index < sceneMeshes.length; index++) {
  40079. var mesh = sceneMeshes[index];
  40080. if (this.renderListPredicate(mesh)) {
  40081. this.renderList.push(mesh);
  40082. }
  40083. }
  40084. }
  40085. if (this.renderList && this.renderList.length === 0) {
  40086. return;
  40087. }
  40088. // Set custom projection.
  40089. // Needs to be before binding to prevent changing the aspect ratio.
  40090. if (this.activeCamera) {
  40091. engine.setViewport(this.activeCamera.viewport);
  40092. if (this.activeCamera !== scene.activeCamera) {
  40093. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  40094. }
  40095. }
  40096. else {
  40097. engine.setViewport(scene.activeCamera.viewport);
  40098. }
  40099. // Prepare renderingManager
  40100. this._renderingManager.reset();
  40101. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  40102. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  40103. var sceneRenderId = scene.getRenderId();
  40104. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  40105. var mesh = currentRenderList[meshIndex];
  40106. if (mesh) {
  40107. if (!mesh.isReady()) {
  40108. // Reset _currentRefreshId
  40109. this.resetRefreshCounter();
  40110. continue;
  40111. }
  40112. mesh._preActivateForIntermediateRendering(sceneRenderId);
  40113. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  40114. mesh._activate(sceneRenderId);
  40115. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40116. var subMesh = mesh.subMeshes[subIndex];
  40117. scene._activeIndices.addCount(subMesh.indexCount, false);
  40118. this._renderingManager.dispatch(subMesh);
  40119. }
  40120. }
  40121. }
  40122. }
  40123. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  40124. var particleSystem = scene.particleSystems[particleIndex];
  40125. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  40126. continue;
  40127. }
  40128. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  40129. this._renderingManager.dispatchParticles(particleSystem);
  40130. }
  40131. }
  40132. if (this.isCube) {
  40133. for (var face = 0; face < 6; face++) {
  40134. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  40135. scene.incrementRenderId();
  40136. scene.resetCachedMaterial();
  40137. }
  40138. }
  40139. else {
  40140. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  40141. }
  40142. this.onAfterUnbindObservable.notifyObservers(this);
  40143. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  40144. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  40145. }
  40146. engine.setViewport(scene.activeCamera.viewport);
  40147. scene.resetCachedMaterial();
  40148. };
  40149. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  40150. var _this = this;
  40151. var scene = this.getScene();
  40152. var engine = scene.getEngine();
  40153. // Bind
  40154. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  40155. if (this.isCube) {
  40156. engine.bindFramebuffer(this._texture, faceIndex);
  40157. }
  40158. else {
  40159. engine.bindFramebuffer(this._texture);
  40160. }
  40161. }
  40162. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  40163. // Clear
  40164. if (this.onClearObservable.hasObservers()) {
  40165. this.onClearObservable.notifyObservers(engine);
  40166. }
  40167. else {
  40168. engine.clear(scene.clearColor, true, true, true);
  40169. }
  40170. if (!this._doNotChangeAspectRatio) {
  40171. scene.updateTransformMatrix(true);
  40172. }
  40173. // Render
  40174. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  40175. if (useCameraPostProcess) {
  40176. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  40177. }
  40178. if (!this._doNotChangeAspectRatio) {
  40179. scene.updateTransformMatrix(true);
  40180. }
  40181. // Dump ?
  40182. if (dumpForDebug) {
  40183. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  40184. }
  40185. // Unbind
  40186. if (!this.isCube || faceIndex === 5) {
  40187. if (this.isCube) {
  40188. if (faceIndex === 5) {
  40189. engine.generateMipMapsForCubemap(this._texture);
  40190. }
  40191. }
  40192. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  40193. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  40194. });
  40195. }
  40196. else {
  40197. this.onAfterRenderObservable.notifyObservers(faceIndex);
  40198. }
  40199. };
  40200. /**
  40201. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  40202. * This allowed control for front to back rendering or reversly depending of the special needs.
  40203. *
  40204. * @param renderingGroupId The rendering group id corresponding to its index
  40205. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  40206. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  40207. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  40208. */
  40209. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  40210. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  40211. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  40212. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  40213. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  40214. };
  40215. /**
  40216. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  40217. *
  40218. * @param renderingGroupId The rendering group id corresponding to its index
  40219. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  40220. */
  40221. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  40222. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  40223. };
  40224. RenderTargetTexture.prototype.clone = function () {
  40225. var textureSize = this.getSize();
  40226. 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);
  40227. // Base texture
  40228. newTexture.hasAlpha = this.hasAlpha;
  40229. newTexture.level = this.level;
  40230. // RenderTarget Texture
  40231. newTexture.coordinatesMode = this.coordinatesMode;
  40232. newTexture.renderList = this.renderList.slice(0);
  40233. return newTexture;
  40234. };
  40235. RenderTargetTexture.prototype.serialize = function () {
  40236. if (!this.name) {
  40237. return null;
  40238. }
  40239. var serializationObject = _super.prototype.serialize.call(this);
  40240. serializationObject.renderTargetSize = this.getRenderSize();
  40241. serializationObject.renderList = [];
  40242. for (var index = 0; index < this.renderList.length; index++) {
  40243. serializationObject.renderList.push(this.renderList[index].id);
  40244. }
  40245. return serializationObject;
  40246. };
  40247. return RenderTargetTexture;
  40248. }(BABYLON.Texture));
  40249. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  40250. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  40251. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  40252. BABYLON.RenderTargetTexture = RenderTargetTexture;
  40253. })(BABYLON || (BABYLON = {}));
  40254. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  40255. /// <reference path="babylon.renderTargetTexture.ts" />
  40256. var BABYLON;
  40257. (function (BABYLON) {
  40258. var MirrorTexture = (function (_super) {
  40259. __extends(MirrorTexture, _super);
  40260. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  40261. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40262. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40263. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  40264. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  40265. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  40266. _this._transformMatrix = BABYLON.Matrix.Zero();
  40267. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  40268. _this.onBeforeRenderObservable.add(function () {
  40269. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  40270. _this._savedViewMatrix = scene.getViewMatrix();
  40271. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  40272. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  40273. scene.clipPlane = _this.mirrorPlane;
  40274. scene.getEngine().cullBackFaces = false;
  40275. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  40276. });
  40277. _this.onAfterRenderObservable.add(function () {
  40278. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  40279. scene.getEngine().cullBackFaces = true;
  40280. scene._mirroredCameraPosition = null;
  40281. delete scene.clipPlane;
  40282. });
  40283. return _this;
  40284. }
  40285. MirrorTexture.prototype.clone = function () {
  40286. var textureSize = this.getSize();
  40287. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  40288. // Base texture
  40289. newTexture.hasAlpha = this.hasAlpha;
  40290. newTexture.level = this.level;
  40291. // Mirror Texture
  40292. newTexture.mirrorPlane = this.mirrorPlane.clone();
  40293. newTexture.renderList = this.renderList.slice(0);
  40294. return newTexture;
  40295. };
  40296. MirrorTexture.prototype.serialize = function () {
  40297. if (!this.name) {
  40298. return null;
  40299. }
  40300. var serializationObject = _super.prototype.serialize.call(this);
  40301. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  40302. return serializationObject;
  40303. };
  40304. return MirrorTexture;
  40305. }(BABYLON.RenderTargetTexture));
  40306. BABYLON.MirrorTexture = MirrorTexture;
  40307. })(BABYLON || (BABYLON = {}));
  40308. //# sourceMappingURL=babylon.mirrorTexture.js.map
  40309. /// <reference path="babylon.renderTargetTexture.ts" />
  40310. var BABYLON;
  40311. (function (BABYLON) {
  40312. /**
  40313. * Creates a refraction texture used by refraction channel of the standard material.
  40314. * @param name the texture name
  40315. * @param size size of the underlying texture
  40316. * @param scene root scene
  40317. */
  40318. var RefractionTexture = (function (_super) {
  40319. __extends(RefractionTexture, _super);
  40320. function RefractionTexture(name, size, scene, generateMipMaps) {
  40321. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  40322. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  40323. _this.depth = 2.0;
  40324. _this.onBeforeRenderObservable.add(function () {
  40325. scene.clipPlane = _this.refractionPlane;
  40326. });
  40327. _this.onAfterRenderObservable.add(function () {
  40328. delete scene.clipPlane;
  40329. });
  40330. return _this;
  40331. }
  40332. RefractionTexture.prototype.clone = function () {
  40333. var textureSize = this.getSize();
  40334. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  40335. // Base texture
  40336. newTexture.hasAlpha = this.hasAlpha;
  40337. newTexture.level = this.level;
  40338. // Refraction Texture
  40339. newTexture.refractionPlane = this.refractionPlane.clone();
  40340. newTexture.renderList = this.renderList.slice(0);
  40341. newTexture.depth = this.depth;
  40342. return newTexture;
  40343. };
  40344. RefractionTexture.prototype.serialize = function () {
  40345. if (!this.name) {
  40346. return null;
  40347. }
  40348. var serializationObject = _super.prototype.serialize.call(this);
  40349. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  40350. serializationObject.depth = this.depth;
  40351. return serializationObject;
  40352. };
  40353. return RefractionTexture;
  40354. }(BABYLON.RenderTargetTexture));
  40355. BABYLON.RefractionTexture = RefractionTexture;
  40356. })(BABYLON || (BABYLON = {}));
  40357. //# sourceMappingURL=babylon.refractionTexture.js.map
  40358. /// <reference path="babylon.texture.ts" />
  40359. var BABYLON;
  40360. (function (BABYLON) {
  40361. var DynamicTexture = (function (_super) {
  40362. __extends(DynamicTexture, _super);
  40363. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  40364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40365. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  40366. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  40367. _this.name = name;
  40368. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40369. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40370. _this._generateMipMaps = generateMipMaps;
  40371. if (options.getContext) {
  40372. _this._canvas = options;
  40373. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  40374. }
  40375. else {
  40376. _this._canvas = document.createElement("canvas");
  40377. if (options.width) {
  40378. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  40379. }
  40380. else {
  40381. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  40382. }
  40383. }
  40384. var textureSize = _this.getSize();
  40385. _this._canvas.width = textureSize.width;
  40386. _this._canvas.height = textureSize.height;
  40387. _this._context = _this._canvas.getContext("2d");
  40388. return _this;
  40389. }
  40390. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  40391. get: function () {
  40392. return true;
  40393. },
  40394. enumerable: true,
  40395. configurable: true
  40396. });
  40397. DynamicTexture.prototype.scale = function (ratio) {
  40398. var textureSize = this.getSize();
  40399. textureSize.width *= ratio;
  40400. textureSize.height *= ratio;
  40401. this._canvas.width = textureSize.width;
  40402. this._canvas.height = textureSize.height;
  40403. this.releaseInternalTexture();
  40404. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  40405. };
  40406. DynamicTexture.prototype.getContext = function () {
  40407. return this._context;
  40408. };
  40409. DynamicTexture.prototype.clear = function () {
  40410. var size = this.getSize();
  40411. this._context.fillRect(0, 0, size.width, size.height);
  40412. };
  40413. DynamicTexture.prototype.update = function (invertY) {
  40414. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  40415. };
  40416. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  40417. if (update === void 0) { update = true; }
  40418. var size = this.getSize();
  40419. if (clearColor) {
  40420. this._context.fillStyle = clearColor;
  40421. this._context.fillRect(0, 0, size.width, size.height);
  40422. }
  40423. this._context.font = font;
  40424. if (x === null || x === undefined) {
  40425. var textSize = this._context.measureText(text);
  40426. x = (size.width - textSize.width) / 2;
  40427. }
  40428. if (y === null || y === undefined) {
  40429. var fontSize = parseInt((font.replace(/\D/g, '')));
  40430. ;
  40431. y = (size.height / 2) + (fontSize / 3.65);
  40432. }
  40433. this._context.fillStyle = color;
  40434. this._context.fillText(text, x, y);
  40435. if (update) {
  40436. this.update(invertY);
  40437. }
  40438. };
  40439. DynamicTexture.prototype.clone = function () {
  40440. var textureSize = this.getSize();
  40441. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  40442. // Base texture
  40443. newTexture.hasAlpha = this.hasAlpha;
  40444. newTexture.level = this.level;
  40445. // Dynamic Texture
  40446. newTexture.wrapU = this.wrapU;
  40447. newTexture.wrapV = this.wrapV;
  40448. return newTexture;
  40449. };
  40450. return DynamicTexture;
  40451. }(BABYLON.Texture));
  40452. BABYLON.DynamicTexture = DynamicTexture;
  40453. })(BABYLON || (BABYLON = {}));
  40454. //# sourceMappingURL=babylon.dynamicTexture.js.map
  40455. var BABYLON;
  40456. (function (BABYLON) {
  40457. var VideoTexture = (function (_super) {
  40458. __extends(VideoTexture, _super);
  40459. /**
  40460. * Creates a video texture.
  40461. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  40462. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  40463. * @param {BABYLON.Scene} scene is obviously the current scene.
  40464. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  40465. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  40466. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  40467. */
  40468. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  40469. if (generateMipMaps === void 0) { generateMipMaps = false; }
  40470. if (invertY === void 0) { invertY = false; }
  40471. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40472. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  40473. _this._autoLaunch = true;
  40474. var urls;
  40475. _this.name = name;
  40476. if (urlsOrVideo instanceof HTMLVideoElement) {
  40477. _this.video = urlsOrVideo;
  40478. }
  40479. else {
  40480. urls = urlsOrVideo;
  40481. _this.video = document.createElement("video");
  40482. _this.video.autoplay = false;
  40483. _this.video.loop = true;
  40484. }
  40485. _this._generateMipMaps = generateMipMaps;
  40486. _this._samplingMode = samplingMode;
  40487. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  40488. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  40489. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  40490. }
  40491. else {
  40492. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40493. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40494. _this._generateMipMaps = false;
  40495. }
  40496. if (urls) {
  40497. _this.video.addEventListener("canplay", function () {
  40498. _this._createTexture();
  40499. });
  40500. urls.forEach(function (url) {
  40501. var source = document.createElement("source");
  40502. source.src = url;
  40503. _this.video.appendChild(source);
  40504. });
  40505. }
  40506. else {
  40507. _this._createTexture();
  40508. }
  40509. _this._lastUpdate = BABYLON.Tools.Now;
  40510. return _this;
  40511. }
  40512. VideoTexture.prototype._createTexture = function () {
  40513. var _this = this;
  40514. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  40515. if (this._autoLaunch) {
  40516. this._autoLaunch = false;
  40517. this.video.play();
  40518. }
  40519. this.video.addEventListener("playing", function () {
  40520. _this._texture.isReady = true;
  40521. });
  40522. };
  40523. VideoTexture.prototype.update = function () {
  40524. var now = BABYLON.Tools.Now;
  40525. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  40526. return false;
  40527. }
  40528. this._lastUpdate = now;
  40529. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  40530. return true;
  40531. };
  40532. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  40533. var video = document.createElement("video");
  40534. var constraintsDeviceId;
  40535. if (constraints && constraints.deviceId) {
  40536. constraintsDeviceId = {
  40537. exact: constraints.deviceId
  40538. };
  40539. }
  40540. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  40541. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  40542. if (navigator.getUserMedia) {
  40543. navigator.getUserMedia({
  40544. video: {
  40545. deviceId: constraintsDeviceId,
  40546. width: {
  40547. min: (constraints && constraints.minWidth) || 256,
  40548. max: (constraints && constraints.maxWidth) || 640
  40549. },
  40550. height: {
  40551. min: (constraints && constraints.minHeight) || 256,
  40552. max: (constraints && constraints.maxHeight) || 480
  40553. }
  40554. }
  40555. }, function (stream) {
  40556. if (video.mozSrcObject !== undefined) {
  40557. video.mozSrcObject = stream;
  40558. }
  40559. else {
  40560. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  40561. }
  40562. video.play();
  40563. if (onReady) {
  40564. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  40565. }
  40566. }, function (e) {
  40567. BABYLON.Tools.Error(e.name);
  40568. });
  40569. }
  40570. };
  40571. return VideoTexture;
  40572. }(BABYLON.Texture));
  40573. BABYLON.VideoTexture = VideoTexture;
  40574. })(BABYLON || (BABYLON = {}));
  40575. //# sourceMappingURL=babylon.videoTexture.js.map
  40576. var BABYLON;
  40577. (function (BABYLON) {
  40578. var RawTexture = (function (_super) {
  40579. __extends(RawTexture, _super);
  40580. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  40581. if (generateMipMaps === void 0) { generateMipMaps = true; }
  40582. if (invertY === void 0) { invertY = false; }
  40583. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40584. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  40585. _this.format = format;
  40586. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  40587. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40588. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40589. return _this;
  40590. }
  40591. RawTexture.prototype.update = function (data) {
  40592. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  40593. };
  40594. // Statics
  40595. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  40596. if (generateMipMaps === void 0) { generateMipMaps = true; }
  40597. if (invertY === void 0) { invertY = false; }
  40598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40599. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  40600. };
  40601. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  40602. if (generateMipMaps === void 0) { generateMipMaps = true; }
  40603. if (invertY === void 0) { invertY = false; }
  40604. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40605. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  40606. };
  40607. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  40608. if (generateMipMaps === void 0) { generateMipMaps = true; }
  40609. if (invertY === void 0) { invertY = false; }
  40610. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40611. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  40612. };
  40613. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  40614. if (generateMipMaps === void 0) { generateMipMaps = true; }
  40615. if (invertY === void 0) { invertY = false; }
  40616. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40617. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  40618. };
  40619. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  40620. if (generateMipMaps === void 0) { generateMipMaps = true; }
  40621. if (invertY === void 0) { invertY = false; }
  40622. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40623. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  40624. };
  40625. return RawTexture;
  40626. }(BABYLON.Texture));
  40627. BABYLON.RawTexture = RawTexture;
  40628. })(BABYLON || (BABYLON = {}));
  40629. //# sourceMappingURL=babylon.rawTexture.js.map
  40630. var BABYLON;
  40631. (function (BABYLON) {
  40632. var PostProcess = (function () {
  40633. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  40634. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  40635. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40636. this.name = name;
  40637. this.width = -1;
  40638. this.height = -1;
  40639. /*
  40640. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  40641. Can only be used on a single postprocess or on the last one of a chain.
  40642. */
  40643. this.enablePixelPerfectMode = false;
  40644. this.samples = 1;
  40645. this._reusable = false;
  40646. this._textures = new BABYLON.SmartArray(2);
  40647. this._currentRenderTextureInd = 0;
  40648. this._scaleRatio = new BABYLON.Vector2(1, 1);
  40649. // Events
  40650. /**
  40651. * An event triggered when the postprocess is activated.
  40652. * @type {BABYLON.Observable}
  40653. */
  40654. this.onActivateObservable = new BABYLON.Observable();
  40655. /**
  40656. * An event triggered when the postprocess changes its size.
  40657. * @type {BABYLON.Observable}
  40658. */
  40659. this.onSizeChangedObservable = new BABYLON.Observable();
  40660. /**
  40661. * An event triggered when the postprocess applies its effect.
  40662. * @type {BABYLON.Observable}
  40663. */
  40664. this.onApplyObservable = new BABYLON.Observable();
  40665. /**
  40666. * An event triggered before rendering the postprocess
  40667. * @type {BABYLON.Observable}
  40668. */
  40669. this.onBeforeRenderObservable = new BABYLON.Observable();
  40670. /**
  40671. * An event triggered after rendering the postprocess
  40672. * @type {BABYLON.Observable}
  40673. */
  40674. this.onAfterRenderObservable = new BABYLON.Observable();
  40675. if (camera != null) {
  40676. this._camera = camera;
  40677. this._scene = camera.getScene();
  40678. camera.attachPostProcess(this);
  40679. this._engine = this._scene.getEngine();
  40680. }
  40681. else {
  40682. this._engine = engine;
  40683. }
  40684. this._options = options;
  40685. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  40686. this._reusable = reusable || false;
  40687. this._textureType = textureType;
  40688. this._samplers = samplers || [];
  40689. this._samplers.push("textureSampler");
  40690. this._fragmentUrl = fragmentUrl;
  40691. this._parameters = parameters || [];
  40692. this._parameters.push("scale");
  40693. this.updateEffect(defines);
  40694. }
  40695. Object.defineProperty(PostProcess.prototype, "onActivate", {
  40696. set: function (callback) {
  40697. if (this._onActivateObserver) {
  40698. this.onActivateObservable.remove(this._onActivateObserver);
  40699. }
  40700. this._onActivateObserver = this.onActivateObservable.add(callback);
  40701. },
  40702. enumerable: true,
  40703. configurable: true
  40704. });
  40705. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  40706. set: function (callback) {
  40707. if (this._onSizeChangedObserver) {
  40708. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  40709. }
  40710. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  40711. },
  40712. enumerable: true,
  40713. configurable: true
  40714. });
  40715. Object.defineProperty(PostProcess.prototype, "onApply", {
  40716. set: function (callback) {
  40717. if (this._onApplyObserver) {
  40718. this.onApplyObservable.remove(this._onApplyObserver);
  40719. }
  40720. this._onApplyObserver = this.onApplyObservable.add(callback);
  40721. },
  40722. enumerable: true,
  40723. configurable: true
  40724. });
  40725. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  40726. set: function (callback) {
  40727. if (this._onBeforeRenderObserver) {
  40728. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40729. }
  40730. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40731. },
  40732. enumerable: true,
  40733. configurable: true
  40734. });
  40735. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  40736. set: function (callback) {
  40737. if (this._onAfterRenderObserver) {
  40738. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40739. }
  40740. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40741. },
  40742. enumerable: true,
  40743. configurable: true
  40744. });
  40745. PostProcess.prototype.updateEffect = function (defines) {
  40746. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  40747. };
  40748. PostProcess.prototype.isReusable = function () {
  40749. return this._reusable;
  40750. };
  40751. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  40752. PostProcess.prototype.markTextureDirty = function () {
  40753. this.width = -1;
  40754. };
  40755. PostProcess.prototype.activate = function (camera, sourceTexture) {
  40756. var _this = this;
  40757. camera = camera || this._camera;
  40758. var scene = camera.getScene();
  40759. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  40760. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  40761. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  40762. var desiredWidth = this._options.width || requiredWidth;
  40763. var desiredHeight = this._options.height || requiredHeight;
  40764. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  40765. if (!this._options.width) {
  40766. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  40767. }
  40768. if (!this._options.height) {
  40769. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  40770. }
  40771. }
  40772. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  40773. if (this._textures.length > 0) {
  40774. for (var i = 0; i < this._textures.length; i++) {
  40775. this._engine._releaseTexture(this._textures.data[i]);
  40776. }
  40777. this._textures.reset();
  40778. }
  40779. this.width = desiredWidth;
  40780. this.height = desiredHeight;
  40781. var textureSize = { width: this.width, height: this.height };
  40782. var textureOptions = {
  40783. generateMipMaps: false,
  40784. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  40785. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  40786. samplingMode: this.renderTargetSamplingMode,
  40787. type: this._textureType
  40788. };
  40789. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  40790. if (this._reusable) {
  40791. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  40792. }
  40793. this.onSizeChangedObservable.notifyObservers(this);
  40794. }
  40795. this._textures.forEach(function (texture) {
  40796. if (texture.samples !== _this.samples) {
  40797. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  40798. }
  40799. });
  40800. if (this.enablePixelPerfectMode) {
  40801. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  40802. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  40803. }
  40804. else {
  40805. this._scaleRatio.copyFromFloats(1, 1);
  40806. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  40807. }
  40808. this.onActivateObservable.notifyObservers(camera);
  40809. // Clear
  40810. if (this.clearColor) {
  40811. this._engine.clear(this.clearColor, true, true, true);
  40812. }
  40813. else {
  40814. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  40815. }
  40816. if (this._reusable) {
  40817. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  40818. }
  40819. };
  40820. Object.defineProperty(PostProcess.prototype, "isSupported", {
  40821. get: function () {
  40822. return this._effect.isSupported;
  40823. },
  40824. enumerable: true,
  40825. configurable: true
  40826. });
  40827. PostProcess.prototype.apply = function () {
  40828. // Check
  40829. if (!this._effect.isReady())
  40830. return null;
  40831. // States
  40832. this._engine.enableEffect(this._effect);
  40833. this._engine.setState(false);
  40834. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40835. this._engine.setDepthBuffer(false);
  40836. this._engine.setDepthWrite(false);
  40837. // Texture
  40838. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  40839. // Parameters
  40840. this._effect.setVector2("scale", this._scaleRatio);
  40841. this.onApplyObservable.notifyObservers(this._effect);
  40842. return this._effect;
  40843. };
  40844. PostProcess.prototype.dispose = function (camera) {
  40845. camera = camera || this._camera;
  40846. if (this._textures.length > 0) {
  40847. for (var i = 0; i < this._textures.length; i++) {
  40848. this._engine._releaseTexture(this._textures.data[i]);
  40849. }
  40850. }
  40851. this._textures.dispose();
  40852. if (!camera) {
  40853. return;
  40854. }
  40855. camera.detachPostProcess(this);
  40856. var index = camera._postProcesses.indexOf(this);
  40857. if (index === 0 && camera._postProcesses.length > 0) {
  40858. this._camera._postProcesses[0].markTextureDirty();
  40859. }
  40860. this.onActivateObservable.clear();
  40861. this.onAfterRenderObservable.clear();
  40862. this.onApplyObservable.clear();
  40863. this.onBeforeRenderObservable.clear();
  40864. this.onSizeChangedObservable.clear();
  40865. };
  40866. return PostProcess;
  40867. }());
  40868. BABYLON.PostProcess = PostProcess;
  40869. })(BABYLON || (BABYLON = {}));
  40870. //# sourceMappingURL=babylon.postProcess.js.map
  40871. var BABYLON;
  40872. (function (BABYLON) {
  40873. var PassPostProcess = (function (_super) {
  40874. __extends(PassPostProcess, _super);
  40875. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40876. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40877. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  40878. }
  40879. return PassPostProcess;
  40880. }(BABYLON.PostProcess));
  40881. BABYLON.PassPostProcess = PassPostProcess;
  40882. })(BABYLON || (BABYLON = {}));
  40883. //# sourceMappingURL=babylon.passPostProcess.js.map
  40884. var BABYLON;
  40885. (function (BABYLON) {
  40886. var ShadowGenerator = (function () {
  40887. /**
  40888. * Creates a ShadowGenerator object.
  40889. * A ShadowGenerator is the required tool to use the shadows.
  40890. * Each light casting shadows needs to use its own ShadowGenerator.
  40891. * Required parameters :
  40892. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  40893. * - `light` : the light object generating the shadows.
  40894. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  40895. */
  40896. function ShadowGenerator(mapSize, light) {
  40897. var _this = this;
  40898. // Members
  40899. this._filter = ShadowGenerator.FILTER_NONE;
  40900. this.blurScale = 2;
  40901. this._blurBoxOffset = 0;
  40902. this._bias = 0.00005;
  40903. this._lightDirection = BABYLON.Vector3.Zero();
  40904. this.forceBackFacesOnly = false;
  40905. this._darkness = 0;
  40906. this._transparencyShadow = false;
  40907. this._viewMatrix = BABYLON.Matrix.Zero();
  40908. this._projectionMatrix = BABYLON.Matrix.Zero();
  40909. this._transformMatrix = BABYLON.Matrix.Zero();
  40910. this._worldViewProjection = BABYLON.Matrix.Zero();
  40911. this._currentFaceIndex = 0;
  40912. this._currentFaceIndexCache = 0;
  40913. this._useFullFloat = true;
  40914. this._light = light;
  40915. this._scene = light.getScene();
  40916. this._mapSize = mapSize;
  40917. light._shadowGenerator = this;
  40918. light._markMeshesAsLightDirty();
  40919. // Texture type fallback from float to int if not supported.
  40920. var textureType;
  40921. var caps = this._scene.getEngine().getCaps();
  40922. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  40923. this._useFullFloat = true;
  40924. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  40925. }
  40926. else {
  40927. this._useFullFloat = false;
  40928. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  40929. }
  40930. // Render target
  40931. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  40932. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40933. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40934. this._shadowMap.anisotropicFilteringLevel = 1;
  40935. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40936. this._shadowMap.renderParticles = false;
  40937. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  40938. _this._currentFaceIndex = faceIndex;
  40939. });
  40940. this._shadowMap.onAfterUnbindObservable.add(function () {
  40941. if (!_this.useBlurExponentialShadowMap) {
  40942. return;
  40943. }
  40944. if (!_this._shadowMap2) {
  40945. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  40946. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40947. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40948. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40949. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  40950. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  40951. effect.setTexture("textureSampler", _this._shadowMap);
  40952. });
  40953. _this.blurBoxOffset = 1;
  40954. }
  40955. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  40956. });
  40957. // Custom render function
  40958. var renderSubMesh = function (subMesh) {
  40959. var mesh = subMesh.getRenderingMesh();
  40960. var scene = _this._scene;
  40961. var engine = scene.getEngine();
  40962. // Culling
  40963. engine.setState(subMesh.getMaterial().backFaceCulling);
  40964. // Managing instances
  40965. var batch = mesh._getInstancesRenderList(subMesh._id);
  40966. if (batch.mustReturn) {
  40967. return;
  40968. }
  40969. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  40970. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  40971. engine.enableEffect(_this._effect);
  40972. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  40973. var material = subMesh.getMaterial();
  40974. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  40975. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  40976. _this._effect.setVector3("lightPosition", _this.getLight().position);
  40977. if (_this.getLight().needCube()) {
  40978. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  40979. }
  40980. // Alpha test
  40981. if (material && material.needAlphaTesting()) {
  40982. var alphaTexture = material.getAlphaTestTexture();
  40983. _this._effect.setTexture("diffuseSampler", alphaTexture);
  40984. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  40985. }
  40986. // Bones
  40987. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40988. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  40989. }
  40990. if (_this.forceBackFacesOnly) {
  40991. engine.setState(true, 0, false, true);
  40992. }
  40993. // Draw
  40994. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  40995. if (_this.forceBackFacesOnly) {
  40996. engine.setState(true, 0, false, false);
  40997. }
  40998. }
  40999. else {
  41000. // Need to reset refresh rate of the shadowMap
  41001. _this._shadowMap.resetRefreshCounter();
  41002. }
  41003. };
  41004. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  41005. var index;
  41006. for (index = 0; index < opaqueSubMeshes.length; index++) {
  41007. renderSubMesh(opaqueSubMeshes.data[index]);
  41008. }
  41009. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  41010. renderSubMesh(alphaTestSubMeshes.data[index]);
  41011. }
  41012. if (_this._transparencyShadow) {
  41013. for (index = 0; index < transparentSubMeshes.length; index++) {
  41014. renderSubMesh(transparentSubMeshes.data[index]);
  41015. }
  41016. }
  41017. };
  41018. this._shadowMap.onClearObservable.add(function (engine) {
  41019. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  41020. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  41021. }
  41022. else {
  41023. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  41024. }
  41025. });
  41026. }
  41027. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  41028. // Static
  41029. get: function () {
  41030. return ShadowGenerator._FILTER_NONE;
  41031. },
  41032. enumerable: true,
  41033. configurable: true
  41034. });
  41035. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  41036. get: function () {
  41037. return ShadowGenerator._FILTER_POISSONSAMPLING;
  41038. },
  41039. enumerable: true,
  41040. configurable: true
  41041. });
  41042. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  41043. get: function () {
  41044. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  41045. },
  41046. enumerable: true,
  41047. configurable: true
  41048. });
  41049. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  41050. get: function () {
  41051. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  41052. },
  41053. enumerable: true,
  41054. configurable: true
  41055. });
  41056. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  41057. get: function () {
  41058. return this._bias;
  41059. },
  41060. set: function (bias) {
  41061. this._bias = bias;
  41062. },
  41063. enumerable: true,
  41064. configurable: true
  41065. });
  41066. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  41067. get: function () {
  41068. return this._blurBoxOffset;
  41069. },
  41070. set: function (value) {
  41071. var _this = this;
  41072. if (this._blurBoxOffset === value) {
  41073. return;
  41074. }
  41075. this._blurBoxOffset = value;
  41076. if (this._boxBlurPostprocess) {
  41077. this._boxBlurPostprocess.dispose();
  41078. }
  41079. var textureType;
  41080. var caps = this._scene.getEngine().getCaps();
  41081. if (this._useFullFloat) {
  41082. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  41083. }
  41084. else {
  41085. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  41086. }
  41087. 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);
  41088. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  41089. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  41090. });
  41091. },
  41092. enumerable: true,
  41093. configurable: true
  41094. });
  41095. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  41096. get: function () {
  41097. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  41098. },
  41099. set: function (value) {
  41100. this._depthScale = value;
  41101. },
  41102. enumerable: true,
  41103. configurable: true
  41104. });
  41105. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  41106. get: function () {
  41107. return this._filter;
  41108. },
  41109. set: function (value) {
  41110. if (this._filter === value) {
  41111. return;
  41112. }
  41113. this._filter = value;
  41114. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  41115. this._shadowMap.anisotropicFilteringLevel = 16;
  41116. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41117. }
  41118. else {
  41119. this._shadowMap.anisotropicFilteringLevel = 1;
  41120. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  41121. }
  41122. this._light._markMeshesAsLightDirty();
  41123. },
  41124. enumerable: true,
  41125. configurable: true
  41126. });
  41127. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  41128. get: function () {
  41129. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  41130. return this.useExponentialShadowMap;
  41131. },
  41132. set: function (value) {
  41133. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  41134. this.useExponentialShadowMap = value;
  41135. },
  41136. enumerable: true,
  41137. configurable: true
  41138. });
  41139. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  41140. get: function () {
  41141. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  41142. },
  41143. set: function (value) {
  41144. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  41145. },
  41146. enumerable: true,
  41147. configurable: true
  41148. });
  41149. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  41150. get: function () {
  41151. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  41152. },
  41153. set: function (value) {
  41154. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  41155. },
  41156. enumerable: true,
  41157. configurable: true
  41158. });
  41159. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  41160. get: function () {
  41161. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  41162. return this.useBlurExponentialShadowMap;
  41163. },
  41164. set: function (value) {
  41165. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  41166. this.useBlurExponentialShadowMap = value;
  41167. },
  41168. enumerable: true,
  41169. configurable: true
  41170. });
  41171. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  41172. get: function () {
  41173. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  41174. },
  41175. set: function (value) {
  41176. if (this._light.needCube() && value) {
  41177. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  41178. }
  41179. else {
  41180. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  41181. }
  41182. },
  41183. enumerable: true,
  41184. configurable: true
  41185. });
  41186. /**
  41187. * Boolean : true when the ShadowGenerator is finally computed.
  41188. */
  41189. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  41190. var defines = [];
  41191. if (this._useFullFloat) {
  41192. defines.push("#define FULLFLOAT");
  41193. }
  41194. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  41195. defines.push("#define ESM");
  41196. }
  41197. if (this.getLight().needCube()) {
  41198. defines.push("#define CUBEMAP");
  41199. }
  41200. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41201. var mesh = subMesh.getMesh();
  41202. var material = subMesh.getMaterial();
  41203. // Alpha test
  41204. if (material && material.needAlphaTesting()) {
  41205. defines.push("#define ALPHATEST");
  41206. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41207. attribs.push(BABYLON.VertexBuffer.UVKind);
  41208. defines.push("#define UV1");
  41209. }
  41210. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41211. var alphaTexture = material.getAlphaTestTexture();
  41212. if (alphaTexture.coordinatesIndex === 1) {
  41213. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41214. defines.push("#define UV2");
  41215. }
  41216. }
  41217. }
  41218. // Bones
  41219. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  41220. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41221. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41222. if (mesh.numBoneInfluencers > 4) {
  41223. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41224. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41225. }
  41226. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  41227. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  41228. }
  41229. else {
  41230. defines.push("#define NUM_BONE_INFLUENCERS 0");
  41231. }
  41232. // Instances
  41233. if (useInstances) {
  41234. defines.push("#define INSTANCES");
  41235. attribs.push("world0");
  41236. attribs.push("world1");
  41237. attribs.push("world2");
  41238. attribs.push("world3");
  41239. }
  41240. // Get correct effect
  41241. var join = defines.join("\n");
  41242. if (this._cachedDefines !== join) {
  41243. this._cachedDefines = join;
  41244. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  41245. }
  41246. return this._effect.isReady();
  41247. };
  41248. /**
  41249. * Returns a RenderTargetTexture object : the shadow map texture.
  41250. */
  41251. ShadowGenerator.prototype.getShadowMap = function () {
  41252. return this._shadowMap;
  41253. };
  41254. /**
  41255. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  41256. */
  41257. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  41258. if (this._shadowMap2) {
  41259. return this._shadowMap2;
  41260. }
  41261. return this._shadowMap;
  41262. };
  41263. /**
  41264. * Returns the associated light object.
  41265. */
  41266. ShadowGenerator.prototype.getLight = function () {
  41267. return this._light;
  41268. };
  41269. // Methods
  41270. /**
  41271. * Returns a Matrix object : the updated transformation matrix.
  41272. */
  41273. ShadowGenerator.prototype.getTransformMatrix = function () {
  41274. var scene = this._scene;
  41275. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  41276. return this._transformMatrix;
  41277. }
  41278. this._currentRenderID = scene.getRenderId();
  41279. this._currentFaceIndexCache = this._currentFaceIndex;
  41280. var lightPosition = this._light.position;
  41281. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  41282. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  41283. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  41284. }
  41285. if (this._light.computeTransformedPosition()) {
  41286. lightPosition = this._light.transformedPosition;
  41287. }
  41288. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  41289. this._cachedPosition = lightPosition.clone();
  41290. this._cachedDirection = this._lightDirection.clone();
  41291. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  41292. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  41293. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  41294. }
  41295. return this._transformMatrix;
  41296. };
  41297. /**
  41298. * Returns the darkness value (float).
  41299. */
  41300. ShadowGenerator.prototype.getDarkness = function () {
  41301. return this._darkness;
  41302. };
  41303. /**
  41304. * Sets the ShadowGenerator darkness value (float <= 1.0).
  41305. * Returns the ShadowGenerator.
  41306. */
  41307. ShadowGenerator.prototype.setDarkness = function (darkness) {
  41308. if (darkness >= 1.0)
  41309. this._darkness = 1.0;
  41310. else if (darkness <= 0.0)
  41311. this._darkness = 0.0;
  41312. else
  41313. this._darkness = darkness;
  41314. return this;
  41315. };
  41316. /**
  41317. * Sets the ability to have transparent shadow (boolean).
  41318. * Returns the ShadowGenerator.
  41319. */
  41320. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  41321. this._transparencyShadow = hasShadow;
  41322. return this;
  41323. };
  41324. ShadowGenerator.prototype._packHalf = function (depth) {
  41325. var scale = depth * 255.0;
  41326. var fract = scale - Math.floor(scale);
  41327. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  41328. };
  41329. /**
  41330. * Disposes the ShadowGenerator.
  41331. * Returns nothing.
  41332. */
  41333. ShadowGenerator.prototype.dispose = function () {
  41334. this._shadowMap.dispose();
  41335. if (this._shadowMap2) {
  41336. this._shadowMap2.dispose();
  41337. }
  41338. if (this._downSamplePostprocess) {
  41339. this._downSamplePostprocess.dispose();
  41340. }
  41341. if (this._boxBlurPostprocess) {
  41342. this._boxBlurPostprocess.dispose();
  41343. }
  41344. this._light._shadowGenerator = null;
  41345. this._light._markMeshesAsLightDirty();
  41346. };
  41347. /**
  41348. * Serializes the ShadowGenerator and returns a serializationObject.
  41349. */
  41350. ShadowGenerator.prototype.serialize = function () {
  41351. var serializationObject = {};
  41352. serializationObject.lightId = this._light.id;
  41353. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  41354. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  41355. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  41356. serializationObject.usePoissonSampling = this.usePoissonSampling;
  41357. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  41358. serializationObject.depthScale = this.depthScale;
  41359. serializationObject.darkness = this.getDarkness();
  41360. serializationObject.renderList = [];
  41361. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  41362. var mesh = this.getShadowMap().renderList[meshIndex];
  41363. serializationObject.renderList.push(mesh.id);
  41364. }
  41365. return serializationObject;
  41366. };
  41367. /**
  41368. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  41369. */
  41370. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  41371. //casting to point light, as light is missing the position attr and typescript complains.
  41372. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  41373. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  41374. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  41375. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  41376. meshes.forEach(function (mesh) {
  41377. shadowGenerator.getShadowMap().renderList.push(mesh);
  41378. });
  41379. }
  41380. if (parsedShadowGenerator.usePoissonSampling) {
  41381. shadowGenerator.usePoissonSampling = true;
  41382. }
  41383. else if (parsedShadowGenerator.useExponentialShadowMap) {
  41384. shadowGenerator.useExponentialShadowMap = true;
  41385. }
  41386. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  41387. shadowGenerator.useBlurExponentialShadowMap = true;
  41388. }
  41389. else if (parsedShadowGenerator.useVarianceShadowMap) {
  41390. shadowGenerator.useExponentialShadowMap = true;
  41391. }
  41392. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  41393. shadowGenerator.useBlurExponentialShadowMap = true;
  41394. }
  41395. if (parsedShadowGenerator.depthScale) {
  41396. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  41397. }
  41398. if (parsedShadowGenerator.blurScale) {
  41399. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  41400. }
  41401. if (parsedShadowGenerator.blurBoxOffset) {
  41402. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  41403. }
  41404. if (parsedShadowGenerator.bias !== undefined) {
  41405. shadowGenerator.bias = parsedShadowGenerator.bias;
  41406. }
  41407. if (parsedShadowGenerator.darkness) {
  41408. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  41409. }
  41410. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  41411. return shadowGenerator;
  41412. };
  41413. return ShadowGenerator;
  41414. }());
  41415. ShadowGenerator._FILTER_NONE = 0;
  41416. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  41417. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  41418. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  41419. BABYLON.ShadowGenerator = ShadowGenerator;
  41420. })(BABYLON || (BABYLON = {}));
  41421. //# sourceMappingURL=babylon.shadowGenerator.js.map
  41422. var BABYLON;
  41423. (function (BABYLON) {
  41424. var DefaultLoadingScreen = (function () {
  41425. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  41426. if (_loadingText === void 0) { _loadingText = ""; }
  41427. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  41428. var _this = this;
  41429. this._renderingCanvas = _renderingCanvas;
  41430. this._loadingText = _loadingText;
  41431. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  41432. // Resize
  41433. this._resizeLoadingUI = function () {
  41434. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  41435. _this._loadingDiv.style.position = "absolute";
  41436. _this._loadingDiv.style.left = canvasRect.left + "px";
  41437. _this._loadingDiv.style.top = canvasRect.top + "px";
  41438. _this._loadingDiv.style.width = canvasRect.width + "px";
  41439. _this._loadingDiv.style.height = canvasRect.height + "px";
  41440. };
  41441. }
  41442. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  41443. var _this = this;
  41444. if (this._loadingDiv) {
  41445. // Do not add a loading screen if there is already one
  41446. return;
  41447. }
  41448. this._loadingDiv = document.createElement("div");
  41449. this._loadingDiv.id = "babylonjsLoadingDiv";
  41450. this._loadingDiv.style.opacity = "0";
  41451. this._loadingDiv.style.transition = "opacity 1.5s ease";
  41452. // Loading text
  41453. this._loadingTextDiv = document.createElement("div");
  41454. this._loadingTextDiv.style.position = "absolute";
  41455. this._loadingTextDiv.style.left = "0";
  41456. this._loadingTextDiv.style.top = "50%";
  41457. this._loadingTextDiv.style.marginTop = "80px";
  41458. this._loadingTextDiv.style.width = "100%";
  41459. this._loadingTextDiv.style.height = "20px";
  41460. this._loadingTextDiv.style.fontFamily = "Arial";
  41461. this._loadingTextDiv.style.fontSize = "14px";
  41462. this._loadingTextDiv.style.color = "white";
  41463. this._loadingTextDiv.style.textAlign = "center";
  41464. this._loadingTextDiv.innerHTML = "Loading";
  41465. this._loadingDiv.appendChild(this._loadingTextDiv);
  41466. //set the predefined text
  41467. this._loadingTextDiv.innerHTML = this._loadingText;
  41468. // Loading img
  41469. var imgBack = new Image();
  41470. 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==";
  41471. imgBack.style.position = "absolute";
  41472. imgBack.style.left = "50%";
  41473. imgBack.style.top = "50%";
  41474. imgBack.style.marginLeft = "-50px";
  41475. imgBack.style.marginTop = "-50px";
  41476. imgBack.style.transition = "transform 1.0s ease";
  41477. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  41478. var deg = 360;
  41479. var onTransitionEnd = function () {
  41480. deg += 360;
  41481. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  41482. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  41483. };
  41484. imgBack.addEventListener("transitionend", onTransitionEnd);
  41485. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  41486. this._loadingDiv.appendChild(imgBack);
  41487. // front image
  41488. var imgFront = new Image();
  41489. 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=";
  41490. imgFront.style.position = "absolute";
  41491. imgFront.style.left = "50%";
  41492. imgFront.style.top = "50%";
  41493. imgFront.style.marginLeft = "-50px";
  41494. imgFront.style.marginTop = "-50px";
  41495. this._loadingDiv.appendChild(imgFront);
  41496. this._resizeLoadingUI();
  41497. window.addEventListener("resize", this._resizeLoadingUI);
  41498. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  41499. document.body.appendChild(this._loadingDiv);
  41500. setTimeout(function () {
  41501. _this._loadingDiv.style.opacity = "1";
  41502. imgBack.style.transform = "rotateZ(360deg)";
  41503. imgBack.style.webkitTransform = "rotateZ(360deg)";
  41504. }, 0);
  41505. };
  41506. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  41507. var _this = this;
  41508. if (!this._loadingDiv) {
  41509. return;
  41510. }
  41511. var onTransitionEnd = function () {
  41512. if (!_this._loadingDiv) {
  41513. return;
  41514. }
  41515. document.body.removeChild(_this._loadingDiv);
  41516. window.removeEventListener("resize", _this._resizeLoadingUI);
  41517. _this._loadingDiv = null;
  41518. };
  41519. this._loadingDiv.style.opacity = "0";
  41520. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  41521. };
  41522. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  41523. set: function (text) {
  41524. this._loadingText = text;
  41525. if (this._loadingTextDiv) {
  41526. this._loadingTextDiv.innerHTML = this._loadingText;
  41527. }
  41528. },
  41529. enumerable: true,
  41530. configurable: true
  41531. });
  41532. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  41533. get: function () {
  41534. return this._loadingDivBackgroundColor;
  41535. },
  41536. set: function (color) {
  41537. this._loadingDivBackgroundColor = color;
  41538. if (!this._loadingDiv) {
  41539. return;
  41540. }
  41541. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  41542. },
  41543. enumerable: true,
  41544. configurable: true
  41545. });
  41546. return DefaultLoadingScreen;
  41547. }());
  41548. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  41549. })(BABYLON || (BABYLON = {}));
  41550. //# sourceMappingURL=babylon.loadingScreen.js.map
  41551. var BABYLON;
  41552. (function (BABYLON) {
  41553. var SceneLoader = (function () {
  41554. function SceneLoader() {
  41555. }
  41556. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  41557. get: function () {
  41558. return 0;
  41559. },
  41560. enumerable: true,
  41561. configurable: true
  41562. });
  41563. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  41564. get: function () {
  41565. return 1;
  41566. },
  41567. enumerable: true,
  41568. configurable: true
  41569. });
  41570. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  41571. get: function () {
  41572. return 2;
  41573. },
  41574. enumerable: true,
  41575. configurable: true
  41576. });
  41577. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  41578. get: function () {
  41579. return 3;
  41580. },
  41581. enumerable: true,
  41582. configurable: true
  41583. });
  41584. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  41585. get: function () {
  41586. return SceneLoader._ForceFullSceneLoadingForIncremental;
  41587. },
  41588. set: function (value) {
  41589. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  41590. },
  41591. enumerable: true,
  41592. configurable: true
  41593. });
  41594. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  41595. get: function () {
  41596. return SceneLoader._ShowLoadingScreen;
  41597. },
  41598. set: function (value) {
  41599. SceneLoader._ShowLoadingScreen = value;
  41600. },
  41601. enumerable: true,
  41602. configurable: true
  41603. });
  41604. Object.defineProperty(SceneLoader, "loggingLevel", {
  41605. get: function () {
  41606. return SceneLoader._loggingLevel;
  41607. },
  41608. set: function (value) {
  41609. SceneLoader._loggingLevel = value;
  41610. },
  41611. enumerable: true,
  41612. configurable: true
  41613. });
  41614. SceneLoader._getDefaultPlugin = function () {
  41615. return SceneLoader._registeredPlugins[".babylon"];
  41616. };
  41617. SceneLoader._getPluginForExtension = function (extension) {
  41618. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  41619. if (registeredPlugin) {
  41620. return registeredPlugin;
  41621. }
  41622. return SceneLoader._getDefaultPlugin();
  41623. };
  41624. SceneLoader._getPluginForFilename = function (sceneFilename) {
  41625. if (sceneFilename.name) {
  41626. sceneFilename = sceneFilename.name;
  41627. }
  41628. var dotPosition = sceneFilename.lastIndexOf(".");
  41629. var queryStringPosition = sceneFilename.indexOf("?");
  41630. if (queryStringPosition === -1) {
  41631. queryStringPosition = sceneFilename.length;
  41632. }
  41633. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  41634. return SceneLoader._getPluginForExtension(extension);
  41635. };
  41636. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  41637. SceneLoader._getDirectLoad = function (sceneFilename) {
  41638. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  41639. return sceneFilename.substr(5);
  41640. }
  41641. return null;
  41642. };
  41643. // Public functions
  41644. SceneLoader.GetPluginForExtension = function (extension) {
  41645. return SceneLoader._getPluginForExtension(extension).plugin;
  41646. };
  41647. SceneLoader.RegisterPlugin = function (plugin) {
  41648. if (typeof plugin.extensions === "string") {
  41649. var extension = plugin.extensions;
  41650. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  41651. plugin: plugin,
  41652. isBinary: false
  41653. };
  41654. }
  41655. else {
  41656. var extensions = plugin.extensions;
  41657. Object.keys(extensions).forEach(function (extension) {
  41658. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  41659. plugin: plugin,
  41660. isBinary: extensions[extension].isBinary
  41661. };
  41662. });
  41663. }
  41664. };
  41665. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  41666. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  41667. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  41668. return;
  41669. }
  41670. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  41671. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  41672. return;
  41673. }
  41674. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  41675. var loadingToken = {};
  41676. scene._addPendingData(loadingToken);
  41677. var manifestChecked = function (success) {
  41678. scene.database = database;
  41679. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  41680. var plugin = registeredPlugin.plugin;
  41681. var useArrayBuffer = registeredPlugin.isBinary;
  41682. var importMeshFromData = function (data) {
  41683. var meshes = [];
  41684. var particleSystems = [];
  41685. var skeletons = [];
  41686. if (scene.isDisposed) {
  41687. if (onerror) {
  41688. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  41689. }
  41690. return;
  41691. }
  41692. try {
  41693. if (plugin.importMesh) {
  41694. var syncedPlugin = plugin;
  41695. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  41696. if (onerror) {
  41697. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  41698. }
  41699. scene._removePendingData(loadingToken);
  41700. return;
  41701. }
  41702. if (onsuccess) {
  41703. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  41704. onsuccess(meshes, particleSystems, skeletons);
  41705. scene._removePendingData(loadingToken);
  41706. }
  41707. }
  41708. else {
  41709. var asyncedPlugin = plugin;
  41710. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  41711. if (onsuccess) {
  41712. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  41713. onsuccess(meshes, particleSystems, skeletons);
  41714. scene._removePendingData(loadingToken);
  41715. }
  41716. }, function () {
  41717. if (onerror) {
  41718. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  41719. }
  41720. scene._removePendingData(loadingToken);
  41721. });
  41722. }
  41723. }
  41724. catch (e) {
  41725. if (onerror) {
  41726. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  41727. }
  41728. scene._removePendingData(loadingToken);
  41729. }
  41730. };
  41731. if (directLoad) {
  41732. importMeshFromData(directLoad);
  41733. return;
  41734. }
  41735. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  41736. importMeshFromData(data);
  41737. }, progressCallBack, database, useArrayBuffer, function () {
  41738. if (onerror) {
  41739. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  41740. }
  41741. });
  41742. };
  41743. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  41744. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  41745. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  41746. }
  41747. else {
  41748. // If the scene is a data stream or offline support is not enabled, it's a direct load
  41749. manifestChecked(true);
  41750. }
  41751. };
  41752. /**
  41753. * Load a scene
  41754. * @param rootUrl a string that defines the root url for scene and resources
  41755. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  41756. * @param engine is the instance of BABYLON.Engine to use to create the scene
  41757. */
  41758. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  41759. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  41760. };
  41761. /**
  41762. * Append a scene
  41763. * @param rootUrl a string that defines the root url for scene and resources
  41764. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  41765. * @param scene is the instance of BABYLON.Scene to append to
  41766. */
  41767. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  41768. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  41769. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  41770. return;
  41771. }
  41772. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  41773. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  41774. var plugin = registeredPlugin.plugin;
  41775. var useArrayBuffer = registeredPlugin.isBinary;
  41776. var database;
  41777. var loadingToken = {};
  41778. scene._addPendingData(loadingToken);
  41779. if (SceneLoader.ShowLoadingScreen) {
  41780. scene.getEngine().displayLoadingUI();
  41781. }
  41782. var loadSceneFromData = function (data) {
  41783. scene.database = database;
  41784. if (plugin.load) {
  41785. var syncedPlugin = plugin;
  41786. if (!syncedPlugin.load(scene, data, rootUrl)) {
  41787. if (onerror) {
  41788. onerror(scene);
  41789. }
  41790. scene._removePendingData(loadingToken);
  41791. scene.getEngine().hideLoadingUI();
  41792. return;
  41793. }
  41794. if (onsuccess) {
  41795. onsuccess(scene);
  41796. }
  41797. scene._removePendingData(loadingToken);
  41798. }
  41799. else {
  41800. var asyncedPlugin = plugin;
  41801. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  41802. if (onsuccess) {
  41803. onsuccess(scene);
  41804. }
  41805. scene._removePendingData(loadingToken);
  41806. }, function () {
  41807. if (onerror) {
  41808. onerror(scene);
  41809. }
  41810. scene._removePendingData(loadingToken);
  41811. scene.getEngine().hideLoadingUI();
  41812. });
  41813. }
  41814. if (SceneLoader.ShowLoadingScreen) {
  41815. scene.executeWhenReady(function () {
  41816. scene.getEngine().hideLoadingUI();
  41817. });
  41818. }
  41819. };
  41820. var manifestChecked = function (success) {
  41821. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  41822. };
  41823. if (directLoad) {
  41824. loadSceneFromData(directLoad);
  41825. return;
  41826. }
  41827. if (rootUrl.indexOf("file:") === -1) {
  41828. if (scene.getEngine().enableOfflineSupport) {
  41829. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  41830. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  41831. }
  41832. else {
  41833. manifestChecked(true);
  41834. }
  41835. }
  41836. else {
  41837. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  41838. }
  41839. };
  41840. return SceneLoader;
  41841. }());
  41842. // Flags
  41843. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  41844. SceneLoader._ShowLoadingScreen = true;
  41845. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  41846. // Members
  41847. SceneLoader._registeredPlugins = {};
  41848. BABYLON.SceneLoader = SceneLoader;
  41849. ;
  41850. })(BABYLON || (BABYLON = {}));
  41851. //# sourceMappingURL=babylon.sceneLoader.js.map
  41852. var BABYLON;
  41853. (function (BABYLON) {
  41854. var Internals;
  41855. (function (Internals) {
  41856. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  41857. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  41858. var parsedMaterial = parsedData.materials[index];
  41859. if (parsedMaterial.id === id) {
  41860. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  41861. }
  41862. }
  41863. return null;
  41864. };
  41865. var isDescendantOf = function (mesh, names, hierarchyIds) {
  41866. names = (names instanceof Array) ? names : [names];
  41867. for (var i in names) {
  41868. if (mesh.name === names[i]) {
  41869. hierarchyIds.push(mesh.id);
  41870. return true;
  41871. }
  41872. }
  41873. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  41874. hierarchyIds.push(mesh.id);
  41875. return true;
  41876. }
  41877. return false;
  41878. };
  41879. var logOperation = function (operation, producer) {
  41880. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  41881. };
  41882. BABYLON.SceneLoader.RegisterPlugin({
  41883. extensions: ".babylon",
  41884. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  41885. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  41886. // when SceneLoader.debugLogging = true (default), or exception encountered.
  41887. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  41888. // and avoid problems with multiple concurrent .babylon loads.
  41889. var log = "importMesh has failed JSON parse";
  41890. try {
  41891. var parsedData = JSON.parse(data);
  41892. log = "";
  41893. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  41894. var loadedSkeletonsIds = [];
  41895. var loadedMaterialsIds = [];
  41896. var hierarchyIds = [];
  41897. var index;
  41898. var cache;
  41899. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  41900. var parsedMesh = parsedData.meshes[index];
  41901. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  41902. if (meshesNames instanceof Array) {
  41903. // Remove found mesh name from list.
  41904. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  41905. }
  41906. //Geometry?
  41907. if (parsedMesh.geometryId) {
  41908. //does the file contain geometries?
  41909. if (parsedData.geometries) {
  41910. //find the correct geometry and add it to the scene
  41911. var found = false;
  41912. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  41913. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  41914. return;
  41915. }
  41916. else {
  41917. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  41918. if (parsedGeometryData.id === parsedMesh.geometryId) {
  41919. switch (geometryType) {
  41920. case "boxes":
  41921. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  41922. break;
  41923. case "spheres":
  41924. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  41925. break;
  41926. case "cylinders":
  41927. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  41928. break;
  41929. case "toruses":
  41930. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  41931. break;
  41932. case "grounds":
  41933. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  41934. break;
  41935. case "planes":
  41936. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  41937. break;
  41938. case "torusKnots":
  41939. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  41940. break;
  41941. case "vertexData":
  41942. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  41943. break;
  41944. }
  41945. found = true;
  41946. }
  41947. });
  41948. }
  41949. });
  41950. if (!found) {
  41951. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  41952. }
  41953. }
  41954. }
  41955. // Material ?
  41956. if (parsedMesh.materialId) {
  41957. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  41958. if (!materialFound && parsedData.multiMaterials) {
  41959. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  41960. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  41961. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  41962. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  41963. var subMatId = parsedMultiMaterial.materials[matIndex];
  41964. loadedMaterialsIds.push(subMatId);
  41965. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  41966. log += "\n\tMaterial " + mat.toString(fullDetails);
  41967. }
  41968. loadedMaterialsIds.push(parsedMultiMaterial.id);
  41969. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  41970. materialFound = true;
  41971. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  41972. break;
  41973. }
  41974. }
  41975. }
  41976. if (!materialFound) {
  41977. loadedMaterialsIds.push(parsedMesh.materialId);
  41978. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  41979. if (!mat) {
  41980. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  41981. }
  41982. else {
  41983. log += "\n\tMaterial " + mat.toString(fullDetails);
  41984. }
  41985. }
  41986. }
  41987. // Skeleton ?
  41988. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  41989. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  41990. if (!skeletonAlreadyLoaded) {
  41991. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  41992. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  41993. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  41994. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  41995. skeletons.push(skeleton);
  41996. loadedSkeletonsIds.push(parsedSkeleton.id);
  41997. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  41998. }
  41999. }
  42000. }
  42001. }
  42002. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  42003. meshes.push(mesh);
  42004. log += "\n\tMesh " + mesh.toString(fullDetails);
  42005. }
  42006. }
  42007. // Connecting parents
  42008. var currentMesh;
  42009. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  42010. currentMesh = scene.meshes[index];
  42011. if (currentMesh._waitingParentId) {
  42012. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  42013. currentMesh._waitingParentId = undefined;
  42014. }
  42015. }
  42016. // freeze and compute world matrix application
  42017. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  42018. currentMesh = scene.meshes[index];
  42019. if (currentMesh._waitingFreezeWorldMatrix) {
  42020. currentMesh.freezeWorldMatrix();
  42021. currentMesh._waitingFreezeWorldMatrix = undefined;
  42022. }
  42023. else {
  42024. currentMesh.computeWorldMatrix(true);
  42025. }
  42026. }
  42027. // Particles
  42028. if (parsedData.particleSystems) {
  42029. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  42030. var parsedParticleSystem = parsedData.particleSystems[index];
  42031. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  42032. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  42033. }
  42034. }
  42035. }
  42036. return true;
  42037. }
  42038. catch (err) {
  42039. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  42040. log = null;
  42041. throw err;
  42042. }
  42043. finally {
  42044. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  42045. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  42046. }
  42047. }
  42048. },
  42049. load: function (scene, data, rootUrl) {
  42050. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  42051. // when SceneLoader.debugLogging = true (default), or exception encountered.
  42052. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  42053. // and avoid problems with multiple concurrent .babylon loads.
  42054. var log = "importScene has failed JSON parse";
  42055. try {
  42056. var parsedData = JSON.parse(data);
  42057. log = "";
  42058. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  42059. // Scene
  42060. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  42061. scene.autoClear = parsedData.autoClear;
  42062. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  42063. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  42064. if (parsedData.gravity) {
  42065. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  42066. }
  42067. // Fog
  42068. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  42069. scene.fogMode = parsedData.fogMode;
  42070. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  42071. scene.fogStart = parsedData.fogStart;
  42072. scene.fogEnd = parsedData.fogEnd;
  42073. scene.fogDensity = parsedData.fogDensity;
  42074. log += "\tFog mode for scene: ";
  42075. switch (scene.fogMode) {
  42076. // getters not compiling, so using hardcoded
  42077. case 1:
  42078. log += "exp\n";
  42079. break;
  42080. case 2:
  42081. log += "exp2\n";
  42082. break;
  42083. case 3:
  42084. log += "linear\n";
  42085. break;
  42086. }
  42087. }
  42088. //Physics
  42089. if (parsedData.physicsEnabled) {
  42090. var physicsPlugin;
  42091. if (parsedData.physicsEngine === "cannon") {
  42092. physicsPlugin = new BABYLON.CannonJSPlugin();
  42093. }
  42094. else if (parsedData.physicsEngine === "oimo") {
  42095. physicsPlugin = new BABYLON.OimoJSPlugin();
  42096. }
  42097. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  42098. //else - default engine, which is currently oimo
  42099. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  42100. scene.enablePhysics(physicsGravity, physicsPlugin);
  42101. }
  42102. // Metadata
  42103. if (parsedData.metadata !== undefined) {
  42104. scene.metadata = parsedData.metadata;
  42105. }
  42106. //collisions, if defined. otherwise, default is true
  42107. if (parsedData.collisionsEnabled != undefined) {
  42108. scene.collisionsEnabled = parsedData.collisionsEnabled;
  42109. }
  42110. scene.workerCollisions = !!parsedData.workerCollisions;
  42111. var index;
  42112. var cache;
  42113. // Lights
  42114. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  42115. var parsedLight = parsedData.lights[index];
  42116. var light = BABYLON.Light.Parse(parsedLight, scene);
  42117. log += (index === 0 ? "\n\tLights:" : "");
  42118. log += "\n\t\t" + light.toString(fullDetails);
  42119. }
  42120. // Animations
  42121. if (parsedData.animations) {
  42122. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  42123. var parsedAnimation = parsedData.animations[index];
  42124. var animation = BABYLON.Animation.Parse(parsedAnimation);
  42125. scene.animations.push(animation);
  42126. log += (index === 0 ? "\n\tAnimations:" : "");
  42127. log += "\n\t\t" + animation.toString(fullDetails);
  42128. }
  42129. }
  42130. if (parsedData.autoAnimate) {
  42131. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  42132. }
  42133. // Materials
  42134. if (parsedData.materials) {
  42135. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  42136. var parsedMaterial = parsedData.materials[index];
  42137. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  42138. log += (index === 0 ? "\n\tMaterials:" : "");
  42139. log += "\n\t\t" + mat.toString(fullDetails);
  42140. }
  42141. }
  42142. if (parsedData.multiMaterials) {
  42143. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  42144. var parsedMultiMaterial = parsedData.multiMaterials[index];
  42145. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  42146. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  42147. log += "\n\t\t" + mmat.toString(fullDetails);
  42148. }
  42149. }
  42150. // Morph targets
  42151. if (parsedData.morphTargetManagers) {
  42152. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  42153. var managerData = _a[_i];
  42154. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  42155. }
  42156. }
  42157. // Skeletons
  42158. if (parsedData.skeletons) {
  42159. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  42160. var parsedSkeleton = parsedData.skeletons[index];
  42161. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  42162. log += (index === 0 ? "\n\tSkeletons:" : "");
  42163. log += "\n\t\t" + skeleton.toString(fullDetails);
  42164. }
  42165. }
  42166. // Geometries
  42167. var geometries = parsedData.geometries;
  42168. if (geometries) {
  42169. // Boxes
  42170. var boxes = geometries.boxes;
  42171. if (boxes) {
  42172. for (index = 0, cache = boxes.length; index < cache; index++) {
  42173. var parsedBox = boxes[index];
  42174. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  42175. }
  42176. }
  42177. // Spheres
  42178. var spheres = geometries.spheres;
  42179. if (spheres) {
  42180. for (index = 0, cache = spheres.length; index < cache; index++) {
  42181. var parsedSphere = spheres[index];
  42182. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  42183. }
  42184. }
  42185. // Cylinders
  42186. var cylinders = geometries.cylinders;
  42187. if (cylinders) {
  42188. for (index = 0, cache = cylinders.length; index < cache; index++) {
  42189. var parsedCylinder = cylinders[index];
  42190. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  42191. }
  42192. }
  42193. // Toruses
  42194. var toruses = geometries.toruses;
  42195. if (toruses) {
  42196. for (index = 0, cache = toruses.length; index < cache; index++) {
  42197. var parsedTorus = toruses[index];
  42198. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  42199. }
  42200. }
  42201. // Grounds
  42202. var grounds = geometries.grounds;
  42203. if (grounds) {
  42204. for (index = 0, cache = grounds.length; index < cache; index++) {
  42205. var parsedGround = grounds[index];
  42206. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  42207. }
  42208. }
  42209. // Planes
  42210. var planes = geometries.planes;
  42211. if (planes) {
  42212. for (index = 0, cache = planes.length; index < cache; index++) {
  42213. var parsedPlane = planes[index];
  42214. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  42215. }
  42216. }
  42217. // TorusKnots
  42218. var torusKnots = geometries.torusKnots;
  42219. if (torusKnots) {
  42220. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  42221. var parsedTorusKnot = torusKnots[index];
  42222. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  42223. }
  42224. }
  42225. // VertexData
  42226. var vertexData = geometries.vertexData;
  42227. if (vertexData) {
  42228. for (index = 0, cache = vertexData.length; index < cache; index++) {
  42229. var parsedVertexData = vertexData[index];
  42230. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  42231. }
  42232. }
  42233. }
  42234. // Meshes
  42235. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  42236. var parsedMesh = parsedData.meshes[index];
  42237. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  42238. log += (index === 0 ? "\n\tMeshes:" : "");
  42239. log += "\n\t\t" + mesh.toString(fullDetails);
  42240. }
  42241. // Cameras
  42242. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  42243. var parsedCamera = parsedData.cameras[index];
  42244. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  42245. log += (index === 0 ? "\n\tCameras:" : "");
  42246. log += "\n\t\t" + camera.toString(fullDetails);
  42247. }
  42248. if (parsedData.activeCameraID) {
  42249. scene.setActiveCameraByID(parsedData.activeCameraID);
  42250. }
  42251. // Browsing all the graph to connect the dots
  42252. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  42253. var camera = scene.cameras[index];
  42254. if (camera._waitingParentId) {
  42255. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  42256. camera._waitingParentId = undefined;
  42257. }
  42258. }
  42259. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  42260. var light = scene.lights[index];
  42261. if (light._waitingParentId) {
  42262. light.parent = scene.getLastEntryByID(light._waitingParentId);
  42263. light._waitingParentId = undefined;
  42264. }
  42265. }
  42266. // Sounds
  42267. var loadedSounds = [];
  42268. var loadedSound;
  42269. if (BABYLON.AudioEngine && parsedData.sounds) {
  42270. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  42271. var parsedSound = parsedData.sounds[index];
  42272. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42273. if (!parsedSound.url)
  42274. parsedSound.url = parsedSound.name;
  42275. if (!loadedSounds[parsedSound.url]) {
  42276. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  42277. loadedSounds[parsedSound.url] = loadedSound;
  42278. }
  42279. else {
  42280. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  42281. }
  42282. }
  42283. else {
  42284. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  42285. }
  42286. }
  42287. }
  42288. loadedSounds = [];
  42289. // Connect parents & children and parse actions
  42290. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  42291. var mesh = scene.meshes[index];
  42292. if (mesh._waitingParentId) {
  42293. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  42294. mesh._waitingParentId = undefined;
  42295. }
  42296. if (mesh._waitingActions) {
  42297. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  42298. mesh._waitingActions = undefined;
  42299. }
  42300. }
  42301. // freeze world matrix application
  42302. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  42303. var currentMesh = scene.meshes[index];
  42304. if (currentMesh._waitingFreezeWorldMatrix) {
  42305. currentMesh.freezeWorldMatrix();
  42306. currentMesh._waitingFreezeWorldMatrix = undefined;
  42307. }
  42308. else {
  42309. currentMesh.computeWorldMatrix(true);
  42310. }
  42311. }
  42312. // Particles Systems
  42313. if (parsedData.particleSystems) {
  42314. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  42315. var parsedParticleSystem = parsedData.particleSystems[index];
  42316. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  42317. }
  42318. }
  42319. // Lens flares
  42320. if (parsedData.lensFlareSystems) {
  42321. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  42322. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  42323. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  42324. }
  42325. }
  42326. // Shadows
  42327. if (parsedData.shadowGenerators) {
  42328. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  42329. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  42330. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  42331. }
  42332. }
  42333. // Lights exclusions / inclusions
  42334. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  42335. var light = scene.lights[index];
  42336. // Excluded check
  42337. if (light._excludedMeshesIds.length > 0) {
  42338. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  42339. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  42340. if (excludedMesh) {
  42341. light.excludedMeshes.push(excludedMesh);
  42342. }
  42343. }
  42344. light._excludedMeshesIds = [];
  42345. }
  42346. // Included check
  42347. if (light._includedOnlyMeshesIds.length > 0) {
  42348. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  42349. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  42350. if (includedOnlyMesh) {
  42351. light.includedOnlyMeshes.push(includedOnlyMesh);
  42352. }
  42353. }
  42354. light._includedOnlyMeshesIds = [];
  42355. }
  42356. }
  42357. // Actions (scene)
  42358. if (parsedData.actions) {
  42359. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  42360. }
  42361. // Finish
  42362. return true;
  42363. }
  42364. catch (err) {
  42365. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  42366. log = null;
  42367. throw err;
  42368. }
  42369. finally {
  42370. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  42371. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  42372. }
  42373. }
  42374. }
  42375. });
  42376. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42377. })(BABYLON || (BABYLON = {}));
  42378. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  42379. var BABYLON;
  42380. (function (BABYLON) {
  42381. var FilesInput = (function () {
  42382. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  42383. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  42384. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  42385. this._engine = p_engine;
  42386. this._canvas = p_canvas;
  42387. this._currentScene = p_scene;
  42388. this._sceneLoadedCallback = p_sceneLoadedCallback;
  42389. this._progressCallback = p_progressCallback;
  42390. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  42391. this._textureLoadingCallback = p_textureLoadingCallback;
  42392. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  42393. }
  42394. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  42395. var _this = this;
  42396. if (p_elementToMonitor) {
  42397. this._elementToMonitor = p_elementToMonitor;
  42398. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  42399. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  42400. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  42401. }
  42402. };
  42403. FilesInput.prototype.renderFunction = function () {
  42404. if (this._additionnalRenderLoopLogicCallback) {
  42405. this._additionnalRenderLoopLogicCallback();
  42406. }
  42407. if (this._currentScene) {
  42408. if (this._textureLoadingCallback) {
  42409. var remaining = this._currentScene.getWaitingItemsCount();
  42410. if (remaining > 0) {
  42411. this._textureLoadingCallback(remaining);
  42412. }
  42413. }
  42414. this._currentScene.render();
  42415. }
  42416. };
  42417. FilesInput.prototype.drag = function (e) {
  42418. e.stopPropagation();
  42419. e.preventDefault();
  42420. };
  42421. FilesInput.prototype.drop = function (eventDrop) {
  42422. eventDrop.stopPropagation();
  42423. eventDrop.preventDefault();
  42424. this.loadFiles(eventDrop);
  42425. };
  42426. FilesInput.prototype.loadFiles = function (event) {
  42427. if (this._startingProcessingFilesCallback)
  42428. this._startingProcessingFilesCallback();
  42429. // Handling data transfer via drag'n'drop
  42430. if (event && event.dataTransfer && event.dataTransfer.files) {
  42431. this._filesToLoad = event.dataTransfer.files;
  42432. }
  42433. // Handling files from input files
  42434. if (event && event.target && event.target.files) {
  42435. this._filesToLoad = event.target.files;
  42436. }
  42437. if (this._filesToLoad && this._filesToLoad.length > 0) {
  42438. for (var i = 0; i < this._filesToLoad.length; i++) {
  42439. var name_1 = this._filesToLoad[i].name.toLowerCase();
  42440. var extension = name_1.split('.').pop();
  42441. var type = this._filesToLoad[i].type;
  42442. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  42443. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  42444. this._sceneFileToLoad = this._filesToLoad[i];
  42445. }
  42446. else {
  42447. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  42448. }
  42449. }
  42450. this.reload();
  42451. }
  42452. };
  42453. FilesInput.prototype.reload = function () {
  42454. var _this = this;
  42455. var that = this;
  42456. // If a ".babylon" file has been provided
  42457. if (this._sceneFileToLoad) {
  42458. if (this._currentScene) {
  42459. if (BABYLON.Tools.errorsCount > 0) {
  42460. BABYLON.Tools.ClearLogCache();
  42461. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  42462. }
  42463. this._engine.stopRenderLoop();
  42464. this._currentScene.dispose();
  42465. }
  42466. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  42467. that._currentScene = newScene;
  42468. // Wait for textures and shaders to be ready
  42469. that._currentScene.executeWhenReady(function () {
  42470. if (that._sceneLoadedCallback) {
  42471. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  42472. }
  42473. that._engine.runRenderLoop(function () { that.renderFunction(); });
  42474. });
  42475. }, function (progress) {
  42476. if (_this._progressCallback) {
  42477. _this._progressCallback(progress);
  42478. }
  42479. });
  42480. }
  42481. else {
  42482. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  42483. }
  42484. };
  42485. return FilesInput;
  42486. }());
  42487. FilesInput.FilesToLoad = new Array();
  42488. BABYLON.FilesInput = FilesInput;
  42489. })(BABYLON || (BABYLON = {}));
  42490. //# sourceMappingURL=babylon.filesInput.js.map
  42491. var BABYLON;
  42492. (function (BABYLON) {
  42493. /**
  42494. * This class implement a typical dictionary using a string as key and the generic type T as value.
  42495. * The underlying implementation relies on an associative array to ensure the best performances.
  42496. * The value can be anything including 'null' but except 'undefined'
  42497. */
  42498. var StringDictionary = (function () {
  42499. function StringDictionary() {
  42500. this._count = 0;
  42501. this._data = {};
  42502. }
  42503. /**
  42504. * This will clear this dictionary and copy the content from the 'source' one.
  42505. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  42506. * @param source the dictionary to take the content from and copy to this dictionary
  42507. */
  42508. StringDictionary.prototype.copyFrom = function (source) {
  42509. var _this = this;
  42510. this.clear();
  42511. source.forEach(function (t, v) { return _this.add(t, v); });
  42512. };
  42513. /**
  42514. * Get a value based from its key
  42515. * @param key the given key to get the matching value from
  42516. * @return the value if found, otherwise undefined is returned
  42517. */
  42518. StringDictionary.prototype.get = function (key) {
  42519. var val = this._data[key];
  42520. if (val !== undefined) {
  42521. return val;
  42522. }
  42523. return undefined;
  42524. };
  42525. /**
  42526. * Get a value from its key or add it if it doesn't exist.
  42527. * This method will ensure you that a given key/data will be present in the dictionary.
  42528. * @param key the given key to get the matching value from
  42529. * @param factory the factory that will create the value if the key is not present in the dictionary.
  42530. * The factory will only be invoked if there's no data for the given key.
  42531. * @return the value corresponding to the key.
  42532. */
  42533. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  42534. var val = this.get(key);
  42535. if (val !== undefined) {
  42536. return val;
  42537. }
  42538. val = factory(key);
  42539. if (val) {
  42540. this.add(key, val);
  42541. }
  42542. return val;
  42543. };
  42544. /**
  42545. * Get a value from its key if present in the dictionary otherwise add it
  42546. * @param key the key to get the value from
  42547. * @param val if there's no such key/value pair in the dictionary add it with this value
  42548. * @return the value corresponding to the key
  42549. */
  42550. StringDictionary.prototype.getOrAdd = function (key, val) {
  42551. var curVal = this.get(key);
  42552. if (curVal !== undefined) {
  42553. return curVal;
  42554. }
  42555. this.add(key, val);
  42556. return val;
  42557. };
  42558. /**
  42559. * Check if there's a given key in the dictionary
  42560. * @param key the key to check for
  42561. * @return true if the key is present, false otherwise
  42562. */
  42563. StringDictionary.prototype.contains = function (key) {
  42564. return this._data[key] !== undefined;
  42565. };
  42566. /**
  42567. * Add a new key and its corresponding value
  42568. * @param key the key to add
  42569. * @param value the value corresponding to the key
  42570. * @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
  42571. */
  42572. StringDictionary.prototype.add = function (key, value) {
  42573. if (this._data[key] !== undefined) {
  42574. return false;
  42575. }
  42576. this._data[key] = value;
  42577. ++this._count;
  42578. return true;
  42579. };
  42580. StringDictionary.prototype.set = function (key, value) {
  42581. if (this._data[key] === undefined) {
  42582. return false;
  42583. }
  42584. this._data[key] = value;
  42585. return true;
  42586. };
  42587. /**
  42588. * Get the element of the given key and remove it from the dictionary
  42589. * @param key
  42590. */
  42591. StringDictionary.prototype.getAndRemove = function (key) {
  42592. var val = this.get(key);
  42593. if (val !== undefined) {
  42594. delete this._data[key];
  42595. --this._count;
  42596. return val;
  42597. }
  42598. return null;
  42599. };
  42600. /**
  42601. * Remove a key/value from the dictionary.
  42602. * @param key the key to remove
  42603. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  42604. */
  42605. StringDictionary.prototype.remove = function (key) {
  42606. if (this.contains(key)) {
  42607. delete this._data[key];
  42608. --this._count;
  42609. return true;
  42610. }
  42611. return false;
  42612. };
  42613. /**
  42614. * Clear the whole content of the dictionary
  42615. */
  42616. StringDictionary.prototype.clear = function () {
  42617. this._data = {};
  42618. this._count = 0;
  42619. };
  42620. Object.defineProperty(StringDictionary.prototype, "count", {
  42621. get: function () {
  42622. return this._count;
  42623. },
  42624. enumerable: true,
  42625. configurable: true
  42626. });
  42627. /**
  42628. * Execute a callback on each key/val of the dictionary.
  42629. * Note that you can remove any element in this dictionary in the callback implementation
  42630. * @param callback the callback to execute on a given key/value pair
  42631. */
  42632. StringDictionary.prototype.forEach = function (callback) {
  42633. for (var cur in this._data) {
  42634. var val = this._data[cur];
  42635. callback(cur, val);
  42636. }
  42637. };
  42638. /**
  42639. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  42640. * If the callback returns null or undefined the method will iterate to the next key/value pair
  42641. * Note that you can remove any element in this dictionary in the callback implementation
  42642. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  42643. */
  42644. StringDictionary.prototype.first = function (callback) {
  42645. for (var cur in this._data) {
  42646. var val = this._data[cur];
  42647. var res = callback(cur, val);
  42648. if (res) {
  42649. return res;
  42650. }
  42651. }
  42652. return null;
  42653. };
  42654. return StringDictionary;
  42655. }());
  42656. BABYLON.StringDictionary = StringDictionary;
  42657. })(BABYLON || (BABYLON = {}));
  42658. //# sourceMappingURL=babylon.stringDictionary.js.map
  42659. var BABYLON;
  42660. (function (BABYLON) {
  42661. var Tags = (function () {
  42662. function Tags() {
  42663. }
  42664. Tags.EnableFor = function (obj) {
  42665. obj._tags = obj._tags || {};
  42666. obj.hasTags = function () {
  42667. return Tags.HasTags(obj);
  42668. };
  42669. obj.addTags = function (tagsString) {
  42670. return Tags.AddTagsTo(obj, tagsString);
  42671. };
  42672. obj.removeTags = function (tagsString) {
  42673. return Tags.RemoveTagsFrom(obj, tagsString);
  42674. };
  42675. obj.matchesTagsQuery = function (tagsQuery) {
  42676. return Tags.MatchesQuery(obj, tagsQuery);
  42677. };
  42678. };
  42679. Tags.DisableFor = function (obj) {
  42680. delete obj._tags;
  42681. delete obj.hasTags;
  42682. delete obj.addTags;
  42683. delete obj.removeTags;
  42684. delete obj.matchesTagsQuery;
  42685. };
  42686. Tags.HasTags = function (obj) {
  42687. if (!obj._tags) {
  42688. return false;
  42689. }
  42690. return !BABYLON.Tools.IsEmpty(obj._tags);
  42691. };
  42692. Tags.GetTags = function (obj, asString) {
  42693. if (asString === void 0) { asString = true; }
  42694. if (!obj._tags) {
  42695. return null;
  42696. }
  42697. if (asString) {
  42698. var tagsArray = [];
  42699. for (var tag in obj._tags) {
  42700. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  42701. tagsArray.push(tag);
  42702. }
  42703. }
  42704. return tagsArray.join(" ");
  42705. }
  42706. else {
  42707. return obj._tags;
  42708. }
  42709. };
  42710. // the tags 'true' and 'false' are reserved and cannot be used as tags
  42711. // a tag cannot start with '||', '&&', and '!'
  42712. // it cannot contain whitespaces
  42713. Tags.AddTagsTo = function (obj, tagsString) {
  42714. if (!tagsString) {
  42715. return;
  42716. }
  42717. if (typeof tagsString !== "string") {
  42718. return;
  42719. }
  42720. var tags = tagsString.split(" ");
  42721. tags.forEach(function (tag, index, array) {
  42722. Tags._AddTagTo(obj, tag);
  42723. });
  42724. };
  42725. Tags._AddTagTo = function (obj, tag) {
  42726. tag = tag.trim();
  42727. if (tag === "" || tag === "true" || tag === "false") {
  42728. return;
  42729. }
  42730. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  42731. return;
  42732. }
  42733. Tags.EnableFor(obj);
  42734. obj._tags[tag] = true;
  42735. };
  42736. Tags.RemoveTagsFrom = function (obj, tagsString) {
  42737. if (!Tags.HasTags(obj)) {
  42738. return;
  42739. }
  42740. var tags = tagsString.split(" ");
  42741. for (var t in tags) {
  42742. Tags._RemoveTagFrom(obj, tags[t]);
  42743. }
  42744. };
  42745. Tags._RemoveTagFrom = function (obj, tag) {
  42746. delete obj._tags[tag];
  42747. };
  42748. Tags.MatchesQuery = function (obj, tagsQuery) {
  42749. if (tagsQuery === undefined) {
  42750. return true;
  42751. }
  42752. if (tagsQuery === "") {
  42753. return Tags.HasTags(obj);
  42754. }
  42755. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  42756. };
  42757. return Tags;
  42758. }());
  42759. BABYLON.Tags = Tags;
  42760. })(BABYLON || (BABYLON = {}));
  42761. //# sourceMappingURL=babylon.tags.js.map
  42762. var BABYLON;
  42763. (function (BABYLON) {
  42764. var Internals;
  42765. (function (Internals) {
  42766. var AndOrNotEvaluator = (function () {
  42767. function AndOrNotEvaluator() {
  42768. }
  42769. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  42770. if (!query.match(/\([^\(\)]*\)/g)) {
  42771. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  42772. }
  42773. else {
  42774. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  42775. // remove parenthesis
  42776. r = r.slice(1, r.length - 1);
  42777. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  42778. });
  42779. }
  42780. if (query === "true") {
  42781. return true;
  42782. }
  42783. if (query === "false") {
  42784. return false;
  42785. }
  42786. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  42787. };
  42788. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  42789. evaluateCallback = evaluateCallback || (function (r) {
  42790. return r === "true" ? true : false;
  42791. });
  42792. var result;
  42793. var or = parenthesisContent.split("||");
  42794. for (var i in or) {
  42795. if (or.hasOwnProperty(i)) {
  42796. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  42797. var and = ori.split("&&");
  42798. if (and.length > 1) {
  42799. for (var j = 0; j < and.length; ++j) {
  42800. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  42801. if (andj !== "true" && andj !== "false") {
  42802. if (andj[0] === "!") {
  42803. result = !evaluateCallback(andj.substring(1));
  42804. }
  42805. else {
  42806. result = evaluateCallback(andj);
  42807. }
  42808. }
  42809. else {
  42810. result = andj === "true" ? true : false;
  42811. }
  42812. if (!result) {
  42813. ori = "false";
  42814. break;
  42815. }
  42816. }
  42817. }
  42818. if (result || ori === "true") {
  42819. result = true;
  42820. break;
  42821. }
  42822. // result equals false (or undefined)
  42823. if (ori !== "true" && ori !== "false") {
  42824. if (ori[0] === "!") {
  42825. result = !evaluateCallback(ori.substring(1));
  42826. }
  42827. else {
  42828. result = evaluateCallback(ori);
  42829. }
  42830. }
  42831. else {
  42832. result = ori === "true" ? true : false;
  42833. }
  42834. }
  42835. }
  42836. // the whole parenthesis scope is replaced by 'true' or 'false'
  42837. return result ? "true" : "false";
  42838. };
  42839. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  42840. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  42841. // remove whitespaces
  42842. r = r.replace(/[\s]/g, function () { return ""; });
  42843. return r.length % 2 ? "!" : "";
  42844. });
  42845. booleanString = booleanString.trim();
  42846. if (booleanString === "!true") {
  42847. booleanString = "false";
  42848. }
  42849. else if (booleanString === "!false") {
  42850. booleanString = "true";
  42851. }
  42852. return booleanString;
  42853. };
  42854. return AndOrNotEvaluator;
  42855. }());
  42856. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  42857. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42858. })(BABYLON || (BABYLON = {}));
  42859. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  42860. var BABYLON;
  42861. (function (BABYLON) {
  42862. var Database = (function () {
  42863. function Database(urlToScene, callbackManifestChecked) {
  42864. // Handling various flavors of prefixed version of IndexedDB
  42865. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  42866. this.callbackManifestChecked = callbackManifestChecked;
  42867. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  42868. this.db = null;
  42869. this.enableSceneOffline = false;
  42870. this.enableTexturesOffline = false;
  42871. this.manifestVersionFound = 0;
  42872. this.mustUpdateRessources = false;
  42873. this.hasReachedQuota = false;
  42874. if (!Database.IDBStorageEnabled) {
  42875. this.callbackManifestChecked(true);
  42876. }
  42877. else {
  42878. this.checkManifestFile();
  42879. }
  42880. }
  42881. Database.prototype.checkManifestFile = function () {
  42882. var _this = this;
  42883. function noManifestFile() {
  42884. that.enableSceneOffline = false;
  42885. that.enableTexturesOffline = false;
  42886. that.callbackManifestChecked(false);
  42887. }
  42888. var that = this;
  42889. var timeStampUsed = false;
  42890. var manifestURL = this.currentSceneUrl + ".manifest";
  42891. var xhr = new XMLHttpRequest();
  42892. if (navigator.onLine) {
  42893. // Adding a timestamp to by-pass browsers' cache
  42894. timeStampUsed = true;
  42895. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  42896. }
  42897. xhr.open("GET", manifestURL, true);
  42898. xhr.addEventListener("load", function () {
  42899. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  42900. try {
  42901. var manifestFile = JSON.parse(xhr.response);
  42902. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  42903. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  42904. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  42905. _this.manifestVersionFound = manifestFile.version;
  42906. }
  42907. if (_this.callbackManifestChecked) {
  42908. _this.callbackManifestChecked(true);
  42909. }
  42910. }
  42911. catch (ex) {
  42912. noManifestFile();
  42913. }
  42914. }
  42915. else {
  42916. noManifestFile();
  42917. }
  42918. }, false);
  42919. xhr.addEventListener("error", function (event) {
  42920. if (timeStampUsed) {
  42921. timeStampUsed = false;
  42922. // Let's retry without the timeStamp
  42923. // It could fail when coupled with HTML5 Offline API
  42924. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  42925. xhr.open("GET", retryManifestURL, true);
  42926. xhr.send();
  42927. }
  42928. else {
  42929. noManifestFile();
  42930. }
  42931. }, false);
  42932. try {
  42933. xhr.send();
  42934. }
  42935. catch (ex) {
  42936. BABYLON.Tools.Error("Error on XHR send request.");
  42937. that.callbackManifestChecked(false);
  42938. }
  42939. };
  42940. Database.prototype.openAsync = function (successCallback, errorCallback) {
  42941. var _this = this;
  42942. function handleError() {
  42943. that.isSupported = false;
  42944. if (errorCallback)
  42945. errorCallback();
  42946. }
  42947. var that = this;
  42948. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  42949. // Your browser doesn't support IndexedDB
  42950. this.isSupported = false;
  42951. if (errorCallback)
  42952. errorCallback();
  42953. }
  42954. else {
  42955. // If the DB hasn't been opened or created yet
  42956. if (!this.db) {
  42957. this.hasReachedQuota = false;
  42958. this.isSupported = true;
  42959. var request = this.idbFactory.open("babylonjs", 1);
  42960. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  42961. request.onerror = function (event) {
  42962. handleError();
  42963. };
  42964. // executes when a version change transaction cannot complete due to other active transactions
  42965. request.onblocked = function (event) {
  42966. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  42967. handleError();
  42968. };
  42969. // DB has been opened successfully
  42970. request.onsuccess = function (event) {
  42971. _this.db = request.result;
  42972. successCallback();
  42973. };
  42974. // Initialization of the DB. Creating Scenes & Textures stores
  42975. request.onupgradeneeded = function (event) {
  42976. _this.db = (event.target).result;
  42977. try {
  42978. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  42979. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  42980. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  42981. }
  42982. catch (ex) {
  42983. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  42984. handleError();
  42985. }
  42986. };
  42987. }
  42988. else {
  42989. if (successCallback)
  42990. successCallback();
  42991. }
  42992. }
  42993. };
  42994. Database.prototype.loadImageFromDB = function (url, image) {
  42995. var _this = this;
  42996. var completeURL = Database.ReturnFullUrlLocation(url);
  42997. var saveAndLoadImage = function () {
  42998. if (!_this.hasReachedQuota && _this.db !== null) {
  42999. // the texture is not yet in the DB, let's try to save it
  43000. _this._saveImageIntoDBAsync(completeURL, image);
  43001. }
  43002. else {
  43003. image.src = url;
  43004. }
  43005. };
  43006. if (!this.mustUpdateRessources) {
  43007. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  43008. }
  43009. else {
  43010. saveAndLoadImage();
  43011. }
  43012. };
  43013. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  43014. if (this.isSupported && this.db !== null) {
  43015. var texture;
  43016. var transaction = this.db.transaction(["textures"]);
  43017. transaction.onabort = function (event) {
  43018. image.src = url;
  43019. };
  43020. transaction.oncomplete = function (event) {
  43021. var blobTextureURL;
  43022. if (texture) {
  43023. var URL = window.URL || window.webkitURL;
  43024. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  43025. image.onerror = function () {
  43026. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  43027. image.src = url;
  43028. };
  43029. image.src = blobTextureURL;
  43030. }
  43031. else {
  43032. notInDBCallback();
  43033. }
  43034. };
  43035. var getRequest = transaction.objectStore("textures").get(url);
  43036. getRequest.onsuccess = function (event) {
  43037. texture = (event.target).result;
  43038. };
  43039. getRequest.onerror = function (event) {
  43040. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  43041. image.src = url;
  43042. };
  43043. }
  43044. else {
  43045. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  43046. image.src = url;
  43047. }
  43048. };
  43049. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  43050. var _this = this;
  43051. if (this.isSupported) {
  43052. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  43053. var generateBlobUrl = function () {
  43054. var blobTextureURL;
  43055. if (blob) {
  43056. var URL = window.URL || window.webkitURL;
  43057. try {
  43058. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  43059. }
  43060. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  43061. catch (ex) {
  43062. blobTextureURL = URL.createObjectURL(blob);
  43063. }
  43064. }
  43065. image.src = blobTextureURL;
  43066. };
  43067. if (Database.IsUASupportingBlobStorage) {
  43068. var xhr = new XMLHttpRequest(), blob;
  43069. xhr.open("GET", url, true);
  43070. xhr.responseType = "blob";
  43071. xhr.addEventListener("load", function () {
  43072. if (xhr.status === 200) {
  43073. // Blob as response (XHR2)
  43074. blob = xhr.response;
  43075. var transaction = _this.db.transaction(["textures"], "readwrite");
  43076. // the transaction could abort because of a QuotaExceededError error
  43077. transaction.onabort = function (event) {
  43078. try {
  43079. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  43080. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  43081. _this.hasReachedQuota = true;
  43082. }
  43083. }
  43084. catch (ex) { }
  43085. generateBlobUrl();
  43086. };
  43087. transaction.oncomplete = function (event) {
  43088. generateBlobUrl();
  43089. };
  43090. var newTexture = { textureUrl: url, data: blob };
  43091. try {
  43092. // Put the blob into the dabase
  43093. var addRequest = transaction.objectStore("textures").put(newTexture);
  43094. addRequest.onsuccess = function (event) {
  43095. };
  43096. addRequest.onerror = function (event) {
  43097. generateBlobUrl();
  43098. };
  43099. }
  43100. catch (ex) {
  43101. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  43102. if (ex.code === 25) {
  43103. Database.IsUASupportingBlobStorage = false;
  43104. }
  43105. image.src = url;
  43106. }
  43107. }
  43108. else {
  43109. image.src = url;
  43110. }
  43111. }, false);
  43112. xhr.addEventListener("error", function (event) {
  43113. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  43114. image.src = url;
  43115. }, false);
  43116. xhr.send();
  43117. }
  43118. else {
  43119. image.src = url;
  43120. }
  43121. }
  43122. else {
  43123. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  43124. image.src = url;
  43125. }
  43126. };
  43127. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  43128. var _this = this;
  43129. var updateVersion = function (event) {
  43130. // the version is not yet in the DB or we need to update it
  43131. _this._saveVersionIntoDBAsync(url, versionLoaded);
  43132. };
  43133. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  43134. };
  43135. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  43136. var _this = this;
  43137. if (this.isSupported) {
  43138. var version;
  43139. try {
  43140. var transaction = this.db.transaction(["versions"]);
  43141. transaction.oncomplete = function (event) {
  43142. if (version) {
  43143. // If the version in the JSON file is > than the version in DB
  43144. if (_this.manifestVersionFound > version.data) {
  43145. _this.mustUpdateRessources = true;
  43146. updateInDBCallback();
  43147. }
  43148. else {
  43149. callback(version.data);
  43150. }
  43151. }
  43152. else {
  43153. _this.mustUpdateRessources = true;
  43154. updateInDBCallback();
  43155. }
  43156. };
  43157. transaction.onabort = function (event) {
  43158. callback(-1);
  43159. };
  43160. var getRequest = transaction.objectStore("versions").get(url);
  43161. getRequest.onsuccess = function (event) {
  43162. version = (event.target).result;
  43163. };
  43164. getRequest.onerror = function (event) {
  43165. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  43166. callback(-1);
  43167. };
  43168. }
  43169. catch (ex) {
  43170. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  43171. callback(-1);
  43172. }
  43173. }
  43174. else {
  43175. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  43176. callback(-1);
  43177. }
  43178. };
  43179. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  43180. var _this = this;
  43181. if (this.isSupported && !this.hasReachedQuota) {
  43182. try {
  43183. // Open a transaction to the database
  43184. var transaction = this.db.transaction(["versions"], "readwrite");
  43185. // the transaction could abort because of a QuotaExceededError error
  43186. transaction.onabort = function (event) {
  43187. try {
  43188. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  43189. _this.hasReachedQuota = true;
  43190. }
  43191. }
  43192. catch (ex) { }
  43193. callback(-1);
  43194. };
  43195. transaction.oncomplete = function (event) {
  43196. callback(_this.manifestVersionFound);
  43197. };
  43198. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  43199. // Put the scene into the database
  43200. var addRequest = transaction.objectStore("versions").put(newVersion);
  43201. addRequest.onsuccess = function (event) {
  43202. };
  43203. addRequest.onerror = function (event) {
  43204. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  43205. };
  43206. }
  43207. catch (ex) {
  43208. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  43209. callback(-1);
  43210. }
  43211. }
  43212. else {
  43213. callback(-1);
  43214. }
  43215. };
  43216. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  43217. var _this = this;
  43218. var completeUrl = Database.ReturnFullUrlLocation(url);
  43219. var saveAndLoadFile = function (event) {
  43220. // the scene is not yet in the DB, let's try to save it
  43221. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  43222. };
  43223. this._checkVersionFromDB(completeUrl, function (version) {
  43224. if (version !== -1) {
  43225. if (!_this.mustUpdateRessources) {
  43226. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  43227. }
  43228. else {
  43229. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  43230. }
  43231. }
  43232. else {
  43233. errorCallback();
  43234. }
  43235. });
  43236. };
  43237. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  43238. if (this.isSupported) {
  43239. var targetStore;
  43240. if (url.indexOf(".babylon") !== -1) {
  43241. targetStore = "scenes";
  43242. }
  43243. else {
  43244. targetStore = "textures";
  43245. }
  43246. var file;
  43247. var transaction = this.db.transaction([targetStore]);
  43248. transaction.oncomplete = function (event) {
  43249. if (file) {
  43250. callback(file.data);
  43251. }
  43252. else {
  43253. notInDBCallback();
  43254. }
  43255. };
  43256. transaction.onabort = function (event) {
  43257. notInDBCallback();
  43258. };
  43259. var getRequest = transaction.objectStore(targetStore).get(url);
  43260. getRequest.onsuccess = function (event) {
  43261. file = (event.target).result;
  43262. };
  43263. getRequest.onerror = function (event) {
  43264. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  43265. notInDBCallback();
  43266. };
  43267. }
  43268. else {
  43269. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  43270. callback();
  43271. }
  43272. };
  43273. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  43274. var _this = this;
  43275. if (this.isSupported) {
  43276. var targetStore;
  43277. if (url.indexOf(".babylon") !== -1) {
  43278. targetStore = "scenes";
  43279. }
  43280. else {
  43281. targetStore = "textures";
  43282. }
  43283. // Create XHR
  43284. var xhr = new XMLHttpRequest(), fileData;
  43285. xhr.open("GET", url, true);
  43286. if (useArrayBuffer) {
  43287. xhr.responseType = "arraybuffer";
  43288. }
  43289. xhr.onprogress = progressCallback;
  43290. xhr.addEventListener("load", function () {
  43291. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  43292. // Blob as response (XHR2)
  43293. //fileData = xhr.responseText;
  43294. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  43295. if (!_this.hasReachedQuota) {
  43296. // Open a transaction to the database
  43297. var transaction = _this.db.transaction([targetStore], "readwrite");
  43298. // the transaction could abort because of a QuotaExceededError error
  43299. transaction.onabort = function (event) {
  43300. try {
  43301. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  43302. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  43303. _this.hasReachedQuota = true;
  43304. }
  43305. }
  43306. catch (ex) { }
  43307. callback(fileData);
  43308. };
  43309. transaction.oncomplete = function (event) {
  43310. callback(fileData);
  43311. };
  43312. var newFile;
  43313. if (targetStore === "scenes") {
  43314. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  43315. }
  43316. else {
  43317. newFile = { textureUrl: url, data: fileData };
  43318. }
  43319. try {
  43320. // Put the scene into the database
  43321. var addRequest = transaction.objectStore(targetStore).put(newFile);
  43322. addRequest.onsuccess = function (event) {
  43323. };
  43324. addRequest.onerror = function (event) {
  43325. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  43326. };
  43327. }
  43328. catch (ex) {
  43329. callback(fileData);
  43330. }
  43331. }
  43332. else {
  43333. callback(fileData);
  43334. }
  43335. }
  43336. else {
  43337. callback();
  43338. }
  43339. }, false);
  43340. xhr.addEventListener("error", function (event) {
  43341. BABYLON.Tools.Error("error on XHR request.");
  43342. callback();
  43343. }, false);
  43344. xhr.send();
  43345. }
  43346. else {
  43347. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  43348. callback();
  43349. }
  43350. };
  43351. return Database;
  43352. }());
  43353. Database.IsUASupportingBlobStorage = true;
  43354. Database.IDBStorageEnabled = true;
  43355. Database.parseURL = function (url) {
  43356. var a = document.createElement('a');
  43357. a.href = url;
  43358. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  43359. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  43360. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  43361. return absLocation;
  43362. };
  43363. Database.ReturnFullUrlLocation = function (url) {
  43364. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  43365. return (Database.parseURL(window.location.href) + url);
  43366. }
  43367. else {
  43368. return url;
  43369. }
  43370. };
  43371. BABYLON.Database = Database;
  43372. })(BABYLON || (BABYLON = {}));
  43373. //# sourceMappingURL=babylon.database.js.map
  43374. var BABYLON;
  43375. (function (BABYLON) {
  43376. var FresnelParameters = (function () {
  43377. function FresnelParameters() {
  43378. this._isEnabled = true;
  43379. this.leftColor = BABYLON.Color3.White();
  43380. this.rightColor = BABYLON.Color3.Black();
  43381. this.bias = 0;
  43382. this.power = 1;
  43383. }
  43384. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  43385. get: function () {
  43386. return this._isEnabled;
  43387. },
  43388. set: function (value) {
  43389. if (this._isEnabled === value) {
  43390. return;
  43391. }
  43392. this._isEnabled = value;
  43393. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43394. },
  43395. enumerable: true,
  43396. configurable: true
  43397. });
  43398. FresnelParameters.prototype.clone = function () {
  43399. var newFresnelParameters = new FresnelParameters();
  43400. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  43401. return newFresnelParameters;
  43402. };
  43403. FresnelParameters.prototype.serialize = function () {
  43404. var serializationObject = {};
  43405. serializationObject.isEnabled = this.isEnabled;
  43406. serializationObject.leftColor = this.leftColor;
  43407. serializationObject.rightColor = this.rightColor;
  43408. serializationObject.bias = this.bias;
  43409. serializationObject.power = this.power;
  43410. return serializationObject;
  43411. };
  43412. FresnelParameters.Parse = function (parsedFresnelParameters) {
  43413. var fresnelParameters = new FresnelParameters();
  43414. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  43415. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  43416. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  43417. fresnelParameters.bias = parsedFresnelParameters.bias;
  43418. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  43419. return fresnelParameters;
  43420. };
  43421. return FresnelParameters;
  43422. }());
  43423. BABYLON.FresnelParameters = FresnelParameters;
  43424. })(BABYLON || (BABYLON = {}));
  43425. //# sourceMappingURL=babylon.fresnelParameters.js.map
  43426. var BABYLON;
  43427. (function (BABYLON) {
  43428. var MultiMaterial = (function (_super) {
  43429. __extends(MultiMaterial, _super);
  43430. function MultiMaterial(name, scene) {
  43431. var _this = _super.call(this, name, scene, true) || this;
  43432. _this.subMaterials = new Array();
  43433. scene.multiMaterials.push(_this);
  43434. return _this;
  43435. }
  43436. // Properties
  43437. MultiMaterial.prototype.getSubMaterial = function (index) {
  43438. if (index < 0 || index >= this.subMaterials.length) {
  43439. return this.getScene().defaultMaterial;
  43440. }
  43441. return this.subMaterials[index];
  43442. };
  43443. // Methods
  43444. MultiMaterial.prototype.getClassName = function () {
  43445. return "MultiMaterial";
  43446. };
  43447. MultiMaterial.prototype.isReady = function (mesh) {
  43448. for (var index = 0; index < this.subMaterials.length; index++) {
  43449. var subMaterial = this.subMaterials[index];
  43450. if (subMaterial) {
  43451. if (!this.subMaterials[index].isReady(mesh)) {
  43452. return false;
  43453. }
  43454. }
  43455. }
  43456. return true;
  43457. };
  43458. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  43459. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  43460. for (var index = 0; index < this.subMaterials.length; index++) {
  43461. var subMaterial = null;
  43462. if (cloneChildren) {
  43463. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  43464. }
  43465. else {
  43466. subMaterial = this.subMaterials[index];
  43467. }
  43468. newMultiMaterial.subMaterials.push(subMaterial);
  43469. }
  43470. return newMultiMaterial;
  43471. };
  43472. MultiMaterial.prototype.serialize = function () {
  43473. var serializationObject = {};
  43474. serializationObject.name = this.name;
  43475. serializationObject.id = this.id;
  43476. serializationObject.tags = BABYLON.Tags.GetTags(this);
  43477. serializationObject.materials = [];
  43478. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  43479. var subMat = this.subMaterials[matIndex];
  43480. if (subMat) {
  43481. serializationObject.materials.push(subMat.id);
  43482. }
  43483. else {
  43484. serializationObject.materials.push(null);
  43485. }
  43486. }
  43487. return serializationObject;
  43488. };
  43489. return MultiMaterial;
  43490. }(BABYLON.Material));
  43491. BABYLON.MultiMaterial = MultiMaterial;
  43492. })(BABYLON || (BABYLON = {}));
  43493. //# sourceMappingURL=babylon.multiMaterial.js.map
  43494. var BABYLON;
  43495. (function (BABYLON) {
  43496. var FreeCameraTouchInput = (function () {
  43497. function FreeCameraTouchInput() {
  43498. this._offsetX = null;
  43499. this._offsetY = null;
  43500. this._pointerCount = 0;
  43501. this._pointerPressed = [];
  43502. this.touchAngularSensibility = 200000.0;
  43503. this.touchMoveSensibility = 250.0;
  43504. }
  43505. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  43506. var _this = this;
  43507. var previousPosition;
  43508. if (this._pointerInput === undefined) {
  43509. this._onLostFocus = function (evt) {
  43510. _this._offsetX = null;
  43511. _this._offsetY = null;
  43512. };
  43513. this._pointerInput = function (p, s) {
  43514. var evt = p.event;
  43515. if (evt.pointerType === "mouse") {
  43516. return;
  43517. }
  43518. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  43519. if (!noPreventDefault) {
  43520. evt.preventDefault();
  43521. }
  43522. _this._pointerPressed.push(evt.pointerId);
  43523. if (_this._pointerPressed.length !== 1) {
  43524. return;
  43525. }
  43526. previousPosition = {
  43527. x: evt.clientX,
  43528. y: evt.clientY
  43529. };
  43530. }
  43531. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  43532. if (!noPreventDefault) {
  43533. evt.preventDefault();
  43534. }
  43535. var index = _this._pointerPressed.indexOf(evt.pointerId);
  43536. if (index === -1) {
  43537. return;
  43538. }
  43539. _this._pointerPressed.splice(index, 1);
  43540. if (index != 0) {
  43541. return;
  43542. }
  43543. previousPosition = null;
  43544. _this._offsetX = null;
  43545. _this._offsetY = null;
  43546. }
  43547. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43548. if (!noPreventDefault) {
  43549. evt.preventDefault();
  43550. }
  43551. if (!previousPosition) {
  43552. return;
  43553. }
  43554. var index = _this._pointerPressed.indexOf(evt.pointerId);
  43555. if (index != 0) {
  43556. return;
  43557. }
  43558. _this._offsetX = evt.clientX - previousPosition.x;
  43559. _this._offsetY = -(evt.clientY - previousPosition.y);
  43560. }
  43561. };
  43562. }
  43563. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43564. element.addEventListener("blur", this._onLostFocus);
  43565. };
  43566. FreeCameraTouchInput.prototype.detachControl = function (element) {
  43567. if (this._pointerInput && element) {
  43568. this.camera.getScene().onPointerObservable.remove(this._observer);
  43569. this._observer = null;
  43570. element.removeEventListener("blur", this._onLostFocus);
  43571. this._onLostFocus = null;
  43572. this._pointerPressed = [];
  43573. this._offsetX = null;
  43574. this._offsetY = null;
  43575. this._pointerCount = 0;
  43576. }
  43577. };
  43578. FreeCameraTouchInput.prototype.checkInputs = function () {
  43579. if (this._offsetX) {
  43580. var camera = this.camera;
  43581. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  43582. if (this._pointerPressed.length > 1) {
  43583. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  43584. }
  43585. else {
  43586. var speed = camera._computeLocalCameraSpeed();
  43587. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  43588. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  43589. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  43590. }
  43591. }
  43592. };
  43593. FreeCameraTouchInput.prototype.getTypeName = function () {
  43594. return "FreeCameraTouchInput";
  43595. };
  43596. FreeCameraTouchInput.prototype.getSimpleName = function () {
  43597. return "touch";
  43598. };
  43599. return FreeCameraTouchInput;
  43600. }());
  43601. __decorate([
  43602. BABYLON.serialize()
  43603. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  43604. __decorate([
  43605. BABYLON.serialize()
  43606. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  43607. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  43608. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  43609. })(BABYLON || (BABYLON = {}));
  43610. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  43611. /// <reference path="babylon.freeCamera.ts" />
  43612. var BABYLON;
  43613. (function (BABYLON) {
  43614. // We're mainly based on the logic defined into the FreeCamera code
  43615. var TouchCamera = (function (_super) {
  43616. __extends(TouchCamera, _super);
  43617. //-- end properties for backward compatibility for inputs
  43618. function TouchCamera(name, position, scene) {
  43619. var _this = _super.call(this, name, position, scene) || this;
  43620. _this.inputs.addTouch();
  43621. _this._setupInputs();
  43622. return _this;
  43623. }
  43624. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  43625. //-- Begin properties for backward compatibility for inputs
  43626. get: function () {
  43627. var touch = this.inputs.attached["touch"];
  43628. if (touch)
  43629. return touch.touchAngularSensibility;
  43630. },
  43631. set: function (value) {
  43632. var touch = this.inputs.attached["touch"];
  43633. if (touch)
  43634. touch.touchAngularSensibility = value;
  43635. },
  43636. enumerable: true,
  43637. configurable: true
  43638. });
  43639. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  43640. get: function () {
  43641. var touch = this.inputs.attached["touch"];
  43642. if (touch)
  43643. return touch.touchMoveSensibility;
  43644. },
  43645. set: function (value) {
  43646. var touch = this.inputs.attached["touch"];
  43647. if (touch)
  43648. touch.touchMoveSensibility = value;
  43649. },
  43650. enumerable: true,
  43651. configurable: true
  43652. });
  43653. TouchCamera.prototype.getClassName = function () {
  43654. return "TouchCamera";
  43655. };
  43656. TouchCamera.prototype._setupInputs = function () {
  43657. var mouse = this.inputs.attached["mouse"];
  43658. if (mouse) {
  43659. mouse.touchEnabled = false;
  43660. }
  43661. };
  43662. return TouchCamera;
  43663. }(BABYLON.FreeCamera));
  43664. BABYLON.TouchCamera = TouchCamera;
  43665. })(BABYLON || (BABYLON = {}));
  43666. //# sourceMappingURL=babylon.touchCamera.js.map
  43667. var BABYLON;
  43668. (function (BABYLON) {
  43669. var ProceduralTexture = (function (_super) {
  43670. __extends(ProceduralTexture, _super);
  43671. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  43672. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43673. if (isCube === void 0) { isCube = false; }
  43674. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  43675. _this.isCube = isCube;
  43676. _this.isEnabled = true;
  43677. _this._currentRefreshId = -1;
  43678. _this._refreshRate = 1;
  43679. _this._vertexBuffers = {};
  43680. _this._uniforms = new Array();
  43681. _this._samplers = new Array();
  43682. _this._textures = new Array();
  43683. _this._floats = new Array();
  43684. _this._floatsArrays = {};
  43685. _this._colors3 = new Array();
  43686. _this._colors4 = new Array();
  43687. _this._vectors2 = new Array();
  43688. _this._vectors3 = new Array();
  43689. _this._matrices = new Array();
  43690. _this._fallbackTextureUsed = false;
  43691. scene._proceduralTextures.push(_this);
  43692. _this.name = name;
  43693. _this.isRenderTarget = true;
  43694. _this._size = size;
  43695. _this._generateMipMaps = generateMipMaps;
  43696. _this.setFragment(fragment);
  43697. _this._fallbackTexture = fallbackTexture;
  43698. var engine = scene.getEngine();
  43699. if (isCube) {
  43700. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  43701. _this.setFloat("face", 0);
  43702. }
  43703. else {
  43704. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  43705. }
  43706. // VBO
  43707. var vertices = [];
  43708. vertices.push(1, 1);
  43709. vertices.push(-1, 1);
  43710. vertices.push(-1, -1);
  43711. vertices.push(1, -1);
  43712. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  43713. // Indices
  43714. var indices = [];
  43715. indices.push(0);
  43716. indices.push(1);
  43717. indices.push(2);
  43718. indices.push(0);
  43719. indices.push(2);
  43720. indices.push(3);
  43721. _this._indexBuffer = engine.createIndexBuffer(indices);
  43722. return _this;
  43723. }
  43724. ProceduralTexture.prototype.reset = function () {
  43725. if (this._effect === undefined) {
  43726. return;
  43727. }
  43728. var engine = this.getScene().getEngine();
  43729. engine._releaseEffect(this._effect);
  43730. };
  43731. ProceduralTexture.prototype.isReady = function () {
  43732. var _this = this;
  43733. var engine = this.getScene().getEngine();
  43734. var shaders;
  43735. if (!this._fragment) {
  43736. return false;
  43737. }
  43738. if (this._fallbackTextureUsed) {
  43739. return true;
  43740. }
  43741. if (this._fragment.fragmentElement !== undefined) {
  43742. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  43743. }
  43744. else {
  43745. shaders = { vertex: "procedural", fragment: this._fragment };
  43746. }
  43747. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  43748. _this.releaseInternalTexture();
  43749. if (_this._fallbackTexture) {
  43750. _this._texture = _this._fallbackTexture._texture;
  43751. _this._texture.references++;
  43752. }
  43753. _this._fallbackTextureUsed = true;
  43754. });
  43755. return this._effect.isReady();
  43756. };
  43757. ProceduralTexture.prototype.resetRefreshCounter = function () {
  43758. this._currentRefreshId = -1;
  43759. };
  43760. ProceduralTexture.prototype.setFragment = function (fragment) {
  43761. this._fragment = fragment;
  43762. };
  43763. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  43764. get: function () {
  43765. return this._refreshRate;
  43766. },
  43767. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  43768. set: function (value) {
  43769. this._refreshRate = value;
  43770. this.resetRefreshCounter();
  43771. },
  43772. enumerable: true,
  43773. configurable: true
  43774. });
  43775. ProceduralTexture.prototype._shouldRender = function () {
  43776. if (!this.isEnabled || !this.isReady() || !this._texture) {
  43777. return false;
  43778. }
  43779. if (this._fallbackTextureUsed) {
  43780. return false;
  43781. }
  43782. if (this._currentRefreshId === -1) {
  43783. this._currentRefreshId = 1;
  43784. return true;
  43785. }
  43786. if (this.refreshRate === this._currentRefreshId) {
  43787. this._currentRefreshId = 1;
  43788. return true;
  43789. }
  43790. this._currentRefreshId++;
  43791. return false;
  43792. };
  43793. ProceduralTexture.prototype.getRenderSize = function () {
  43794. return this._size;
  43795. };
  43796. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  43797. if (this._fallbackTextureUsed) {
  43798. return;
  43799. }
  43800. this.releaseInternalTexture();
  43801. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  43802. };
  43803. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  43804. if (this._uniforms.indexOf(uniformName) === -1) {
  43805. this._uniforms.push(uniformName);
  43806. }
  43807. };
  43808. ProceduralTexture.prototype.setTexture = function (name, texture) {
  43809. if (this._samplers.indexOf(name) === -1) {
  43810. this._samplers.push(name);
  43811. }
  43812. this._textures[name] = texture;
  43813. return this;
  43814. };
  43815. ProceduralTexture.prototype.setFloat = function (name, value) {
  43816. this._checkUniform(name);
  43817. this._floats[name] = value;
  43818. return this;
  43819. };
  43820. ProceduralTexture.prototype.setFloats = function (name, value) {
  43821. this._checkUniform(name);
  43822. this._floatsArrays[name] = value;
  43823. return this;
  43824. };
  43825. ProceduralTexture.prototype.setColor3 = function (name, value) {
  43826. this._checkUniform(name);
  43827. this._colors3[name] = value;
  43828. return this;
  43829. };
  43830. ProceduralTexture.prototype.setColor4 = function (name, value) {
  43831. this._checkUniform(name);
  43832. this._colors4[name] = value;
  43833. return this;
  43834. };
  43835. ProceduralTexture.prototype.setVector2 = function (name, value) {
  43836. this._checkUniform(name);
  43837. this._vectors2[name] = value;
  43838. return this;
  43839. };
  43840. ProceduralTexture.prototype.setVector3 = function (name, value) {
  43841. this._checkUniform(name);
  43842. this._vectors3[name] = value;
  43843. return this;
  43844. };
  43845. ProceduralTexture.prototype.setMatrix = function (name, value) {
  43846. this._checkUniform(name);
  43847. this._matrices[name] = value;
  43848. return this;
  43849. };
  43850. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  43851. var scene = this.getScene();
  43852. var engine = scene.getEngine();
  43853. // Render
  43854. engine.enableEffect(this._effect);
  43855. engine.setState(false);
  43856. // Texture
  43857. for (var name in this._textures) {
  43858. this._effect.setTexture(name, this._textures[name]);
  43859. }
  43860. // Float
  43861. for (name in this._floats) {
  43862. this._effect.setFloat(name, this._floats[name]);
  43863. }
  43864. // Floats
  43865. for (name in this._floatsArrays) {
  43866. this._effect.setArray(name, this._floatsArrays[name]);
  43867. }
  43868. // Color3
  43869. for (name in this._colors3) {
  43870. this._effect.setColor3(name, this._colors3[name]);
  43871. }
  43872. // Color4
  43873. for (name in this._colors4) {
  43874. var color = this._colors4[name];
  43875. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  43876. }
  43877. // Vector2
  43878. for (name in this._vectors2) {
  43879. this._effect.setVector2(name, this._vectors2[name]);
  43880. }
  43881. // Vector3
  43882. for (name in this._vectors3) {
  43883. this._effect.setVector3(name, this._vectors3[name]);
  43884. }
  43885. // Matrix
  43886. for (name in this._matrices) {
  43887. this._effect.setMatrix(name, this._matrices[name]);
  43888. }
  43889. if (this.isCube) {
  43890. for (var face = 0; face < 6; face++) {
  43891. engine.bindFramebuffer(this._texture, face);
  43892. // VBOs
  43893. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  43894. this._effect.setFloat("face", face);
  43895. // Clear
  43896. engine.clear(scene.clearColor, true, true, true);
  43897. // Draw order
  43898. engine.draw(true, 0, 6);
  43899. // Mipmaps
  43900. if (face === 5) {
  43901. engine.generateMipMapsForCubemap(this._texture);
  43902. }
  43903. }
  43904. }
  43905. else {
  43906. engine.bindFramebuffer(this._texture);
  43907. // VBOs
  43908. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  43909. // Clear
  43910. engine.clear(scene.clearColor, true, true, true);
  43911. // Draw order
  43912. engine.draw(true, 0, 6);
  43913. }
  43914. // Unbind
  43915. engine.unBindFramebuffer(this._texture, this.isCube);
  43916. if (this.onGenerated) {
  43917. this.onGenerated();
  43918. }
  43919. };
  43920. ProceduralTexture.prototype.clone = function () {
  43921. var textureSize = this.getSize();
  43922. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  43923. // Base texture
  43924. newTexture.hasAlpha = this.hasAlpha;
  43925. newTexture.level = this.level;
  43926. // RenderTarget Texture
  43927. newTexture.coordinatesMode = this.coordinatesMode;
  43928. return newTexture;
  43929. };
  43930. ProceduralTexture.prototype.dispose = function () {
  43931. var index = this.getScene()._proceduralTextures.indexOf(this);
  43932. if (index >= 0) {
  43933. this.getScene()._proceduralTextures.splice(index, 1);
  43934. }
  43935. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  43936. if (vertexBuffer) {
  43937. vertexBuffer.dispose();
  43938. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  43939. }
  43940. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  43941. this._indexBuffer = null;
  43942. }
  43943. _super.prototype.dispose.call(this);
  43944. };
  43945. return ProceduralTexture;
  43946. }(BABYLON.Texture));
  43947. BABYLON.ProceduralTexture = ProceduralTexture;
  43948. })(BABYLON || (BABYLON = {}));
  43949. //# sourceMappingURL=babylon.proceduralTexture.js.map
  43950. /// <reference path="babylon.proceduralTexture.ts" />
  43951. var BABYLON;
  43952. (function (BABYLON) {
  43953. var CustomProceduralTexture = (function (_super) {
  43954. __extends(CustomProceduralTexture, _super);
  43955. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  43956. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  43957. _this._animate = true;
  43958. _this._time = 0;
  43959. _this._texturePath = texturePath;
  43960. //Try to load json
  43961. _this.loadJson(texturePath);
  43962. _this.refreshRate = 1;
  43963. return _this;
  43964. }
  43965. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  43966. var _this = this;
  43967. var that = this;
  43968. function noConfigFile() {
  43969. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  43970. try {
  43971. that.setFragment(that._texturePath);
  43972. }
  43973. catch (ex) {
  43974. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  43975. }
  43976. }
  43977. var configFileUrl = jsonUrl + "/config.json";
  43978. var xhr = new XMLHttpRequest();
  43979. xhr.open("GET", configFileUrl, true);
  43980. xhr.addEventListener("load", function () {
  43981. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  43982. try {
  43983. _this._config = JSON.parse(xhr.response);
  43984. _this.updateShaderUniforms();
  43985. _this.updateTextures();
  43986. _this.setFragment(_this._texturePath + "/custom");
  43987. _this._animate = _this._config.animate;
  43988. _this.refreshRate = _this._config.refreshrate;
  43989. }
  43990. catch (ex) {
  43991. noConfigFile();
  43992. }
  43993. }
  43994. else {
  43995. noConfigFile();
  43996. }
  43997. }, false);
  43998. xhr.addEventListener("error", function () {
  43999. noConfigFile();
  44000. }, false);
  44001. try {
  44002. xhr.send();
  44003. }
  44004. catch (ex) {
  44005. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  44006. }
  44007. };
  44008. CustomProceduralTexture.prototype.isReady = function () {
  44009. if (!_super.prototype.isReady.call(this)) {
  44010. return false;
  44011. }
  44012. for (var name in this._textures) {
  44013. var texture = this._textures[name];
  44014. if (!texture.isReady()) {
  44015. return false;
  44016. }
  44017. }
  44018. return true;
  44019. };
  44020. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  44021. if (this._animate) {
  44022. this._time += this.getScene().getAnimationRatio() * 0.03;
  44023. this.updateShaderUniforms();
  44024. }
  44025. _super.prototype.render.call(this, useCameraPostProcess);
  44026. };
  44027. CustomProceduralTexture.prototype.updateTextures = function () {
  44028. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  44029. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  44030. }
  44031. };
  44032. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  44033. if (this._config) {
  44034. for (var j = 0; j < this._config.uniforms.length; j++) {
  44035. var uniform = this._config.uniforms[j];
  44036. switch (uniform.type) {
  44037. case "float":
  44038. this.setFloat(uniform.name, uniform.value);
  44039. break;
  44040. case "color3":
  44041. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  44042. break;
  44043. case "color4":
  44044. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  44045. break;
  44046. case "vector2":
  44047. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  44048. break;
  44049. case "vector3":
  44050. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  44051. break;
  44052. }
  44053. }
  44054. }
  44055. this.setFloat("time", this._time);
  44056. };
  44057. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  44058. get: function () {
  44059. return this._animate;
  44060. },
  44061. set: function (value) {
  44062. this._animate = value;
  44063. },
  44064. enumerable: true,
  44065. configurable: true
  44066. });
  44067. return CustomProceduralTexture;
  44068. }(BABYLON.ProceduralTexture));
  44069. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  44070. })(BABYLON || (BABYLON = {}));
  44071. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  44072. var BABYLON;
  44073. (function (BABYLON) {
  44074. var FreeCameraGamepadInput = (function () {
  44075. function FreeCameraGamepadInput() {
  44076. this.gamepadAngularSensibility = 200;
  44077. this.gamepadMoveSensibility = 40;
  44078. // private members
  44079. this._cameraTransform = BABYLON.Matrix.Identity();
  44080. this._deltaTransform = BABYLON.Vector3.Zero();
  44081. this._vector3 = BABYLON.Vector3.Zero();
  44082. this._vector2 = BABYLON.Vector2.Zero();
  44083. }
  44084. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  44085. var _this = this;
  44086. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  44087. };
  44088. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  44089. if (this._gamepads) {
  44090. this._gamepads.dispose();
  44091. }
  44092. this.gamepad = null;
  44093. };
  44094. FreeCameraGamepadInput.prototype.checkInputs = function () {
  44095. if (this.gamepad && this.gamepad.leftStick) {
  44096. var camera = this.camera;
  44097. var LSValues = this.gamepad.leftStick;
  44098. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  44099. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  44100. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  44101. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  44102. var RSValues = this.gamepad.rightStick;
  44103. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  44104. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  44105. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  44106. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  44107. if (!camera.rotationQuaternion) {
  44108. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  44109. }
  44110. else {
  44111. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  44112. }
  44113. var speed = camera._computeLocalCameraSpeed() * 50.0;
  44114. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  44115. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  44116. camera.cameraDirection.addInPlace(this._deltaTransform);
  44117. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  44118. camera.cameraRotation.addInPlace(this._vector2);
  44119. }
  44120. };
  44121. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  44122. // Only the first gamepad found can control the camera
  44123. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  44124. // prioritize XBOX gamepads.
  44125. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  44126. this.gamepad = gamepad;
  44127. }
  44128. }
  44129. };
  44130. FreeCameraGamepadInput.prototype.getTypeName = function () {
  44131. return "FreeCameraGamepadInput";
  44132. };
  44133. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  44134. return "gamepad";
  44135. };
  44136. return FreeCameraGamepadInput;
  44137. }());
  44138. __decorate([
  44139. BABYLON.serialize()
  44140. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  44141. __decorate([
  44142. BABYLON.serialize()
  44143. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  44144. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  44145. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  44146. })(BABYLON || (BABYLON = {}));
  44147. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  44148. var BABYLON;
  44149. (function (BABYLON) {
  44150. var ArcRotateCameraGamepadInput = (function () {
  44151. function ArcRotateCameraGamepadInput() {
  44152. this.gamepadRotationSensibility = 80;
  44153. this.gamepadMoveSensibility = 40;
  44154. }
  44155. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  44156. var _this = this;
  44157. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  44158. };
  44159. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  44160. if (this._gamepads) {
  44161. this._gamepads.dispose();
  44162. }
  44163. this.gamepad = null;
  44164. };
  44165. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  44166. if (this.gamepad) {
  44167. var camera = this.camera;
  44168. var RSValues = this.gamepad.rightStick;
  44169. if (RSValues.x != 0) {
  44170. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  44171. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  44172. camera.inertialAlphaOffset += normalizedRX;
  44173. }
  44174. }
  44175. if (RSValues.y != 0) {
  44176. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  44177. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  44178. camera.inertialBetaOffset += normalizedRY;
  44179. }
  44180. }
  44181. var LSValues = this.gamepad.leftStick;
  44182. if (LSValues.y != 0) {
  44183. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  44184. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  44185. this.camera.inertialRadiusOffset -= normalizedLY;
  44186. }
  44187. }
  44188. }
  44189. };
  44190. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  44191. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  44192. // prioritize XBOX gamepads.
  44193. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  44194. this.gamepad = gamepad;
  44195. }
  44196. }
  44197. };
  44198. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  44199. return "ArcRotateCameraGamepadInput";
  44200. };
  44201. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  44202. return "gamepad";
  44203. };
  44204. return ArcRotateCameraGamepadInput;
  44205. }());
  44206. __decorate([
  44207. BABYLON.serialize()
  44208. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  44209. __decorate([
  44210. BABYLON.serialize()
  44211. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  44212. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  44213. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  44214. })(BABYLON || (BABYLON = {}));
  44215. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  44216. var BABYLON;
  44217. (function (BABYLON) {
  44218. var Gamepads = (function () {
  44219. function Gamepads(ongamedpadconnected) {
  44220. var _this = this;
  44221. this.babylonGamepads = [];
  44222. this.oneGamepadConnected = false;
  44223. this.isMonitoring = false;
  44224. this.gamepadEventSupported = 'GamepadEvent' in window;
  44225. this.gamepadSupport = (navigator.getGamepads ||
  44226. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  44227. this._callbackGamepadConnected = ongamedpadconnected;
  44228. if (this.gamepadSupport) {
  44229. //first add already-connected gamepads
  44230. this._updateGamepadObjects();
  44231. if (this.babylonGamepads.length) {
  44232. this._startMonitoringGamepads();
  44233. }
  44234. // Checking if the gamepad connected event is supported (like in Firefox)
  44235. if (this.gamepadEventSupported) {
  44236. this._onGamepadConnectedEvent = function (evt) {
  44237. _this._onGamepadConnected(evt.gamepad);
  44238. };
  44239. this._onGamepadDisonnectedEvent = function (evt) {
  44240. _this._onGamepadDisconnected(evt);
  44241. };
  44242. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  44243. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  44244. }
  44245. else {
  44246. this._startMonitoringGamepads();
  44247. }
  44248. }
  44249. }
  44250. Gamepads.prototype.dispose = function () {
  44251. if (Gamepads.gamepadDOMInfo) {
  44252. document.body.removeChild(Gamepads.gamepadDOMInfo);
  44253. }
  44254. if (this._onGamepadConnectedEvent) {
  44255. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  44256. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  44257. this._onGamepadConnectedEvent = null;
  44258. this._onGamepadDisonnectedEvent = null;
  44259. }
  44260. };
  44261. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  44262. var newGamepad = this._addNewGamepad(gamepad);
  44263. if (this._callbackGamepadConnected)
  44264. this._callbackGamepadConnected(newGamepad);
  44265. this._startMonitoringGamepads();
  44266. };
  44267. Gamepads.prototype._addNewGamepad = function (gamepad) {
  44268. if (!this.oneGamepadConnected) {
  44269. this.oneGamepadConnected = true;
  44270. if (Gamepads.gamepadDOMInfo) {
  44271. document.body.removeChild(Gamepads.gamepadDOMInfo);
  44272. Gamepads.gamepadDOMInfo = null;
  44273. }
  44274. }
  44275. var newGamepad;
  44276. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  44277. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  44278. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  44279. }
  44280. else if (gamepad.pose) {
  44281. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  44282. }
  44283. else {
  44284. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  44285. }
  44286. this.babylonGamepads.push(newGamepad);
  44287. return newGamepad;
  44288. };
  44289. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  44290. // Remove the gamepad from the list of gamepads to monitor.
  44291. for (var i in this.babylonGamepads) {
  44292. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  44293. this.babylonGamepads.splice(+i, 1);
  44294. break;
  44295. }
  44296. }
  44297. // If no gamepads are left, stop the polling loop.
  44298. if (this.babylonGamepads.length == 0) {
  44299. this._stopMonitoringGamepads();
  44300. }
  44301. };
  44302. Gamepads.prototype._startMonitoringGamepads = function () {
  44303. if (!this.isMonitoring) {
  44304. this.isMonitoring = true;
  44305. this._checkGamepadsStatus();
  44306. }
  44307. };
  44308. Gamepads.prototype._stopMonitoringGamepads = function () {
  44309. this.isMonitoring = false;
  44310. };
  44311. Gamepads.prototype._checkGamepadsStatus = function () {
  44312. var _this = this;
  44313. // updating gamepad objects
  44314. this._updateGamepadObjects();
  44315. for (var i in this.babylonGamepads) {
  44316. this.babylonGamepads[i].update();
  44317. }
  44318. if (this.isMonitoring) {
  44319. if (window.requestAnimationFrame) {
  44320. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44321. }
  44322. else if (window.mozRequestAnimationFrame) {
  44323. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44324. }
  44325. else if (window.webkitRequestAnimationFrame) {
  44326. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  44327. }
  44328. }
  44329. };
  44330. // This function is called only on Chrome, which does not yet support
  44331. // connection/disconnection events, but requires you to monitor
  44332. // an array for changes.
  44333. Gamepads.prototype._updateGamepadObjects = function () {
  44334. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  44335. for (var i = 0; i < gamepads.length; i++) {
  44336. if (gamepads[i]) {
  44337. if (!(gamepads[i].index in this.babylonGamepads)) {
  44338. var newGamepad = this._addNewGamepad(gamepads[i]);
  44339. if (this._callbackGamepadConnected) {
  44340. this._callbackGamepadConnected(newGamepad);
  44341. }
  44342. }
  44343. else {
  44344. this.babylonGamepads[i].browserGamepad = gamepads[i];
  44345. }
  44346. }
  44347. }
  44348. };
  44349. return Gamepads;
  44350. }());
  44351. BABYLON.Gamepads = Gamepads;
  44352. var StickValues = (function () {
  44353. function StickValues(x, y) {
  44354. this.x = x;
  44355. this.y = y;
  44356. }
  44357. return StickValues;
  44358. }());
  44359. BABYLON.StickValues = StickValues;
  44360. var Gamepad = (function () {
  44361. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  44362. if (leftStickX === void 0) { leftStickX = 0; }
  44363. if (leftStickY === void 0) { leftStickY = 1; }
  44364. if (rightStickX === void 0) { rightStickX = 2; }
  44365. if (rightStickY === void 0) { rightStickY = 3; }
  44366. this.id = id;
  44367. this.index = index;
  44368. this.browserGamepad = browserGamepad;
  44369. this.type = Gamepad.GAMEPAD;
  44370. this._leftStickAxisX = leftStickX;
  44371. this._leftStickAxisY = leftStickY;
  44372. this._rightStickAxisX = rightStickX;
  44373. this._rightStickAxisY = rightStickY;
  44374. if (this.browserGamepad.axes.length >= 2) {
  44375. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  44376. }
  44377. if (this.browserGamepad.axes.length >= 4) {
  44378. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  44379. }
  44380. }
  44381. Gamepad.prototype.onleftstickchanged = function (callback) {
  44382. this._onleftstickchanged = callback;
  44383. };
  44384. Gamepad.prototype.onrightstickchanged = function (callback) {
  44385. this._onrightstickchanged = callback;
  44386. };
  44387. Object.defineProperty(Gamepad.prototype, "leftStick", {
  44388. get: function () {
  44389. return this._leftStick;
  44390. },
  44391. set: function (newValues) {
  44392. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  44393. this._onleftstickchanged(newValues);
  44394. }
  44395. this._leftStick = newValues;
  44396. },
  44397. enumerable: true,
  44398. configurable: true
  44399. });
  44400. Object.defineProperty(Gamepad.prototype, "rightStick", {
  44401. get: function () {
  44402. return this._rightStick;
  44403. },
  44404. set: function (newValues) {
  44405. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  44406. this._onrightstickchanged(newValues);
  44407. }
  44408. this._rightStick = newValues;
  44409. },
  44410. enumerable: true,
  44411. configurable: true
  44412. });
  44413. Gamepad.prototype.update = function () {
  44414. if (this._leftStick) {
  44415. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  44416. }
  44417. if (this._rightStick) {
  44418. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  44419. }
  44420. };
  44421. return Gamepad;
  44422. }());
  44423. Gamepad.GAMEPAD = 0;
  44424. Gamepad.GENERIC = 1;
  44425. Gamepad.XBOX = 2;
  44426. Gamepad.POSE_ENABLED = 3;
  44427. BABYLON.Gamepad = Gamepad;
  44428. var GenericPad = (function (_super) {
  44429. __extends(GenericPad, _super);
  44430. function GenericPad(id, index, gamepad) {
  44431. var _this = _super.call(this, id, index, gamepad) || this;
  44432. _this.id = id;
  44433. _this.index = index;
  44434. _this.gamepad = gamepad;
  44435. _this.type = Gamepad.GENERIC;
  44436. _this._buttons = new Array(gamepad.buttons.length);
  44437. return _this;
  44438. }
  44439. GenericPad.prototype.onbuttondown = function (callback) {
  44440. this._onbuttondown = callback;
  44441. };
  44442. GenericPad.prototype.onbuttonup = function (callback) {
  44443. this._onbuttonup = callback;
  44444. };
  44445. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  44446. if (newValue !== currentValue) {
  44447. if (this._onbuttondown && newValue === 1) {
  44448. this._onbuttondown(buttonIndex);
  44449. }
  44450. if (this._onbuttonup && newValue === 0) {
  44451. this._onbuttonup(buttonIndex);
  44452. }
  44453. }
  44454. return newValue;
  44455. };
  44456. GenericPad.prototype.update = function () {
  44457. _super.prototype.update.call(this);
  44458. for (var index = 0; index < this._buttons.length; index++) {
  44459. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  44460. }
  44461. };
  44462. return GenericPad;
  44463. }(Gamepad));
  44464. BABYLON.GenericPad = GenericPad;
  44465. var Xbox360Button;
  44466. (function (Xbox360Button) {
  44467. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  44468. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  44469. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  44470. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  44471. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  44472. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  44473. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  44474. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  44475. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  44476. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  44477. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  44478. var Xbox360Dpad;
  44479. (function (Xbox360Dpad) {
  44480. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  44481. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  44482. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  44483. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  44484. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  44485. var Xbox360Pad = (function (_super) {
  44486. __extends(Xbox360Pad, _super);
  44487. function Xbox360Pad(id, index, gamepad, xboxOne) {
  44488. if (xboxOne === void 0) { xboxOne = false; }
  44489. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  44490. _this._leftTrigger = 0;
  44491. _this._rightTrigger = 0;
  44492. _this._buttonA = 0;
  44493. _this._buttonB = 0;
  44494. _this._buttonX = 0;
  44495. _this._buttonY = 0;
  44496. _this._buttonBack = 0;
  44497. _this._buttonStart = 0;
  44498. _this._buttonLB = 0;
  44499. _this._buttonRB = 0;
  44500. _this._buttonLeftStick = 0;
  44501. _this._buttonRightStick = 0;
  44502. _this._dPadUp = 0;
  44503. _this._dPadDown = 0;
  44504. _this._dPadLeft = 0;
  44505. _this._dPadRight = 0;
  44506. _this._isXboxOnePad = false;
  44507. _this.type = Gamepad.XBOX;
  44508. _this._isXboxOnePad = xboxOne;
  44509. return _this;
  44510. }
  44511. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  44512. this._onlefttriggerchanged = callback;
  44513. };
  44514. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  44515. this._onrighttriggerchanged = callback;
  44516. };
  44517. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  44518. get: function () {
  44519. return this._leftTrigger;
  44520. },
  44521. set: function (newValue) {
  44522. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  44523. this._onlefttriggerchanged(newValue);
  44524. }
  44525. this._leftTrigger = newValue;
  44526. },
  44527. enumerable: true,
  44528. configurable: true
  44529. });
  44530. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  44531. get: function () {
  44532. return this._rightTrigger;
  44533. },
  44534. set: function (newValue) {
  44535. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  44536. this._onrighttriggerchanged(newValue);
  44537. }
  44538. this._rightTrigger = newValue;
  44539. },
  44540. enumerable: true,
  44541. configurable: true
  44542. });
  44543. Xbox360Pad.prototype.onbuttondown = function (callback) {
  44544. this._onbuttondown = callback;
  44545. };
  44546. Xbox360Pad.prototype.onbuttonup = function (callback) {
  44547. this._onbuttonup = callback;
  44548. };
  44549. Xbox360Pad.prototype.ondpaddown = function (callback) {
  44550. this._ondpaddown = callback;
  44551. };
  44552. Xbox360Pad.prototype.ondpadup = function (callback) {
  44553. this._ondpadup = callback;
  44554. };
  44555. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  44556. if (newValue !== currentValue) {
  44557. if (this._onbuttondown && newValue === 1) {
  44558. this._onbuttondown(buttonType);
  44559. }
  44560. if (this._onbuttonup && newValue === 0) {
  44561. this._onbuttonup(buttonType);
  44562. }
  44563. }
  44564. return newValue;
  44565. };
  44566. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  44567. if (newValue !== currentValue) {
  44568. if (this._ondpaddown && newValue === 1) {
  44569. this._ondpaddown(buttonType);
  44570. }
  44571. if (this._ondpadup && newValue === 0) {
  44572. this._ondpadup(buttonType);
  44573. }
  44574. }
  44575. return newValue;
  44576. };
  44577. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  44578. get: function () {
  44579. return this._buttonA;
  44580. },
  44581. set: function (value) {
  44582. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  44583. },
  44584. enumerable: true,
  44585. configurable: true
  44586. });
  44587. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  44588. get: function () {
  44589. return this._buttonB;
  44590. },
  44591. set: function (value) {
  44592. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  44593. },
  44594. enumerable: true,
  44595. configurable: true
  44596. });
  44597. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  44598. get: function () {
  44599. return this._buttonX;
  44600. },
  44601. set: function (value) {
  44602. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  44603. },
  44604. enumerable: true,
  44605. configurable: true
  44606. });
  44607. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  44608. get: function () {
  44609. return this._buttonY;
  44610. },
  44611. set: function (value) {
  44612. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  44613. },
  44614. enumerable: true,
  44615. configurable: true
  44616. });
  44617. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  44618. get: function () {
  44619. return this._buttonStart;
  44620. },
  44621. set: function (value) {
  44622. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  44623. },
  44624. enumerable: true,
  44625. configurable: true
  44626. });
  44627. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  44628. get: function () {
  44629. return this._buttonBack;
  44630. },
  44631. set: function (value) {
  44632. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  44633. },
  44634. enumerable: true,
  44635. configurable: true
  44636. });
  44637. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  44638. get: function () {
  44639. return this._buttonLB;
  44640. },
  44641. set: function (value) {
  44642. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  44643. },
  44644. enumerable: true,
  44645. configurable: true
  44646. });
  44647. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  44648. get: function () {
  44649. return this._buttonRB;
  44650. },
  44651. set: function (value) {
  44652. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  44653. },
  44654. enumerable: true,
  44655. configurable: true
  44656. });
  44657. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  44658. get: function () {
  44659. return this._buttonLeftStick;
  44660. },
  44661. set: function (value) {
  44662. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  44663. },
  44664. enumerable: true,
  44665. configurable: true
  44666. });
  44667. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  44668. get: function () {
  44669. return this._buttonRightStick;
  44670. },
  44671. set: function (value) {
  44672. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  44673. },
  44674. enumerable: true,
  44675. configurable: true
  44676. });
  44677. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  44678. get: function () {
  44679. return this._dPadUp;
  44680. },
  44681. set: function (value) {
  44682. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  44683. },
  44684. enumerable: true,
  44685. configurable: true
  44686. });
  44687. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  44688. get: function () {
  44689. return this._dPadDown;
  44690. },
  44691. set: function (value) {
  44692. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  44693. },
  44694. enumerable: true,
  44695. configurable: true
  44696. });
  44697. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  44698. get: function () {
  44699. return this._dPadLeft;
  44700. },
  44701. set: function (value) {
  44702. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  44703. },
  44704. enumerable: true,
  44705. configurable: true
  44706. });
  44707. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  44708. get: function () {
  44709. return this._dPadRight;
  44710. },
  44711. set: function (value) {
  44712. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  44713. },
  44714. enumerable: true,
  44715. configurable: true
  44716. });
  44717. Xbox360Pad.prototype.update = function () {
  44718. _super.prototype.update.call(this);
  44719. if (this._isXboxOnePad) {
  44720. this.buttonA = this.browserGamepad.buttons[0].value;
  44721. this.buttonB = this.browserGamepad.buttons[1].value;
  44722. this.buttonX = this.browserGamepad.buttons[2].value;
  44723. this.buttonY = this.browserGamepad.buttons[3].value;
  44724. this.buttonLB = this.browserGamepad.buttons[4].value;
  44725. this.buttonRB = this.browserGamepad.buttons[5].value;
  44726. this.leftTrigger = this.browserGamepad.axes[2];
  44727. this.rightTrigger = this.browserGamepad.axes[5];
  44728. this.buttonBack = this.browserGamepad.buttons[9].value;
  44729. this.buttonStart = this.browserGamepad.buttons[8].value;
  44730. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  44731. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  44732. this.dPadUp = this.browserGamepad.buttons[11].value;
  44733. this.dPadDown = this.browserGamepad.buttons[12].value;
  44734. this.dPadLeft = this.browserGamepad.buttons[13].value;
  44735. this.dPadRight = this.browserGamepad.buttons[14].value;
  44736. }
  44737. else {
  44738. this.buttonA = this.browserGamepad.buttons[0].value;
  44739. this.buttonB = this.browserGamepad.buttons[1].value;
  44740. this.buttonX = this.browserGamepad.buttons[2].value;
  44741. this.buttonY = this.browserGamepad.buttons[3].value;
  44742. this.buttonLB = this.browserGamepad.buttons[4].value;
  44743. this.buttonRB = this.browserGamepad.buttons[5].value;
  44744. this.leftTrigger = this.browserGamepad.buttons[6].value;
  44745. this.rightTrigger = this.browserGamepad.buttons[7].value;
  44746. this.buttonBack = this.browserGamepad.buttons[8].value;
  44747. this.buttonStart = this.browserGamepad.buttons[9].value;
  44748. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  44749. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  44750. this.dPadUp = this.browserGamepad.buttons[12].value;
  44751. this.dPadDown = this.browserGamepad.buttons[13].value;
  44752. this.dPadLeft = this.browserGamepad.buttons[14].value;
  44753. this.dPadRight = this.browserGamepad.buttons[15].value;
  44754. }
  44755. };
  44756. return Xbox360Pad;
  44757. }(Gamepad));
  44758. BABYLON.Xbox360Pad = Xbox360Pad;
  44759. })(BABYLON || (BABYLON = {}));
  44760. //# sourceMappingURL=babylon.gamepads.js.map
  44761. var BABYLON;
  44762. (function (BABYLON) {
  44763. var PoseEnabledControllerType;
  44764. (function (PoseEnabledControllerType) {
  44765. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  44766. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  44767. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  44768. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  44769. var PoseEnabledControllerHelper = (function () {
  44770. function PoseEnabledControllerHelper() {
  44771. }
  44772. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  44773. // for now, only Oculus and Vive are supported
  44774. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  44775. return new OculusTouchController(vrGamepad);
  44776. }
  44777. else {
  44778. return new ViveController(vrGamepad);
  44779. }
  44780. };
  44781. return PoseEnabledControllerHelper;
  44782. }());
  44783. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  44784. var PoseEnabledController = (function (_super) {
  44785. __extends(PoseEnabledController, _super);
  44786. function PoseEnabledController(vrGamepad) {
  44787. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  44788. _this.vrGamepad = vrGamepad;
  44789. _this.deviceScaleFactor = 1;
  44790. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  44791. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  44792. _this.controllerType = PoseEnabledControllerType.GENERIC;
  44793. _this.position = BABYLON.Vector3.Zero();
  44794. _this.rotationQuaternion = new BABYLON.Quaternion();
  44795. _this.devicePosition = BABYLON.Vector3.Zero();
  44796. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  44797. _this._calculatedPosition = BABYLON.Vector3.Zero();
  44798. _this._calculatedRotation = new BABYLON.Quaternion();
  44799. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  44800. return _this;
  44801. }
  44802. PoseEnabledController.prototype.update = function () {
  44803. _super.prototype.update.call(this);
  44804. var pose = this.vrGamepad.pose;
  44805. this.updateFromDevice(pose);
  44806. if (this._mesh) {
  44807. this._mesh.position.copyFrom(this._calculatedPosition);
  44808. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  44809. }
  44810. };
  44811. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  44812. if (poseData) {
  44813. this.rawPose = poseData;
  44814. if (poseData.position) {
  44815. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  44816. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  44817. this.devicePosition.z *= -1;
  44818. }
  44819. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  44820. this._calculatedPosition.addInPlace(this.position);
  44821. }
  44822. if (poseData.orientation) {
  44823. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  44824. if (this._mesh) {
  44825. if (this._mesh.getScene().useRightHandedSystem) {
  44826. this.deviceRotationQuaternion.z *= -1;
  44827. this.deviceRotationQuaternion.w *= -1;
  44828. }
  44829. else {
  44830. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  44831. }
  44832. }
  44833. // if the camera is set, rotate to the camera's rotation
  44834. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  44835. }
  44836. }
  44837. };
  44838. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  44839. if (this._mesh) {
  44840. this._mesh.parent = undefined;
  44841. }
  44842. this._mesh = mesh;
  44843. if (this._poseControlledCamera) {
  44844. this._mesh.parent = this._poseControlledCamera;
  44845. }
  44846. if (!this._mesh.rotationQuaternion) {
  44847. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  44848. }
  44849. };
  44850. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  44851. this._poseControlledCamera = camera;
  44852. if (this._mesh) {
  44853. this._mesh.parent = this._poseControlledCamera;
  44854. }
  44855. };
  44856. PoseEnabledController.prototype.detachMesh = function () {
  44857. this._mesh = undefined;
  44858. };
  44859. return PoseEnabledController;
  44860. }(BABYLON.Gamepad));
  44861. BABYLON.PoseEnabledController = PoseEnabledController;
  44862. var WebVRController = (function (_super) {
  44863. __extends(WebVRController, _super);
  44864. function WebVRController(vrGamepad) {
  44865. var _this = _super.call(this, vrGamepad) || this;
  44866. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  44867. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  44868. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  44869. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  44870. _this.onPadStateChangedObservable = new BABYLON.Observable();
  44871. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  44872. _this.pad = { x: 0, y: 0 };
  44873. // avoid GC, store state in a tmp object
  44874. _this._changes = {
  44875. pressChanged: false,
  44876. touchChanged: false,
  44877. valueChanged: false,
  44878. changed: false
  44879. };
  44880. _this._buttons = new Array(vrGamepad.buttons.length);
  44881. _this.hand = vrGamepad.hand;
  44882. return _this;
  44883. }
  44884. WebVRController.prototype.onButtonStateChange = function (callback) {
  44885. this._onButtonStateChange = callback;
  44886. };
  44887. WebVRController.prototype.update = function () {
  44888. _super.prototype.update.call(this);
  44889. for (var index = 0; index < this._buttons.length; index++) {
  44890. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  44891. }
  44892. ;
  44893. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  44894. this.pad.x = this.leftStick.x;
  44895. this.pad.y = this.leftStick.y;
  44896. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  44897. }
  44898. };
  44899. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  44900. if (!currentState) {
  44901. this._buttons[buttonIndex] = {
  44902. pressed: newState.pressed,
  44903. touched: newState.touched,
  44904. value: newState.value
  44905. };
  44906. return;
  44907. }
  44908. this._checkChanges(newState, currentState);
  44909. if (this._changes.changed) {
  44910. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  44911. this.handleButtonChange(buttonIndex, newState, this._changes);
  44912. }
  44913. this._buttons[buttonIndex].pressed = newState.pressed;
  44914. this._buttons[buttonIndex].touched = newState.touched;
  44915. // oculus triggers are never 0, thou not touched.
  44916. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  44917. };
  44918. WebVRController.prototype._checkChanges = function (newState, currentState) {
  44919. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  44920. this._changes.touchChanged = newState.touched !== currentState.touched;
  44921. this._changes.valueChanged = newState.value !== currentState.value;
  44922. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  44923. return this._changes;
  44924. };
  44925. return WebVRController;
  44926. }(PoseEnabledController));
  44927. BABYLON.WebVRController = WebVRController;
  44928. var OculusTouchController = (function (_super) {
  44929. __extends(OculusTouchController, _super);
  44930. function OculusTouchController(vrGamepad) {
  44931. var _this = _super.call(this, vrGamepad) || this;
  44932. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  44933. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  44934. _this.controllerType = PoseEnabledControllerType.OCULUS;
  44935. return _this;
  44936. }
  44937. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  44938. var _this = this;
  44939. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  44940. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  44941. /*
  44942. Parent Mesh name: oculus_touch_left
  44943. - body
  44944. - trigger
  44945. - thumbstick
  44946. - grip
  44947. - button_y
  44948. - button_x
  44949. - button_enter
  44950. */
  44951. _this._defaultModel = newMeshes[1];
  44952. if (meshLoaded) {
  44953. meshLoaded(_this._defaultModel);
  44954. }
  44955. _this.attachToMesh(_this._defaultModel);
  44956. });
  44957. };
  44958. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  44959. // helper getters for left and right hand.
  44960. get: function () {
  44961. if (this.hand === 'right') {
  44962. return this.onMainButtonStateChangedObservable;
  44963. }
  44964. else {
  44965. throw new Error('No A button on left hand');
  44966. }
  44967. },
  44968. enumerable: true,
  44969. configurable: true
  44970. });
  44971. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  44972. get: function () {
  44973. if (this.hand === 'right') {
  44974. return this.onSecondaryButtonStateChangedObservable;
  44975. }
  44976. else {
  44977. throw new Error('No B button on left hand');
  44978. }
  44979. },
  44980. enumerable: true,
  44981. configurable: true
  44982. });
  44983. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  44984. get: function () {
  44985. if (this.hand === 'left') {
  44986. return this.onMainButtonStateChangedObservable;
  44987. }
  44988. else {
  44989. throw new Error('No X button on right hand');
  44990. }
  44991. },
  44992. enumerable: true,
  44993. configurable: true
  44994. });
  44995. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  44996. get: function () {
  44997. if (this.hand === 'left') {
  44998. return this.onSecondaryButtonStateChangedObservable;
  44999. }
  45000. else {
  45001. throw new Error('No Y button on right hand');
  45002. }
  45003. },
  45004. enumerable: true,
  45005. configurable: true
  45006. });
  45007. /*
  45008. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  45009. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  45010. 2) secondary trigger (same)
  45011. 3) A (right) X (left), touch, pressed = value
  45012. 4) B / Y
  45013. 5) thumb rest
  45014. */
  45015. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  45016. var notifyObject = state; //{ state: state, changes: changes };
  45017. switch (buttonIdx) {
  45018. case 0:
  45019. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  45020. return;
  45021. case 1:
  45022. if (this._defaultModel) {
  45023. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  45024. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  45025. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  45026. }
  45027. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  45028. return;
  45029. case 2:
  45030. if (this._defaultModel) {
  45031. (this._defaultModel.getChildren()[4]).position.x = notifyObject.value * 0.0035;
  45032. }
  45033. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  45034. return;
  45035. case 3:
  45036. if (this._defaultModel) {
  45037. if (notifyObject.pressed) {
  45038. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  45039. }
  45040. else {
  45041. (this._defaultModel.getChildren()[1]).position.y = 0;
  45042. }
  45043. }
  45044. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  45045. return;
  45046. case 4:
  45047. if (this._defaultModel) {
  45048. if (notifyObject.pressed) {
  45049. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  45050. }
  45051. else {
  45052. (this._defaultModel.getChildren()[2]).position.y = 0;
  45053. }
  45054. }
  45055. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  45056. return;
  45057. case 5:
  45058. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  45059. return;
  45060. }
  45061. };
  45062. return OculusTouchController;
  45063. }(WebVRController));
  45064. BABYLON.OculusTouchController = OculusTouchController;
  45065. var ViveController = (function (_super) {
  45066. __extends(ViveController, _super);
  45067. function ViveController(vrGamepad) {
  45068. var _this = _super.call(this, vrGamepad) || this;
  45069. _this.controllerType = PoseEnabledControllerType.VIVE;
  45070. return _this;
  45071. }
  45072. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  45073. var _this = this;
  45074. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  45075. /*
  45076. Parent Mesh name: ViveWand
  45077. - body
  45078. - r_gripper
  45079. - l_gripper
  45080. - menu_button
  45081. - system_button
  45082. - trackpad
  45083. - trigger
  45084. - LED
  45085. */
  45086. _this._defaultModel = newMeshes[1];
  45087. if (meshLoaded) {
  45088. meshLoaded(_this._defaultModel);
  45089. }
  45090. _this.attachToMesh(_this._defaultModel);
  45091. });
  45092. };
  45093. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  45094. get: function () {
  45095. return this.onMainButtonStateChangedObservable;
  45096. },
  45097. enumerable: true,
  45098. configurable: true
  45099. });
  45100. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  45101. get: function () {
  45102. return this.onMainButtonStateChangedObservable;
  45103. },
  45104. enumerable: true,
  45105. configurable: true
  45106. });
  45107. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  45108. get: function () {
  45109. return this.onSecondaryButtonStateChangedObservable;
  45110. },
  45111. enumerable: true,
  45112. configurable: true
  45113. });
  45114. /**
  45115. * Vive mapping:
  45116. * 0: touchpad
  45117. * 1: trigger
  45118. * 2: left AND right buttons
  45119. * 3: menu button
  45120. */
  45121. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  45122. var notifyObject = state; //{ state: state, changes: changes };
  45123. switch (buttonIdx) {
  45124. case 0:
  45125. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  45126. return;
  45127. case 1:
  45128. if (this._defaultModel) {
  45129. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  45130. }
  45131. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  45132. return;
  45133. case 2:
  45134. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  45135. return;
  45136. case 3:
  45137. if (this._defaultModel) {
  45138. if (notifyObject.pressed) {
  45139. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  45140. }
  45141. else {
  45142. (this._defaultModel.getChildren()[2]).position.y = 0;
  45143. }
  45144. }
  45145. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  45146. return;
  45147. }
  45148. };
  45149. return ViveController;
  45150. }(WebVRController));
  45151. BABYLON.ViveController = ViveController;
  45152. })(BABYLON || (BABYLON = {}));
  45153. //# sourceMappingURL=babylon.extendedGamepad.js.map
  45154. /// <reference path="babylon.targetCamera.ts" />
  45155. var BABYLON;
  45156. (function (BABYLON) {
  45157. var FollowCamera = (function (_super) {
  45158. __extends(FollowCamera, _super);
  45159. function FollowCamera(name, position, scene, lockedTarget) {
  45160. var _this = _super.call(this, name, position, scene) || this;
  45161. _this.radius = 12;
  45162. _this.rotationOffset = 0;
  45163. _this.heightOffset = 4;
  45164. _this.cameraAcceleration = 0.05;
  45165. _this.maxCameraSpeed = 20;
  45166. _this.lockedTarget = lockedTarget;
  45167. return _this;
  45168. }
  45169. FollowCamera.prototype.getRadians = function (degrees) {
  45170. return degrees * Math.PI / 180;
  45171. };
  45172. FollowCamera.prototype.follow = function (cameraTarget) {
  45173. if (!cameraTarget)
  45174. return;
  45175. var yRotation;
  45176. if (cameraTarget.rotationQuaternion) {
  45177. var rotMatrix = new BABYLON.Matrix();
  45178. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  45179. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  45180. }
  45181. else {
  45182. yRotation = cameraTarget.rotation.y;
  45183. }
  45184. var radians = this.getRadians(this.rotationOffset) + yRotation;
  45185. var targetPosition = cameraTarget.getAbsolutePosition();
  45186. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  45187. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  45188. var dx = targetX - this.position.x;
  45189. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  45190. var dz = (targetZ) - this.position.z;
  45191. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  45192. var vy = dy * this.cameraAcceleration;
  45193. var vz = dz * this.cameraAcceleration * 2;
  45194. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  45195. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  45196. }
  45197. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  45198. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  45199. }
  45200. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  45201. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  45202. }
  45203. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  45204. this.setTarget(targetPosition);
  45205. };
  45206. FollowCamera.prototype._checkInputs = function () {
  45207. _super.prototype._checkInputs.call(this);
  45208. this.follow(this.lockedTarget);
  45209. };
  45210. FollowCamera.prototype.getClassName = function () {
  45211. return "FollowCamera";
  45212. };
  45213. return FollowCamera;
  45214. }(BABYLON.TargetCamera));
  45215. __decorate([
  45216. BABYLON.serialize()
  45217. ], FollowCamera.prototype, "radius", void 0);
  45218. __decorate([
  45219. BABYLON.serialize()
  45220. ], FollowCamera.prototype, "rotationOffset", void 0);
  45221. __decorate([
  45222. BABYLON.serialize()
  45223. ], FollowCamera.prototype, "heightOffset", void 0);
  45224. __decorate([
  45225. BABYLON.serialize()
  45226. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  45227. __decorate([
  45228. BABYLON.serialize()
  45229. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  45230. __decorate([
  45231. BABYLON.serializeAsMeshReference("lockedTargetId")
  45232. ], FollowCamera.prototype, "lockedTarget", void 0);
  45233. BABYLON.FollowCamera = FollowCamera;
  45234. var ArcFollowCamera = (function (_super) {
  45235. __extends(ArcFollowCamera, _super);
  45236. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  45237. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45238. _this.alpha = alpha;
  45239. _this.beta = beta;
  45240. _this.radius = radius;
  45241. _this.target = target;
  45242. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  45243. _this.follow();
  45244. return _this;
  45245. }
  45246. ArcFollowCamera.prototype.follow = function () {
  45247. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  45248. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  45249. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  45250. var targetPosition = this.target.getAbsolutePosition();
  45251. this.position = targetPosition.add(this._cartesianCoordinates);
  45252. this.setTarget(targetPosition);
  45253. };
  45254. ArcFollowCamera.prototype._checkInputs = function () {
  45255. _super.prototype._checkInputs.call(this);
  45256. this.follow();
  45257. };
  45258. ArcFollowCamera.prototype.getClassName = function () {
  45259. return "ArcFollowCamera";
  45260. };
  45261. return ArcFollowCamera;
  45262. }(BABYLON.TargetCamera));
  45263. BABYLON.ArcFollowCamera = ArcFollowCamera;
  45264. })(BABYLON || (BABYLON = {}));
  45265. //# sourceMappingURL=babylon.followCamera.js.map
  45266. /// <reference path="babylon.touchCamera.ts" />
  45267. var BABYLON;
  45268. (function (BABYLON) {
  45269. // We're mainly based on the logic defined into the FreeCamera code
  45270. var UniversalCamera = (function (_super) {
  45271. __extends(UniversalCamera, _super);
  45272. //-- end properties for backward compatibility for inputs
  45273. function UniversalCamera(name, position, scene) {
  45274. var _this = _super.call(this, name, position, scene) || this;
  45275. _this.inputs.addGamepad();
  45276. return _this;
  45277. }
  45278. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  45279. //-- Begin properties for backward compatibility for inputs
  45280. get: function () {
  45281. var gamepad = this.inputs.attached["gamepad"];
  45282. if (gamepad)
  45283. return gamepad.gamepadAngularSensibility;
  45284. },
  45285. set: function (value) {
  45286. var gamepad = this.inputs.attached["gamepad"];
  45287. if (gamepad)
  45288. gamepad.gamepadAngularSensibility = value;
  45289. },
  45290. enumerable: true,
  45291. configurable: true
  45292. });
  45293. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  45294. get: function () {
  45295. var gamepad = this.inputs.attached["gamepad"];
  45296. if (gamepad)
  45297. return gamepad.gamepadMoveSensibility;
  45298. },
  45299. set: function (value) {
  45300. var gamepad = this.inputs.attached["gamepad"];
  45301. if (gamepad)
  45302. gamepad.gamepadMoveSensibility = value;
  45303. },
  45304. enumerable: true,
  45305. configurable: true
  45306. });
  45307. UniversalCamera.prototype.getClassName = function () {
  45308. return "UniversalCamera";
  45309. };
  45310. return UniversalCamera;
  45311. }(BABYLON.TouchCamera));
  45312. BABYLON.UniversalCamera = UniversalCamera;
  45313. })(BABYLON || (BABYLON = {}));
  45314. //# sourceMappingURL=babylon.universalCamera.js.map
  45315. /// <reference path="babylon.universalCamera.ts" />
  45316. var BABYLON;
  45317. (function (BABYLON) {
  45318. // We're mainly based on the logic defined into the FreeCamera code
  45319. var GamepadCamera = (function (_super) {
  45320. __extends(GamepadCamera, _super);
  45321. //-- end properties for backward compatibility for inputs
  45322. function GamepadCamera(name, position, scene) {
  45323. return _super.call(this, name, position, scene) || this;
  45324. }
  45325. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  45326. //-- Begin properties for backward compatibility for inputs
  45327. get: function () {
  45328. var gamepad = this.inputs.attached["gamepad"];
  45329. if (gamepad)
  45330. return gamepad.gamepadAngularSensibility;
  45331. },
  45332. set: function (value) {
  45333. var gamepad = this.inputs.attached["gamepad"];
  45334. if (gamepad)
  45335. gamepad.gamepadAngularSensibility = value;
  45336. },
  45337. enumerable: true,
  45338. configurable: true
  45339. });
  45340. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  45341. get: function () {
  45342. var gamepad = this.inputs.attached["gamepad"];
  45343. if (gamepad)
  45344. return gamepad.gamepadMoveSensibility;
  45345. },
  45346. set: function (value) {
  45347. var gamepad = this.inputs.attached["gamepad"];
  45348. if (gamepad)
  45349. gamepad.gamepadMoveSensibility = value;
  45350. },
  45351. enumerable: true,
  45352. configurable: true
  45353. });
  45354. GamepadCamera.prototype.getClassName = function () {
  45355. return "GamepadCamera";
  45356. };
  45357. return GamepadCamera;
  45358. }(BABYLON.UniversalCamera));
  45359. BABYLON.GamepadCamera = GamepadCamera;
  45360. })(BABYLON || (BABYLON = {}));
  45361. //# sourceMappingURL=babylon.gamepadCamera.js.map
  45362. var BABYLON;
  45363. (function (BABYLON) {
  45364. var DepthRenderer = (function () {
  45365. function DepthRenderer(scene, type) {
  45366. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  45367. var _this = this;
  45368. this._viewMatrix = BABYLON.Matrix.Zero();
  45369. this._projectionMatrix = BABYLON.Matrix.Zero();
  45370. this._transformMatrix = BABYLON.Matrix.Zero();
  45371. this._worldViewProjection = BABYLON.Matrix.Zero();
  45372. this._scene = scene;
  45373. var engine = scene.getEngine();
  45374. // Render target
  45375. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  45376. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45377. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45378. this._depthMap.refreshRate = 1;
  45379. this._depthMap.renderParticles = false;
  45380. this._depthMap.renderList = null;
  45381. // set default depth value to 1.0 (far away)
  45382. this._depthMap.onClearObservable.add(function (engine) {
  45383. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  45384. });
  45385. // Custom render function
  45386. var renderSubMesh = function (subMesh) {
  45387. var mesh = subMesh.getRenderingMesh();
  45388. var scene = _this._scene;
  45389. var engine = scene.getEngine();
  45390. // Culling
  45391. engine.setState(subMesh.getMaterial().backFaceCulling);
  45392. // Managing instances
  45393. var batch = mesh._getInstancesRenderList(subMesh._id);
  45394. if (batch.mustReturn) {
  45395. return;
  45396. }
  45397. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  45398. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  45399. engine.enableEffect(_this._effect);
  45400. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  45401. var material = subMesh.getMaterial();
  45402. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  45403. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  45404. // Alpha test
  45405. if (material && material.needAlphaTesting()) {
  45406. var alphaTexture = material.getAlphaTestTexture();
  45407. _this._effect.setTexture("diffuseSampler", alphaTexture);
  45408. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45409. }
  45410. // Bones
  45411. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45412. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45413. }
  45414. // Draw
  45415. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  45416. }
  45417. };
  45418. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  45419. var index;
  45420. for (index = 0; index < opaqueSubMeshes.length; index++) {
  45421. renderSubMesh(opaqueSubMeshes.data[index]);
  45422. }
  45423. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  45424. renderSubMesh(alphaTestSubMeshes.data[index]);
  45425. }
  45426. };
  45427. }
  45428. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  45429. var material = subMesh.getMaterial();
  45430. if (material.disableDepthWrite) {
  45431. return false;
  45432. }
  45433. var defines = [];
  45434. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45435. var mesh = subMesh.getMesh();
  45436. var scene = mesh.getScene();
  45437. // Alpha test
  45438. if (material && material.needAlphaTesting()) {
  45439. defines.push("#define ALPHATEST");
  45440. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45441. attribs.push(BABYLON.VertexBuffer.UVKind);
  45442. defines.push("#define UV1");
  45443. }
  45444. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45445. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45446. defines.push("#define UV2");
  45447. }
  45448. }
  45449. // Bones
  45450. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45451. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45452. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45453. if (mesh.numBoneInfluencers > 4) {
  45454. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45455. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45456. }
  45457. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45458. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45459. }
  45460. else {
  45461. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45462. }
  45463. // Instances
  45464. if (useInstances) {
  45465. defines.push("#define INSTANCES");
  45466. attribs.push("world0");
  45467. attribs.push("world1");
  45468. attribs.push("world2");
  45469. attribs.push("world3");
  45470. }
  45471. // Get correct effect
  45472. var join = defines.join("\n");
  45473. if (this._cachedDefines !== join) {
  45474. this._cachedDefines = join;
  45475. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  45476. }
  45477. return this._effect.isReady();
  45478. };
  45479. DepthRenderer.prototype.getDepthMap = function () {
  45480. return this._depthMap;
  45481. };
  45482. // Methods
  45483. DepthRenderer.prototype.dispose = function () {
  45484. this._depthMap.dispose();
  45485. };
  45486. return DepthRenderer;
  45487. }());
  45488. BABYLON.DepthRenderer = DepthRenderer;
  45489. })(BABYLON || (BABYLON = {}));
  45490. //# sourceMappingURL=babylon.depthRenderer.js.map
  45491. var BABYLON;
  45492. (function (BABYLON) {
  45493. var PostProcessRenderPipelineManager = (function () {
  45494. function PostProcessRenderPipelineManager() {
  45495. this._renderPipelines = {};
  45496. }
  45497. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  45498. this._renderPipelines[renderPipeline._name] = renderPipeline;
  45499. };
  45500. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  45501. var renderPipeline = this._renderPipelines[renderPipelineName];
  45502. if (!renderPipeline) {
  45503. return;
  45504. }
  45505. renderPipeline._attachCameras(cameras, unique);
  45506. };
  45507. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  45508. var renderPipeline = this._renderPipelines[renderPipelineName];
  45509. if (!renderPipeline) {
  45510. return;
  45511. }
  45512. renderPipeline._detachCameras(cameras);
  45513. };
  45514. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  45515. var renderPipeline = this._renderPipelines[renderPipelineName];
  45516. if (!renderPipeline) {
  45517. return;
  45518. }
  45519. renderPipeline._enableEffect(renderEffectName, cameras);
  45520. };
  45521. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  45522. var renderPipeline = this._renderPipelines[renderPipelineName];
  45523. if (!renderPipeline) {
  45524. return;
  45525. }
  45526. renderPipeline._disableEffect(renderEffectName, cameras);
  45527. };
  45528. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  45529. var renderPipeline = this._renderPipelines[renderPipelineName];
  45530. if (!renderPipeline) {
  45531. return;
  45532. }
  45533. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  45534. };
  45535. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  45536. var renderPipeline = this._renderPipelines[renderPipelineName];
  45537. if (!renderPipeline) {
  45538. return;
  45539. }
  45540. renderPipeline._disableDisplayOnlyPass(cameras);
  45541. };
  45542. PostProcessRenderPipelineManager.prototype.update = function () {
  45543. for (var renderPipelineName in this._renderPipelines) {
  45544. var pipeline = this._renderPipelines[renderPipelineName];
  45545. if (!pipeline.isSupported) {
  45546. pipeline.dispose();
  45547. delete this._renderPipelines[renderPipelineName];
  45548. }
  45549. else {
  45550. pipeline._update();
  45551. }
  45552. }
  45553. };
  45554. return PostProcessRenderPipelineManager;
  45555. }());
  45556. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  45557. })(BABYLON || (BABYLON = {}));
  45558. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  45559. var BABYLON;
  45560. (function (BABYLON) {
  45561. var PostProcessRenderPass = (function () {
  45562. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  45563. this._enabled = true;
  45564. this._refCount = 0;
  45565. this._name = name;
  45566. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  45567. this.setRenderList(renderList);
  45568. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  45569. this._renderTexture.onAfterRenderObservable.add(afterRender);
  45570. this._scene = scene;
  45571. this._renderList = renderList;
  45572. }
  45573. // private
  45574. PostProcessRenderPass.prototype._incRefCount = function () {
  45575. if (this._refCount === 0) {
  45576. this._scene.customRenderTargets.push(this._renderTexture);
  45577. }
  45578. return ++this._refCount;
  45579. };
  45580. PostProcessRenderPass.prototype._decRefCount = function () {
  45581. this._refCount--;
  45582. if (this._refCount <= 0) {
  45583. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  45584. }
  45585. return this._refCount;
  45586. };
  45587. PostProcessRenderPass.prototype._update = function () {
  45588. this.setRenderList(this._renderList);
  45589. };
  45590. // public
  45591. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  45592. this._renderTexture.renderList = renderList;
  45593. };
  45594. PostProcessRenderPass.prototype.getRenderTexture = function () {
  45595. return this._renderTexture;
  45596. };
  45597. return PostProcessRenderPass;
  45598. }());
  45599. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  45600. })(BABYLON || (BABYLON = {}));
  45601. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  45602. var BABYLON;
  45603. (function (BABYLON) {
  45604. var PostProcessRenderEffect = (function () {
  45605. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  45606. this._engine = engine;
  45607. this._name = name;
  45608. this._singleInstance = singleInstance || true;
  45609. this._getPostProcess = getPostProcess;
  45610. this._cameras = [];
  45611. this._indicesForCamera = [];
  45612. this._postProcesses = {};
  45613. this._renderPasses = {};
  45614. this._renderEffectAsPasses = {};
  45615. }
  45616. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  45617. get: function () {
  45618. for (var index in this._postProcesses) {
  45619. if (!this._postProcesses[index].isSupported) {
  45620. return false;
  45621. }
  45622. }
  45623. return true;
  45624. },
  45625. enumerable: true,
  45626. configurable: true
  45627. });
  45628. PostProcessRenderEffect.prototype._update = function () {
  45629. for (var renderPassName in this._renderPasses) {
  45630. this._renderPasses[renderPassName]._update();
  45631. }
  45632. };
  45633. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  45634. this._renderPasses[renderPass._name] = renderPass;
  45635. this._linkParameters();
  45636. };
  45637. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  45638. delete this._renderPasses[renderPass._name];
  45639. this._linkParameters();
  45640. };
  45641. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  45642. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  45643. this._linkParameters();
  45644. };
  45645. PostProcessRenderEffect.prototype.getPass = function (passName) {
  45646. for (var renderPassName in this._renderPasses) {
  45647. if (renderPassName === passName) {
  45648. return this._renderPasses[passName];
  45649. }
  45650. }
  45651. };
  45652. PostProcessRenderEffect.prototype.emptyPasses = function () {
  45653. this._renderPasses = {};
  45654. this._linkParameters();
  45655. };
  45656. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  45657. var cameraKey;
  45658. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45659. for (var i = 0; i < _cam.length; i++) {
  45660. var camera = _cam[i];
  45661. var cameraName = camera.name;
  45662. if (this._singleInstance) {
  45663. cameraKey = 0;
  45664. }
  45665. else {
  45666. cameraKey = cameraName;
  45667. }
  45668. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  45669. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  45670. if (!this._indicesForCamera[cameraName]) {
  45671. this._indicesForCamera[cameraName] = [];
  45672. }
  45673. this._indicesForCamera[cameraName].push(index);
  45674. if (this._cameras.indexOf(camera) === -1) {
  45675. this._cameras[cameraName] = camera;
  45676. }
  45677. for (var passName in this._renderPasses) {
  45678. this._renderPasses[passName]._incRefCount();
  45679. }
  45680. }
  45681. this._linkParameters();
  45682. };
  45683. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  45684. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45685. for (var i = 0; i < _cam.length; i++) {
  45686. var camera = _cam[i];
  45687. var cameraName = camera.name;
  45688. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  45689. var index = this._cameras.indexOf(cameraName);
  45690. this._indicesForCamera.splice(index, 1);
  45691. this._cameras.splice(index, 1);
  45692. for (var passName in this._renderPasses) {
  45693. this._renderPasses[passName]._decRefCount();
  45694. }
  45695. }
  45696. };
  45697. PostProcessRenderEffect.prototype._enable = function (cameras) {
  45698. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45699. for (var i = 0; i < _cam.length; i++) {
  45700. var camera = _cam[i];
  45701. var cameraName = camera.name;
  45702. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  45703. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  45704. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  45705. }
  45706. }
  45707. for (var passName in this._renderPasses) {
  45708. this._renderPasses[passName]._incRefCount();
  45709. }
  45710. }
  45711. };
  45712. PostProcessRenderEffect.prototype._disable = function (cameras) {
  45713. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45714. for (var i = 0; i < _cam.length; i++) {
  45715. var camera = _cam[i];
  45716. var cameraName = camera.Name;
  45717. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  45718. for (var passName in this._renderPasses) {
  45719. this._renderPasses[passName]._decRefCount();
  45720. }
  45721. }
  45722. };
  45723. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  45724. if (this._singleInstance) {
  45725. return this._postProcesses[0];
  45726. }
  45727. else {
  45728. return this._postProcesses[camera.name];
  45729. }
  45730. };
  45731. PostProcessRenderEffect.prototype._linkParameters = function () {
  45732. var _this = this;
  45733. for (var index in this._postProcesses) {
  45734. if (this.applyParameters) {
  45735. this.applyParameters(this._postProcesses[index]);
  45736. }
  45737. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  45738. _this._linkTextures(effect);
  45739. });
  45740. }
  45741. };
  45742. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  45743. for (var renderPassName in this._renderPasses) {
  45744. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  45745. }
  45746. for (var renderEffectName in this._renderEffectAsPasses) {
  45747. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  45748. }
  45749. };
  45750. return PostProcessRenderEffect;
  45751. }());
  45752. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  45753. })(BABYLON || (BABYLON = {}));
  45754. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  45755. var BABYLON;
  45756. (function (BABYLON) {
  45757. var PostProcessRenderPipeline = (function () {
  45758. function PostProcessRenderPipeline(engine, name) {
  45759. this._engine = engine;
  45760. this._name = name;
  45761. this._renderEffects = {};
  45762. this._renderEffectsForIsolatedPass = {};
  45763. this._cameras = [];
  45764. }
  45765. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  45766. get: function () {
  45767. for (var renderEffectName in this._renderEffects) {
  45768. if (!this._renderEffects[renderEffectName].isSupported) {
  45769. return false;
  45770. }
  45771. }
  45772. return true;
  45773. },
  45774. enumerable: true,
  45775. configurable: true
  45776. });
  45777. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  45778. this._renderEffects[renderEffect._name] = renderEffect;
  45779. };
  45780. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  45781. var renderEffects = this._renderEffects[renderEffectName];
  45782. if (!renderEffects) {
  45783. return;
  45784. }
  45785. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  45786. };
  45787. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  45788. var renderEffects = this._renderEffects[renderEffectName];
  45789. if (!renderEffects) {
  45790. return;
  45791. }
  45792. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  45793. };
  45794. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  45795. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45796. var indicesToDelete = [];
  45797. var i;
  45798. for (i = 0; i < _cam.length; i++) {
  45799. var camera = _cam[i];
  45800. var cameraName = camera.name;
  45801. if (this._cameras.indexOf(camera) === -1) {
  45802. this._cameras[cameraName] = camera;
  45803. }
  45804. else if (unique) {
  45805. indicesToDelete.push(i);
  45806. }
  45807. }
  45808. for (i = 0; i < indicesToDelete.length; i++) {
  45809. cameras.splice(indicesToDelete[i], 1);
  45810. }
  45811. for (var renderEffectName in this._renderEffects) {
  45812. this._renderEffects[renderEffectName]._attachCameras(_cam);
  45813. }
  45814. };
  45815. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  45816. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45817. for (var renderEffectName in this._renderEffects) {
  45818. this._renderEffects[renderEffectName]._detachCameras(_cam);
  45819. }
  45820. for (var i = 0; i < _cam.length; i++) {
  45821. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  45822. }
  45823. };
  45824. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  45825. var _this = this;
  45826. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45827. var pass = null;
  45828. var renderEffectName;
  45829. for (renderEffectName in this._renderEffects) {
  45830. pass = this._renderEffects[renderEffectName].getPass(passName);
  45831. if (pass != null) {
  45832. break;
  45833. }
  45834. }
  45835. if (pass === null) {
  45836. return;
  45837. }
  45838. for (renderEffectName in this._renderEffects) {
  45839. this._renderEffects[renderEffectName]._disable(_cam);
  45840. }
  45841. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  45842. for (var i = 0; i < _cam.length; i++) {
  45843. var camera = _cam[i];
  45844. var cameraName = camera.name;
  45845. 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); });
  45846. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  45847. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  45848. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  45849. }
  45850. };
  45851. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  45852. var _this = this;
  45853. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  45854. for (var i = 0; i < _cam.length; i++) {
  45855. var camera = _cam[i];
  45856. var cameraName = camera.name;
  45857. 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); });
  45858. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  45859. }
  45860. for (var renderEffectName in this._renderEffects) {
  45861. this._renderEffects[renderEffectName]._enable(_cam);
  45862. }
  45863. };
  45864. PostProcessRenderPipeline.prototype._update = function () {
  45865. for (var renderEffectName in this._renderEffects) {
  45866. this._renderEffects[renderEffectName]._update();
  45867. }
  45868. for (var i = 0; i < this._cameras.length; i++) {
  45869. var cameraName = this._cameras[i].name;
  45870. if (this._renderEffectsForIsolatedPass[cameraName]) {
  45871. this._renderEffectsForIsolatedPass[cameraName]._update();
  45872. }
  45873. }
  45874. };
  45875. PostProcessRenderPipeline.prototype.dispose = function () {
  45876. // Must be implemented by children
  45877. };
  45878. return PostProcessRenderPipeline;
  45879. }());
  45880. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  45881. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  45882. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  45883. })(BABYLON || (BABYLON = {}));
  45884. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  45885. var BABYLON;
  45886. (function (BABYLON) {
  45887. var SSAORenderingPipeline = (function (_super) {
  45888. __extends(SSAORenderingPipeline, _super);
  45889. /**
  45890. * @constructor
  45891. * @param {string} name - The rendering pipeline name
  45892. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  45893. * @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 }
  45894. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  45895. */
  45896. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  45897. var _this = _super.call(this, scene.getEngine(), name) || this;
  45898. // Members
  45899. /**
  45900. * The PassPostProcess id in the pipeline that contains the original scene color
  45901. * @type {string}
  45902. */
  45903. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  45904. /**
  45905. * The SSAO PostProcess id in the pipeline
  45906. * @type {string}
  45907. */
  45908. _this.SSAORenderEffect = "SSAORenderEffect";
  45909. /**
  45910. * The horizontal blur PostProcess id in the pipeline
  45911. * @type {string}
  45912. */
  45913. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  45914. /**
  45915. * The vertical blur PostProcess id in the pipeline
  45916. * @type {string}
  45917. */
  45918. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  45919. /**
  45920. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  45921. * @type {string}
  45922. */
  45923. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  45924. /**
  45925. * The output strength of the SSAO post-process. Default value is 1.0.
  45926. * @type {number}
  45927. */
  45928. _this.totalStrength = 1.0;
  45929. /**
  45930. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  45931. * @type {number}
  45932. */
  45933. _this.radius = 0.0001;
  45934. /**
  45935. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  45936. * Must not be equal to fallOff and superior to fallOff.
  45937. * Default value is 0.975
  45938. * @type {number}
  45939. */
  45940. _this.area = 0.0075;
  45941. /**
  45942. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  45943. * Must not be equal to area and inferior to area.
  45944. * Default value is 0.0
  45945. * @type {number}
  45946. */
  45947. _this.fallOff = 0.000001;
  45948. /**
  45949. * The base color of the SSAO post-process
  45950. * The final result is "base + ssao" between [0, 1]
  45951. * @type {number}
  45952. */
  45953. _this.base = 0.5;
  45954. _this._firstUpdate = true;
  45955. _this._scene = scene;
  45956. // Set up assets
  45957. _this._createRandomTexture();
  45958. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  45959. var ssaoRatio = ratio.ssaoRatio || ratio;
  45960. var combineRatio = ratio.combineRatio || ratio;
  45961. _this._ratio = {
  45962. ssaoRatio: ssaoRatio,
  45963. combineRatio: combineRatio
  45964. };
  45965. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  45966. _this._createSSAOPostProcess(ssaoRatio);
  45967. _this._createBlurPostProcess(ssaoRatio);
  45968. _this._createSSAOCombinePostProcess(combineRatio);
  45969. // Set up pipeline
  45970. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  45971. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  45972. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  45973. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  45974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  45975. // Finish
  45976. scene.postProcessRenderPipelineManager.addPipeline(_this);
  45977. if (cameras)
  45978. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  45979. return _this;
  45980. }
  45981. // Public Methods
  45982. /**
  45983. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  45984. */
  45985. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  45986. if (disableDepthRender === void 0) { disableDepthRender = false; }
  45987. for (var i = 0; i < this._scene.cameras.length; i++) {
  45988. var camera = this._scene.cameras[i];
  45989. this._originalColorPostProcess.dispose(camera);
  45990. this._ssaoPostProcess.dispose(camera);
  45991. this._blurHPostProcess.dispose(camera);
  45992. this._blurVPostProcess.dispose(camera);
  45993. this._ssaoCombinePostProcess.dispose(camera);
  45994. }
  45995. this._randomTexture.dispose();
  45996. if (disableDepthRender)
  45997. this._scene.disableDepthRenderer();
  45998. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  45999. _super.prototype.dispose.call(this);
  46000. };
  46001. // Private Methods
  46002. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  46003. var _this = this;
  46004. /*
  46005. var samplerOffsets = [
  46006. -8.0, -6.0, -4.0, -2.0,
  46007. 0.0,
  46008. 2.0, 4.0, 6.0, 8.0
  46009. ];
  46010. */
  46011. var samples = 16;
  46012. var samplerOffsets = [];
  46013. for (var i = -8; i < 8; i++) {
  46014. samplerOffsets.push(i * 2);
  46015. }
  46016. 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");
  46017. this._blurHPostProcess.onApply = function (effect) {
  46018. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  46019. effect.setTexture("depthSampler", _this._depthTexture);
  46020. if (_this._firstUpdate) {
  46021. effect.setArray("samplerOffsets", samplerOffsets);
  46022. }
  46023. };
  46024. 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");
  46025. this._blurVPostProcess.onApply = function (effect) {
  46026. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  46027. effect.setTexture("depthSampler", _this._depthTexture);
  46028. if (_this._firstUpdate) {
  46029. effect.setArray("samplerOffsets", samplerOffsets);
  46030. _this._firstUpdate = false;
  46031. }
  46032. };
  46033. };
  46034. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  46035. var _this = this;
  46036. var numSamples = 16;
  46037. var sampleSphere = [
  46038. 0.5381, 0.1856, -0.4319,
  46039. 0.1379, 0.2486, 0.4430,
  46040. 0.3371, 0.5679, -0.0057,
  46041. -0.6999, -0.0451, -0.0019,
  46042. 0.0689, -0.1598, -0.8547,
  46043. 0.0560, 0.0069, -0.1843,
  46044. -0.0146, 0.1402, 0.0762,
  46045. 0.0100, -0.1924, -0.0344,
  46046. -0.3577, -0.5301, -0.4358,
  46047. -0.3169, 0.1063, 0.0158,
  46048. 0.0103, -0.5869, 0.0046,
  46049. -0.0897, -0.4940, 0.3287,
  46050. 0.7119, -0.0154, -0.0918,
  46051. -0.0533, 0.0596, -0.5411,
  46052. 0.0352, -0.0631, 0.5460,
  46053. -0.4776, 0.2847, -0.0271
  46054. ];
  46055. var samplesFactor = 1.0 / numSamples;
  46056. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  46057. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  46058. "area", "fallOff", "base", "range", "viewport"
  46059. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  46060. var viewport = new BABYLON.Vector2(0, 0);
  46061. this._ssaoPostProcess.onApply = function (effect) {
  46062. if (_this._firstUpdate) {
  46063. effect.setArray3("sampleSphere", sampleSphere);
  46064. effect.setFloat("samplesFactor", samplesFactor);
  46065. effect.setFloat("randTextureTiles", 4.0);
  46066. }
  46067. effect.setFloat("totalStrength", _this.totalStrength);
  46068. effect.setFloat("radius", _this.radius);
  46069. effect.setFloat("area", _this.area);
  46070. effect.setFloat("fallOff", _this.fallOff);
  46071. effect.setFloat("base", _this.base);
  46072. effect.setTexture("textureSampler", _this._depthTexture);
  46073. effect.setTexture("randomSampler", _this._randomTexture);
  46074. };
  46075. };
  46076. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  46077. var _this = this;
  46078. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46079. this._ssaoCombinePostProcess.onApply = function (effect) {
  46080. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  46081. };
  46082. };
  46083. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  46084. var size = 512;
  46085. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  46086. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46087. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46088. var context = this._randomTexture.getContext();
  46089. var rand = function (min, max) {
  46090. return Math.random() * (max - min) + min;
  46091. };
  46092. var randVector = BABYLON.Vector3.Zero();
  46093. for (var x = 0; x < size; x++) {
  46094. for (var y = 0; y < size; y++) {
  46095. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  46096. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  46097. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  46098. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  46099. context.fillRect(x, y, 1, 1);
  46100. }
  46101. }
  46102. this._randomTexture.update(false);
  46103. };
  46104. return SSAORenderingPipeline;
  46105. }(BABYLON.PostProcessRenderPipeline));
  46106. __decorate([
  46107. BABYLON.serialize()
  46108. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  46109. __decorate([
  46110. BABYLON.serialize()
  46111. ], SSAORenderingPipeline.prototype, "radius", void 0);
  46112. __decorate([
  46113. BABYLON.serialize()
  46114. ], SSAORenderingPipeline.prototype, "area", void 0);
  46115. __decorate([
  46116. BABYLON.serialize()
  46117. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  46118. __decorate([
  46119. BABYLON.serialize()
  46120. ], SSAORenderingPipeline.prototype, "base", void 0);
  46121. __decorate([
  46122. BABYLON.serialize()
  46123. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  46124. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  46125. })(BABYLON || (BABYLON = {}));
  46126. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  46127. // BABYLON.JS Chromatic Aberration GLSL Shader
  46128. // Author: Olivier Guyot
  46129. // Separates very slightly R, G and B colors on the edges of the screen
  46130. // Inspired by Francois Tarlier & Martins Upitis
  46131. var BABYLON;
  46132. (function (BABYLON) {
  46133. var LensRenderingPipeline = (function (_super) {
  46134. __extends(LensRenderingPipeline, _super);
  46135. /**
  46136. * @constructor
  46137. *
  46138. * Effect parameters are as follow:
  46139. * {
  46140. * chromatic_aberration: number; // from 0 to x (1 for realism)
  46141. * edge_blur: number; // from 0 to x (1 for realism)
  46142. * distortion: number; // from 0 to x (1 for realism)
  46143. * grain_amount: number; // from 0 to 1
  46144. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  46145. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  46146. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  46147. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  46148. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  46149. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  46150. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  46151. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  46152. * }
  46153. * Note: if an effect parameter is unset, effect is disabled
  46154. *
  46155. * @param {string} name - The rendering pipeline name
  46156. * @param {object} parameters - An object containing all parameters (see above)
  46157. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46158. * @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)
  46159. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46160. */
  46161. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  46162. if (ratio === void 0) { ratio = 1.0; }
  46163. var _this = _super.call(this, scene.getEngine(), name) || this;
  46164. // Lens effects can be of the following:
  46165. // - chromatic aberration (slight shift of RGB colors)
  46166. // - blur on the edge of the lens
  46167. // - lens distortion
  46168. // - depth-of-field blur & highlights enhancing
  46169. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  46170. // - grain effect (noise or custom texture)
  46171. // Two additional texture samplers are needed:
  46172. // - depth map (for depth-of-field)
  46173. // - grain texture
  46174. /**
  46175. * The chromatic aberration PostProcess id in the pipeline
  46176. * @type {string}
  46177. */
  46178. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  46179. /**
  46180. * The highlights enhancing PostProcess id in the pipeline
  46181. * @type {string}
  46182. */
  46183. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  46184. /**
  46185. * The depth-of-field PostProcess id in the pipeline
  46186. * @type {string}
  46187. */
  46188. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  46189. _this._scene = scene;
  46190. // Fetch texture samplers
  46191. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  46192. if (parameters.grain_texture) {
  46193. _this._grainTexture = parameters.grain_texture;
  46194. }
  46195. else {
  46196. _this._createGrainTexture();
  46197. }
  46198. // save parameters
  46199. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  46200. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  46201. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  46202. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  46203. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  46204. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  46205. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  46206. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  46207. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  46208. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  46209. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  46210. // Create effects
  46211. _this._createChromaticAberrationPostProcess(ratio);
  46212. _this._createHighlightsPostProcess(ratio);
  46213. _this._createDepthOfFieldPostProcess(ratio / 4);
  46214. // Set up pipeline
  46215. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  46216. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  46217. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  46218. if (_this._highlightsGain === -1) {
  46219. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  46220. }
  46221. // Finish
  46222. scene.postProcessRenderPipelineManager.addPipeline(_this);
  46223. if (cameras) {
  46224. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46225. }
  46226. return _this;
  46227. }
  46228. // public methods (self explanatory)
  46229. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  46230. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  46231. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  46232. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  46233. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  46234. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  46235. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  46236. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  46237. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  46238. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  46239. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  46240. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  46241. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  46242. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  46243. };
  46244. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  46245. this._highlightsPostProcess.updateEffect();
  46246. };
  46247. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  46248. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  46249. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  46250. this._highlightsGain = amount;
  46251. };
  46252. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  46253. if (this._highlightsGain === -1) {
  46254. this._highlightsGain = 1.0;
  46255. }
  46256. this._highlightsThreshold = amount;
  46257. };
  46258. LensRenderingPipeline.prototype.disableHighlights = function () {
  46259. this._highlightsGain = -1;
  46260. };
  46261. /**
  46262. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  46263. */
  46264. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  46265. if (disableDepthRender === void 0) { disableDepthRender = false; }
  46266. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46267. this._chromaticAberrationPostProcess = undefined;
  46268. this._highlightsPostProcess = undefined;
  46269. this._depthOfFieldPostProcess = undefined;
  46270. this._grainTexture.dispose();
  46271. if (disableDepthRender)
  46272. this._scene.disableDepthRenderer();
  46273. };
  46274. // colors shifting and distortion
  46275. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  46276. var _this = this;
  46277. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  46278. [], // samplers
  46279. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46280. this._chromaticAberrationPostProcess.onApply = function (effect) {
  46281. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  46282. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46283. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46284. };
  46285. };
  46286. // highlights enhancing
  46287. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  46288. var _this = this;
  46289. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  46290. [], // samplers
  46291. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  46292. this._highlightsPostProcess.onApply = function (effect) {
  46293. effect.setFloat('gain', _this._highlightsGain);
  46294. effect.setFloat('threshold', _this._highlightsThreshold);
  46295. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  46296. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46297. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46298. };
  46299. };
  46300. // colors shifting and distortion
  46301. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  46302. var _this = this;
  46303. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  46304. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  46305. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  46306. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46307. this._depthOfFieldPostProcess.onApply = function (effect) {
  46308. effect.setTexture("depthSampler", _this._depthTexture);
  46309. effect.setTexture("grainSampler", _this._grainTexture);
  46310. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  46311. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  46312. effect.setFloat('grain_amount', _this._grainAmount);
  46313. effect.setBool('blur_noise', _this._blurNoise);
  46314. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46315. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46316. effect.setFloat('distortion', _this._distortion);
  46317. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  46318. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  46319. effect.setFloat('aperture', _this._dofAperture);
  46320. effect.setFloat('darken', _this._dofDarken);
  46321. effect.setFloat('edge_blur', _this._edgeBlur);
  46322. effect.setBool('highlights', (_this._highlightsGain !== -1));
  46323. effect.setFloat('near', _this._scene.activeCamera.minZ);
  46324. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  46325. };
  46326. };
  46327. // creates a black and white random noise texture, 512x512
  46328. LensRenderingPipeline.prototype._createGrainTexture = function () {
  46329. var size = 512;
  46330. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46331. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46332. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46333. var context = this._grainTexture.getContext();
  46334. var rand = function (min, max) {
  46335. return Math.random() * (max - min) + min;
  46336. };
  46337. var value;
  46338. for (var x = 0; x < size; x++) {
  46339. for (var y = 0; y < size; y++) {
  46340. value = Math.floor(rand(0.42, 0.58) * 255);
  46341. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  46342. context.fillRect(x, y, 1, 1);
  46343. }
  46344. }
  46345. this._grainTexture.update(false);
  46346. };
  46347. return LensRenderingPipeline;
  46348. }(BABYLON.PostProcessRenderPipeline));
  46349. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  46350. })(BABYLON || (BABYLON = {}));
  46351. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  46352. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  46353. var BABYLON;
  46354. (function (BABYLON) {
  46355. var HDRRenderingPipeline = (function (_super) {
  46356. __extends(HDRRenderingPipeline, _super);
  46357. /**
  46358. * @constructor
  46359. * @param {string} name - The rendering pipeline name
  46360. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46361. * @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)
  46362. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  46363. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46364. */
  46365. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  46366. if (originalPostProcess === void 0) { originalPostProcess = null; }
  46367. var _this = _super.call(this, scene.getEngine(), name) || this;
  46368. /**
  46369. * Public members
  46370. */
  46371. // Gaussian Blur
  46372. /**
  46373. * Gaussian blur coefficient
  46374. * @type {number}
  46375. */
  46376. _this.gaussCoeff = 0.3;
  46377. /**
  46378. * Gaussian blur mean
  46379. * @type {number}
  46380. */
  46381. _this.gaussMean = 1.0;
  46382. /**
  46383. * Gaussian blur standard deviation
  46384. * @type {number}
  46385. */
  46386. _this.gaussStandDev = 0.8;
  46387. /**
  46388. * Gaussian blur multiplier. Multiplies the blur effect
  46389. * @type {number}
  46390. */
  46391. _this.gaussMultiplier = 4.0;
  46392. // HDR
  46393. /**
  46394. * Exposure, controls the overall intensity of the pipeline
  46395. * @type {number}
  46396. */
  46397. _this.exposure = 1.0;
  46398. /**
  46399. * Minimum luminance that the post-process can output. Luminance is >= 0
  46400. * @type {number}
  46401. */
  46402. _this.minimumLuminance = 1.0;
  46403. /**
  46404. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  46405. * @type {number}
  46406. */
  46407. _this.maximumLuminance = 1e20;
  46408. /**
  46409. * Increase rate for luminance: eye adaptation speed to dark
  46410. * @type {number}
  46411. */
  46412. _this.luminanceIncreaserate = 0.5;
  46413. /**
  46414. * Decrease rate for luminance: eye adaptation speed to bright
  46415. * @type {number}
  46416. */
  46417. _this.luminanceDecreaseRate = 0.5;
  46418. // Bright pass
  46419. /**
  46420. * Minimum luminance needed to compute HDR
  46421. * @type {number}
  46422. */
  46423. _this.brightThreshold = 0.8;
  46424. _this._needUpdate = true;
  46425. _this._scene = scene;
  46426. // Bright pass
  46427. _this._createBrightPassPostProcess(scene, ratio);
  46428. // Down sample X4
  46429. _this._createDownSampleX4PostProcess(scene, ratio);
  46430. // Create gaussian blur post-processes
  46431. _this._createGaussianBlurPostProcess(scene, ratio);
  46432. // Texture adder
  46433. _this._createTextureAdderPostProcess(scene, ratio);
  46434. // Luminance generator
  46435. _this._createLuminanceGeneratorPostProcess(scene);
  46436. // HDR
  46437. _this._createHDRPostProcess(scene, ratio);
  46438. // Pass postprocess
  46439. if (originalPostProcess === null) {
  46440. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46441. }
  46442. else {
  46443. _this._originalPostProcess = originalPostProcess;
  46444. }
  46445. // Configure pipeline
  46446. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  46447. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  46448. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  46449. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  46450. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  46451. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  46452. var addDownSamplerPostProcess = function (id) {
  46453. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  46454. };
  46455. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46456. addDownSamplerPostProcess(i);
  46457. }
  46458. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  46459. // Finish
  46460. scene.postProcessRenderPipelineManager.addPipeline(_this);
  46461. if (cameras !== null) {
  46462. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46463. }
  46464. _this.update();
  46465. return _this;
  46466. }
  46467. /**
  46468. * Tells the pipeline to update its post-processes
  46469. */
  46470. HDRRenderingPipeline.prototype.update = function () {
  46471. this._needUpdate = true;
  46472. };
  46473. /**
  46474. * Returns the current calculated luminance
  46475. */
  46476. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  46477. return this._hdrCurrentLuminance;
  46478. };
  46479. /**
  46480. * Returns the currently drawn luminance
  46481. */
  46482. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  46483. return this._hdrOutputLuminance;
  46484. };
  46485. /**
  46486. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  46487. */
  46488. HDRRenderingPipeline.prototype.dispose = function () {
  46489. for (var i = 0; i < this._scene.cameras.length; i++) {
  46490. var camera = this._scene.cameras[i];
  46491. this._originalPostProcess.dispose(camera);
  46492. this._brightPassPostProcess.dispose(camera);
  46493. this._downSampleX4PostProcess.dispose(camera);
  46494. this._guassianBlurHPostProcess.dispose(camera);
  46495. this._guassianBlurVPostProcess.dispose(camera);
  46496. this._textureAdderPostProcess.dispose(camera);
  46497. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  46498. this._downSamplePostProcesses[j].dispose(camera);
  46499. }
  46500. this._hdrPostProcess.dispose(camera);
  46501. }
  46502. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46503. _super.prototype.dispose.call(this);
  46504. };
  46505. /**
  46506. * Creates the HDR post-process and computes the luminance adaptation
  46507. */
  46508. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  46509. var _this = this;
  46510. var hdrLastLuminance = 0.0;
  46511. this._hdrOutputLuminance = -1.0;
  46512. this._hdrCurrentLuminance = 1.0;
  46513. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  46514. this._hdrPostProcess.onApply = function (effect) {
  46515. if (_this._hdrOutputLuminance < 0.0) {
  46516. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46517. }
  46518. else {
  46519. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  46520. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  46521. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  46522. }
  46523. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  46524. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  46525. }
  46526. else {
  46527. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46528. }
  46529. }
  46530. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  46531. hdrLastLuminance += scene.getEngine().getDeltaTime();
  46532. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46533. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46534. effect.setFloat("exposure", _this.exposure);
  46535. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  46536. _this._needUpdate = false;
  46537. };
  46538. };
  46539. /**
  46540. * Texture Adder post-process
  46541. */
  46542. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  46543. var _this = this;
  46544. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  46545. this._textureAdderPostProcess.onApply = function (effect) {
  46546. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46547. };
  46548. };
  46549. /**
  46550. * Down sample X4 post-process
  46551. */
  46552. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  46553. var _this = this;
  46554. var downSampleX4Offsets = new Array(32);
  46555. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  46556. this._downSampleX4PostProcess.onApply = function (effect) {
  46557. if (_this._needUpdate) {
  46558. var id = 0;
  46559. for (var i = -2; i < 2; i++) {
  46560. for (var j = -2; j < 2; j++) {
  46561. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  46562. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  46563. id += 2;
  46564. }
  46565. }
  46566. }
  46567. effect.setArray2("dsOffsets", downSampleX4Offsets);
  46568. };
  46569. };
  46570. /**
  46571. * Bright pass post-process
  46572. */
  46573. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  46574. var _this = this;
  46575. var brightOffsets = new Array(8);
  46576. var brightPassCallback = function (effect) {
  46577. if (_this._needUpdate) {
  46578. var sU = (1.0 / _this._brightPassPostProcess.width);
  46579. var sV = (1.0 / _this._brightPassPostProcess.height);
  46580. brightOffsets[0] = -0.5 * sU;
  46581. brightOffsets[1] = 0.5 * sV;
  46582. brightOffsets[2] = 0.5 * sU;
  46583. brightOffsets[3] = 0.5 * sV;
  46584. brightOffsets[4] = -0.5 * sU;
  46585. brightOffsets[5] = -0.5 * sV;
  46586. brightOffsets[6] = 0.5 * sU;
  46587. brightOffsets[7] = -0.5 * sV;
  46588. }
  46589. effect.setArray2("dsOffsets", brightOffsets);
  46590. effect.setFloat("brightThreshold", _this.brightThreshold);
  46591. };
  46592. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  46593. this._brightPassPostProcess.onApply = brightPassCallback;
  46594. };
  46595. /**
  46596. * Luminance generator. Creates the luminance post-process and down sample post-processes
  46597. */
  46598. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  46599. var _this = this;
  46600. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  46601. var luminanceOffsets = new Array(8);
  46602. var downSampleOffsets = new Array(18);
  46603. var halfDestPixelSize;
  46604. this._downSamplePostProcesses = new Array(lumSteps);
  46605. // Utils for luminance
  46606. var luminanceUpdateSourceOffsets = function (width, height) {
  46607. var sU = (1.0 / width);
  46608. var sV = (1.0 / height);
  46609. luminanceOffsets[0] = -0.5 * sU;
  46610. luminanceOffsets[1] = 0.5 * sV;
  46611. luminanceOffsets[2] = 0.5 * sU;
  46612. luminanceOffsets[3] = 0.5 * sV;
  46613. luminanceOffsets[4] = -0.5 * sU;
  46614. luminanceOffsets[5] = -0.5 * sV;
  46615. luminanceOffsets[6] = 0.5 * sU;
  46616. luminanceOffsets[7] = -0.5 * sV;
  46617. };
  46618. var luminanceUpdateDestOffsets = function (width, height) {
  46619. var id = 0;
  46620. for (var x = -1; x < 2; x++) {
  46621. for (var y = -1; y < 2; y++) {
  46622. downSampleOffsets[id] = (x) / width;
  46623. downSampleOffsets[id + 1] = (y) / height;
  46624. id += 2;
  46625. }
  46626. }
  46627. };
  46628. // Luminance callback
  46629. var luminanceCallback = function (effect) {
  46630. if (_this._needUpdate) {
  46631. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  46632. }
  46633. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46634. effect.setArray2("lumOffsets", luminanceOffsets);
  46635. };
  46636. // Down sample callbacks
  46637. var downSampleCallback = function (indice) {
  46638. var i = indice;
  46639. return function (effect) {
  46640. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  46641. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  46642. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  46643. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  46644. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  46645. effect.setArray2("dsOffsets", downSampleOffsets);
  46646. };
  46647. };
  46648. var downSampleAfterRenderCallback = function (effect) {
  46649. // Unpack result
  46650. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  46651. 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);
  46652. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  46653. };
  46654. // Create luminance post-process
  46655. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  46656. 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);
  46657. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  46658. // Create down sample post-processes
  46659. for (var i = lumSteps - 2; i >= 0; i--) {
  46660. var length = Math.pow(3, i);
  46661. ratio = { width: length, height: length };
  46662. var defines = "#define DOWN_SAMPLE\n";
  46663. if (i === 0) {
  46664. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  46665. }
  46666. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  46667. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  46668. if (i === 0) {
  46669. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  46670. }
  46671. }
  46672. };
  46673. /**
  46674. * Gaussian blur post-processes. Horizontal and Vertical
  46675. */
  46676. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  46677. var _this = this;
  46678. var blurOffsetsW = new Array(9);
  46679. var blurOffsetsH = new Array(9);
  46680. var blurWeights = new Array(9);
  46681. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  46682. // Utils for gaussian blur
  46683. var calculateBlurOffsets = function (height) {
  46684. var lastOutputDimensions = {
  46685. width: scene.getEngine().getRenderWidth(),
  46686. height: scene.getEngine().getRenderHeight()
  46687. };
  46688. for (var i = 0; i < 9; i++) {
  46689. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  46690. if (height) {
  46691. blurOffsetsH[i] = value;
  46692. }
  46693. else {
  46694. blurOffsetsW[i] = value;
  46695. }
  46696. }
  46697. };
  46698. var calculateWeights = function () {
  46699. var x = 0.0;
  46700. for (var i = 0; i < 9; i++) {
  46701. x = (i - 4.0) / 4.0;
  46702. 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));
  46703. }
  46704. };
  46705. // Callback
  46706. var gaussianBlurCallback = function (height) {
  46707. return function (effect) {
  46708. if (_this._needUpdate) {
  46709. calculateWeights();
  46710. calculateBlurOffsets(height);
  46711. }
  46712. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  46713. effect.setArray("blurWeights", blurWeights);
  46714. effect.setFloat("multiplier", _this.gaussMultiplier);
  46715. };
  46716. };
  46717. // Create horizontal gaussian blur post-processes
  46718. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  46719. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  46720. // Create vertical gaussian blur post-process
  46721. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  46722. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  46723. };
  46724. return HDRRenderingPipeline;
  46725. }(BABYLON.PostProcessRenderPipeline));
  46726. // Luminance generator
  46727. HDRRenderingPipeline.LUM_STEPS = 6;
  46728. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  46729. })(BABYLON || (BABYLON = {}));
  46730. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  46731. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  46732. var BABYLON;
  46733. (function (BABYLON) {
  46734. var StandardRenderingPipeline = (function (_super) {
  46735. __extends(StandardRenderingPipeline, _super);
  46736. /**
  46737. * @constructor
  46738. * @param {string} name - The rendering pipeline name
  46739. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46740. * @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)
  46741. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  46742. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46743. */
  46744. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  46745. if (originalPostProcess === void 0) { originalPostProcess = null; }
  46746. var _this = _super.call(this, scene.getEngine(), name) || this;
  46747. _this.downSampleX4PostProcess = null;
  46748. _this.brightPassPostProcess = null;
  46749. _this.gaussianBlurHPostProcesses = [];
  46750. _this.gaussianBlurVPostProcesses = [];
  46751. _this.textureAdderPostProcess = null;
  46752. _this.textureAdderFinalPostProcess = null;
  46753. _this.lensFlareFinalPostProcess = null;
  46754. _this.lensFlarePostProcess = null;
  46755. _this.lensFlareComposePostProcess = null;
  46756. _this.depthOfFieldPostProcess = null;
  46757. // Values
  46758. _this.brightThreshold = 1.0;
  46759. _this.blurWidth = 2.0;
  46760. _this.horizontalBlur = false;
  46761. _this.gaussianCoefficient = 0.25;
  46762. _this.gaussianMean = 1.0;
  46763. _this.gaussianStandardDeviation = 1.0;
  46764. _this.exposure = 1.0;
  46765. _this.lensTexture = null;
  46766. _this.lensColorTexture = null;
  46767. _this.lensFlareStrength = 20.0;
  46768. _this.lensFlareGhostDispersal = 1.4;
  46769. _this.lensFlareHaloWidth = 0.7;
  46770. _this.lensFlareDistortionStrength = 16.0;
  46771. _this.lensStarTexture = null;
  46772. _this.lensFlareDirtTexture = null;
  46773. _this.depthOfFieldDistance = 10.0;
  46774. _this.depthOfFieldBlurWidth = 2.0;
  46775. // IAnimatable
  46776. _this.animations = [];
  46777. _this._depthRenderer = null;
  46778. _this._currentDepthOfFieldSource = null;
  46779. // Getters and setters
  46780. _this._depthOfFieldEnabled = true;
  46781. _this._lensFlareEnabled = true;
  46782. _this._cameras = cameras || [];
  46783. // Initialize
  46784. _this._scene = scene;
  46785. // Create pass post-processe
  46786. if (!originalPostProcess) {
  46787. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  46788. }
  46789. else {
  46790. _this.originalPostProcess = originalPostProcess;
  46791. }
  46792. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  46793. // Create down sample X4 post-process
  46794. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  46795. // Create bright pass post-process
  46796. _this._createBrightPassPostProcess(scene, ratio / 2);
  46797. // Create gaussian blur post-processes (down sampling blurs)
  46798. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  46799. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  46800. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  46801. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  46802. // Create texture adder post-process
  46803. _this._createTextureAdderPostProcess(scene, ratio);
  46804. // Create depth-of-field source post-process
  46805. _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);
  46806. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  46807. // Create lens flare post-process
  46808. _this._createLensFlarePostProcess(scene, ratio);
  46809. // Create depth-of-field source post-process post lens-flare and disable it now
  46810. _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);
  46811. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  46812. // Create gaussian blur used by depth-of-field
  46813. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  46814. // Create depth-of-field post-process
  46815. _this._createDepthOfFieldPostProcess(scene, ratio);
  46816. // Finish
  46817. scene.postProcessRenderPipelineManager.addPipeline(_this);
  46818. if (cameras !== null) {
  46819. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46820. }
  46821. // Deactivate
  46822. _this.LensFlareEnabled = false;
  46823. _this.DepthOfFieldEnabled = false;
  46824. return _this;
  46825. }
  46826. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  46827. get: function () {
  46828. return this._depthOfFieldEnabled;
  46829. },
  46830. set: function (enabled) {
  46831. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  46832. if (enabled && !this._depthOfFieldEnabled) {
  46833. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  46834. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  46835. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  46836. this._depthRenderer = this._scene.enableDepthRenderer();
  46837. }
  46838. else if (!enabled && this._depthOfFieldEnabled) {
  46839. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  46840. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  46841. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  46842. }
  46843. this._depthOfFieldEnabled = enabled;
  46844. },
  46845. enumerable: true,
  46846. configurable: true
  46847. });
  46848. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  46849. get: function () {
  46850. return this._lensFlareEnabled;
  46851. },
  46852. set: function (enabled) {
  46853. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  46854. if (enabled && !this._lensFlareEnabled) {
  46855. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._cameras);
  46856. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._cameras);
  46857. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  46858. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  46859. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._cameras);
  46860. this._setDepthOfFieldSavePostProcess("HDRPostLensFlareDepthOfFieldSource");
  46861. }
  46862. else if (!enabled && this._lensFlareEnabled) {
  46863. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._cameras);
  46864. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._cameras);
  46865. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  46866. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  46867. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._cameras);
  46868. this._setDepthOfFieldSavePostProcess("HDRBaseDepthOfFieldSource");
  46869. }
  46870. this._lensFlareEnabled = enabled;
  46871. },
  46872. enumerable: true,
  46873. configurable: true
  46874. });
  46875. // Sets depth-of-field save post-process
  46876. StandardRenderingPipeline.prototype._setDepthOfFieldSavePostProcess = function (name) {
  46877. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._cameras);
  46878. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, name, this._cameras);
  46879. switch (name) {
  46880. case "HDRBaseDepthOfFieldSource":
  46881. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  46882. break;
  46883. case "HDRPostLensFlareDepthOfFieldSource":
  46884. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  46885. break;
  46886. default: break;
  46887. }
  46888. };
  46889. // Down Sample X4 Post-Processs
  46890. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  46891. var _this = this;
  46892. var downSampleX4Offsets = new Array(32);
  46893. 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);
  46894. this.downSampleX4PostProcess.onApply = function (effect) {
  46895. var id = 0;
  46896. for (var i = -2; i < 2; i++) {
  46897. for (var j = -2; j < 2; j++) {
  46898. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  46899. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  46900. id += 2;
  46901. }
  46902. }
  46903. effect.setArray2("dsOffsets", downSampleX4Offsets);
  46904. };
  46905. // Add to pipeline
  46906. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  46907. };
  46908. // Brightpass Post-Process
  46909. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  46910. var _this = this;
  46911. var brightOffsets = new Array(8);
  46912. 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);
  46913. this.brightPassPostProcess.onApply = function (effect) {
  46914. var sU = (1.0 / _this.brightPassPostProcess.width);
  46915. var sV = (1.0 / _this.brightPassPostProcess.height);
  46916. brightOffsets[0] = -0.5 * sU;
  46917. brightOffsets[1] = 0.5 * sV;
  46918. brightOffsets[2] = 0.5 * sU;
  46919. brightOffsets[3] = 0.5 * sV;
  46920. brightOffsets[4] = -0.5 * sU;
  46921. brightOffsets[5] = -0.5 * sV;
  46922. brightOffsets[6] = 0.5 * sU;
  46923. brightOffsets[7] = -0.5 * sV;
  46924. effect.setArray2("dsOffsets", brightOffsets);
  46925. effect.setFloat("brightThreshold", _this.brightThreshold);
  46926. };
  46927. // Add to pipeline
  46928. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  46929. };
  46930. // Create gaussian blur H&V post-processes
  46931. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  46932. var _this = this;
  46933. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  46934. var blurOffsets = new Array(9);
  46935. var blurWeights = new Array(9);
  46936. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  46937. var callback = function (height) {
  46938. return function (effect) {
  46939. // Weights
  46940. var x = 0.0;
  46941. for (var i = 0; i < 9; i++) {
  46942. x = (i - 4.0) / 4.0;
  46943. blurWeights[i] =
  46944. _this.gaussianCoefficient
  46945. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  46946. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  46947. }
  46948. var lastOutputDimensions = {
  46949. width: scene.getEngine().getRenderWidth(),
  46950. height: scene.getEngine().getRenderHeight()
  46951. };
  46952. for (var i = 0; i < 9; i++) {
  46953. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  46954. blurOffsets[i] = value;
  46955. }
  46956. effect.setArray("blurOffsets", blurOffsets);
  46957. effect.setArray("blurWeights", blurWeights);
  46958. if (height) {
  46959. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  46960. }
  46961. else {
  46962. effect.setFloat("blurWidth", _this[blurWidthKey]);
  46963. }
  46964. };
  46965. };
  46966. // Create horizontal gaussian blur post-processes
  46967. 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);
  46968. gaussianBlurHPostProcess.onApply = callback(false);
  46969. // Create vertical gaussian blur post-process
  46970. 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);
  46971. gaussianBlurVPostProcess.onApply = callback(true);
  46972. // Add to pipeline
  46973. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  46974. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  46975. // Finish
  46976. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  46977. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  46978. };
  46979. // Create texture adder post-process
  46980. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  46981. var _this = this;
  46982. 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);
  46983. this.textureAdderPostProcess.onApply = function (effect) {
  46984. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  46985. effect.setTexture("lensSampler", _this.lensTexture);
  46986. effect.setFloat("exposure", _this.exposure);
  46987. };
  46988. // Add to pipeline
  46989. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  46990. };
  46991. // Create lens flare post-process
  46992. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  46993. var _this = this;
  46994. 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);
  46995. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  46996. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  46997. 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);
  46998. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  46999. var resolution = new BABYLON.Vector2(0, 0);
  47000. // Lens flare
  47001. this.lensFlarePostProcess.onApply = function (effect) {
  47002. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  47003. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  47004. effect.setFloat("strength", _this.lensFlareStrength);
  47005. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  47006. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  47007. // Shift
  47008. resolution.x = _this.lensFlarePostProcess.width;
  47009. resolution.y = _this.lensFlarePostProcess.height;
  47010. effect.setVector2("resolution", resolution);
  47011. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  47012. };
  47013. // Compose
  47014. 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);
  47015. 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);
  47016. this.lensFlareComposePostProcess.onApply = function (effect) {
  47017. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  47018. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  47019. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  47020. // Lens start rotation matrix
  47021. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  47022. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  47023. 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));
  47024. camRot *= 4.0;
  47025. 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);
  47026. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  47027. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  47028. };
  47029. };
  47030. // Create depth-of-field post-process
  47031. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  47032. var _this = this;
  47033. 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);
  47034. this.depthOfFieldPostProcess.onApply = function (effect) {
  47035. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  47036. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  47037. effect.setFloat("distance", _this.depthOfFieldDistance);
  47038. };
  47039. // Add to pipeline
  47040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  47041. };
  47042. // Dispose
  47043. StandardRenderingPipeline.prototype.dispose = function () {
  47044. for (var i = 0; i < this._cameras.length; i++) {
  47045. var camera = this._cameras[i];
  47046. this.originalPostProcess.dispose(camera);
  47047. this.downSampleX4PostProcess.dispose(camera);
  47048. this.brightPassPostProcess.dispose(camera);
  47049. this.textureAdderPostProcess.dispose(camera);
  47050. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  47051. this.gaussianBlurHPostProcesses[j].dispose(camera);
  47052. }
  47053. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  47054. this.gaussianBlurVPostProcesses[j].dispose(camera);
  47055. }
  47056. this.textureAdderFinalPostProcess.dispose(camera);
  47057. this.lensFlarePostProcess.dispose(camera);
  47058. this.lensFlareComposePostProcess.dispose(camera);
  47059. this.depthOfFieldPostProcess.dispose(camera);
  47060. }
  47061. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  47062. _super.prototype.dispose.call(this);
  47063. };
  47064. // Serialize rendering pipeline
  47065. StandardRenderingPipeline.prototype.serialize = function () {
  47066. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47067. serializationObject.customType = "StandardRenderingPipeline";
  47068. return serializationObject;
  47069. };
  47070. // Parse serialized pipeline
  47071. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  47072. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  47073. };
  47074. return StandardRenderingPipeline;
  47075. }(BABYLON.PostProcessRenderPipeline));
  47076. __decorate([
  47077. BABYLON.serialize()
  47078. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  47079. __decorate([
  47080. BABYLON.serialize()
  47081. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  47082. __decorate([
  47083. BABYLON.serialize()
  47084. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  47085. __decorate([
  47086. BABYLON.serialize()
  47087. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  47088. __decorate([
  47089. BABYLON.serialize()
  47090. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  47091. __decorate([
  47092. BABYLON.serialize()
  47093. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  47094. __decorate([
  47095. BABYLON.serialize()
  47096. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  47097. __decorate([
  47098. BABYLON.serializeAsTexture("lensTexture")
  47099. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  47100. __decorate([
  47101. BABYLON.serializeAsTexture("lensColorTexture")
  47102. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  47103. __decorate([
  47104. BABYLON.serialize()
  47105. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  47106. __decorate([
  47107. BABYLON.serialize()
  47108. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  47109. __decorate([
  47110. BABYLON.serialize()
  47111. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  47112. __decorate([
  47113. BABYLON.serialize()
  47114. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  47115. __decorate([
  47116. BABYLON.serializeAsTexture("lensStarTexture")
  47117. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  47118. __decorate([
  47119. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  47120. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  47121. __decorate([
  47122. BABYLON.serialize()
  47123. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  47124. __decorate([
  47125. BABYLON.serialize()
  47126. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  47127. __decorate([
  47128. BABYLON.serialize()
  47129. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  47130. __decorate([
  47131. BABYLON.serialize()
  47132. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  47133. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  47134. })(BABYLON || (BABYLON = {}));
  47135. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  47136. var BABYLON;
  47137. (function (BABYLON) {
  47138. var AnaglyphPostProcess = (function (_super) {
  47139. __extends(AnaglyphPostProcess, _super);
  47140. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  47141. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  47142. _this._passedProcess = rigCameras[0]._rigPostProcess;
  47143. _this.onApplyObservable.add(function (effect) {
  47144. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  47145. });
  47146. return _this;
  47147. }
  47148. return AnaglyphPostProcess;
  47149. }(BABYLON.PostProcess));
  47150. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  47151. })(BABYLON || (BABYLON = {}));
  47152. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  47153. var BABYLON;
  47154. (function (BABYLON) {
  47155. var BlurPostProcess = (function (_super) {
  47156. __extends(BlurPostProcess, _super);
  47157. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  47158. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47159. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  47160. _this.direction = direction;
  47161. _this.blurWidth = blurWidth;
  47162. _this.onApplyObservable.add(function (effect) {
  47163. effect.setFloat2("screenSize", _this.width, _this.height);
  47164. effect.setVector2("direction", _this.direction);
  47165. effect.setFloat("blurWidth", _this.blurWidth);
  47166. });
  47167. return _this;
  47168. }
  47169. return BlurPostProcess;
  47170. }(BABYLON.PostProcess));
  47171. BABYLON.BlurPostProcess = BlurPostProcess;
  47172. })(BABYLON || (BABYLON = {}));
  47173. //# sourceMappingURL=babylon.blurPostProcess.js.map
  47174. var BABYLON;
  47175. (function (BABYLON) {
  47176. var RefractionPostProcess = (function (_super) {
  47177. __extends(RefractionPostProcess, _super);
  47178. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  47179. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  47180. _this.color = color;
  47181. _this.depth = depth;
  47182. _this.colorLevel = colorLevel;
  47183. _this.onActivateObservable.add(function (cam) {
  47184. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  47185. });
  47186. _this.onApplyObservable.add(function (effect) {
  47187. effect.setColor3("baseColor", _this.color);
  47188. effect.setFloat("depth", _this.depth);
  47189. effect.setFloat("colorLevel", _this.colorLevel);
  47190. effect.setTexture("refractionSampler", _this._refRexture);
  47191. });
  47192. return _this;
  47193. }
  47194. // Methods
  47195. RefractionPostProcess.prototype.dispose = function (camera) {
  47196. if (this._refRexture) {
  47197. this._refRexture.dispose();
  47198. }
  47199. _super.prototype.dispose.call(this, camera);
  47200. };
  47201. return RefractionPostProcess;
  47202. }(BABYLON.PostProcess));
  47203. BABYLON.RefractionPostProcess = RefractionPostProcess;
  47204. })(BABYLON || (BABYLON = {}));
  47205. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  47206. var BABYLON;
  47207. (function (BABYLON) {
  47208. var BlackAndWhitePostProcess = (function (_super) {
  47209. __extends(BlackAndWhitePostProcess, _super);
  47210. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  47211. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  47212. }
  47213. return BlackAndWhitePostProcess;
  47214. }(BABYLON.PostProcess));
  47215. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  47216. })(BABYLON || (BABYLON = {}));
  47217. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  47218. var BABYLON;
  47219. (function (BABYLON) {
  47220. var ConvolutionPostProcess = (function (_super) {
  47221. __extends(ConvolutionPostProcess, _super);
  47222. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  47223. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  47224. _this.kernel = kernel;
  47225. _this.onApply = function (effect) {
  47226. effect.setFloat2("screenSize", _this.width, _this.height);
  47227. effect.setArray("kernel", _this.kernel);
  47228. };
  47229. return _this;
  47230. }
  47231. return ConvolutionPostProcess;
  47232. }(BABYLON.PostProcess));
  47233. // Statics
  47234. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  47235. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  47236. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  47237. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  47238. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  47239. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  47240. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  47241. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  47242. })(BABYLON || (BABYLON = {}));
  47243. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  47244. var BABYLON;
  47245. (function (BABYLON) {
  47246. var FilterPostProcess = (function (_super) {
  47247. __extends(FilterPostProcess, _super);
  47248. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  47249. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  47250. _this.kernelMatrix = kernelMatrix;
  47251. _this.onApply = function (effect) {
  47252. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  47253. };
  47254. return _this;
  47255. }
  47256. return FilterPostProcess;
  47257. }(BABYLON.PostProcess));
  47258. BABYLON.FilterPostProcess = FilterPostProcess;
  47259. })(BABYLON || (BABYLON = {}));
  47260. //# sourceMappingURL=babylon.filterPostProcess.js.map
  47261. var BABYLON;
  47262. (function (BABYLON) {
  47263. var FxaaPostProcess = (function (_super) {
  47264. __extends(FxaaPostProcess, _super);
  47265. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  47266. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  47267. _this.onSizeChangedObservable.add(function () {
  47268. _this.texelWidth = 1.0 / _this.width;
  47269. _this.texelHeight = 1.0 / _this.height;
  47270. });
  47271. _this.onApplyObservable.add(function (effect) {
  47272. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  47273. });
  47274. return _this;
  47275. }
  47276. return FxaaPostProcess;
  47277. }(BABYLON.PostProcess));
  47278. BABYLON.FxaaPostProcess = FxaaPostProcess;
  47279. })(BABYLON || (BABYLON = {}));
  47280. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  47281. var BABYLON;
  47282. (function (BABYLON) {
  47283. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  47284. var VolumetricLightScatteringPostProcess = (function (_super) {
  47285. __extends(VolumetricLightScatteringPostProcess, _super);
  47286. /**
  47287. * @constructor
  47288. * @param {string} name - The post-process name
  47289. * @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)
  47290. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  47291. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  47292. * @param {number} samples - The post-process quality, default 100
  47293. * @param {number} samplingMode - The post-process filtering mode
  47294. * @param {BABYLON.Engine} engine - The babylon engine
  47295. * @param {boolean} reusable - If the post-process is reusable
  47296. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  47297. */
  47298. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  47299. if (samples === void 0) { samples = 100; }
  47300. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47301. 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;
  47302. _this._screenCoordinates = BABYLON.Vector2.Zero();
  47303. /**
  47304. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  47305. * @type {Vector3}
  47306. */
  47307. _this.customMeshPosition = BABYLON.Vector3.Zero();
  47308. /**
  47309. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  47310. * @type {boolean}
  47311. */
  47312. _this.useCustomMeshPosition = false;
  47313. /**
  47314. * If the post-process should inverse the light scattering direction
  47315. * @type {boolean}
  47316. */
  47317. _this.invert = true;
  47318. /**
  47319. * Array containing the excluded meshes not rendered in the internal pass
  47320. */
  47321. _this.excludedMeshes = new Array();
  47322. /**
  47323. * Controls the overall intensity of the post-process
  47324. * @type {number}
  47325. */
  47326. _this.exposure = 0.3;
  47327. /**
  47328. * Dissipates each sample's contribution in range [0, 1]
  47329. * @type {number}
  47330. */
  47331. _this.decay = 0.96815;
  47332. /**
  47333. * Controls the overall intensity of each sample
  47334. * @type {number}
  47335. */
  47336. _this.weight = 0.58767;
  47337. /**
  47338. * Controls the density of each sample
  47339. * @type {number}
  47340. */
  47341. _this.density = 0.926;
  47342. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  47343. var engine = scene.getEngine();
  47344. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47345. // Configure mesh
  47346. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  47347. // Configure
  47348. _this._createPass(scene, ratio.passRatio || ratio);
  47349. _this.onActivate = function (camera) {
  47350. if (!_this.isSupported) {
  47351. _this.dispose(camera);
  47352. }
  47353. _this.onActivate = null;
  47354. };
  47355. _this.onApplyObservable.add(function (effect) {
  47356. _this._updateMeshScreenCoordinates(scene);
  47357. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  47358. effect.setFloat("exposure", _this.exposure);
  47359. effect.setFloat("decay", _this.decay);
  47360. effect.setFloat("weight", _this.weight);
  47361. effect.setFloat("density", _this.density);
  47362. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  47363. });
  47364. return _this;
  47365. }
  47366. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  47367. get: function () {
  47368. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47369. return false;
  47370. },
  47371. set: function (useDiffuseColor) {
  47372. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47373. },
  47374. enumerable: true,
  47375. configurable: true
  47376. });
  47377. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  47378. var mesh = subMesh.getMesh();
  47379. // Render this.mesh as default
  47380. if (mesh === this.mesh) {
  47381. return mesh.material.isReady(mesh);
  47382. }
  47383. var defines = [];
  47384. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47385. var material = subMesh.getMaterial();
  47386. var needUV = false;
  47387. // Alpha test
  47388. if (material) {
  47389. if (material.needAlphaTesting()) {
  47390. defines.push("#define ALPHATEST");
  47391. }
  47392. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47393. attribs.push(BABYLON.VertexBuffer.UVKind);
  47394. defines.push("#define UV1");
  47395. }
  47396. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47397. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47398. defines.push("#define UV2");
  47399. }
  47400. }
  47401. // Bones
  47402. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47403. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47404. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47405. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47406. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47407. }
  47408. else {
  47409. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47410. }
  47411. // Instances
  47412. if (useInstances) {
  47413. defines.push("#define INSTANCES");
  47414. attribs.push("world0");
  47415. attribs.push("world1");
  47416. attribs.push("world2");
  47417. attribs.push("world3");
  47418. }
  47419. // Get correct effect
  47420. var join = defines.join("\n");
  47421. if (this._cachedDefines !== join) {
  47422. this._cachedDefines = join;
  47423. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  47424. }
  47425. return this._volumetricLightScatteringPass.isReady();
  47426. };
  47427. /**
  47428. * Sets the new light position for light scattering effect
  47429. * @param {BABYLON.Vector3} The new custom light position
  47430. */
  47431. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  47432. this.customMeshPosition = position;
  47433. };
  47434. /**
  47435. * Returns the light position for light scattering effect
  47436. * @return {BABYLON.Vector3} The custom light position
  47437. */
  47438. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  47439. return this.customMeshPosition;
  47440. };
  47441. /**
  47442. * Disposes the internal assets and detaches the post-process from the camera
  47443. */
  47444. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  47445. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  47446. if (rttIndex !== -1) {
  47447. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  47448. }
  47449. this._volumetricLightScatteringRTT.dispose();
  47450. _super.prototype.dispose.call(this, camera);
  47451. };
  47452. /**
  47453. * Returns the render target texture used by the post-process
  47454. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  47455. */
  47456. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  47457. return this._volumetricLightScatteringRTT;
  47458. };
  47459. // Private methods
  47460. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  47461. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  47462. return true;
  47463. }
  47464. return false;
  47465. };
  47466. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  47467. var _this = this;
  47468. var engine = scene.getEngine();
  47469. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47470. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47471. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47472. this._volumetricLightScatteringRTT.renderList = null;
  47473. this._volumetricLightScatteringRTT.renderParticles = false;
  47474. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  47475. // Custom render function for submeshes
  47476. var renderSubMesh = function (subMesh) {
  47477. var mesh = subMesh.getRenderingMesh();
  47478. if (_this._meshExcluded(mesh)) {
  47479. return;
  47480. }
  47481. var scene = mesh.getScene();
  47482. var engine = scene.getEngine();
  47483. // Culling
  47484. engine.setState(subMesh.getMaterial().backFaceCulling);
  47485. // Managing instances
  47486. var batch = mesh._getInstancesRenderList(subMesh._id);
  47487. if (batch.mustReturn) {
  47488. return;
  47489. }
  47490. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47491. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47492. var effect = _this._volumetricLightScatteringPass;
  47493. if (mesh === _this.mesh) {
  47494. if (subMesh.effect) {
  47495. effect = subMesh.effect;
  47496. }
  47497. else {
  47498. effect = subMesh.getMaterial().getEffect();
  47499. }
  47500. }
  47501. engine.enableEffect(effect);
  47502. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  47503. if (mesh === _this.mesh) {
  47504. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  47505. }
  47506. else {
  47507. var material = subMesh.getMaterial();
  47508. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  47509. // Alpha test
  47510. if (material && material.needAlphaTesting()) {
  47511. var alphaTexture = material.getAlphaTestTexture();
  47512. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  47513. if (alphaTexture) {
  47514. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47515. }
  47516. }
  47517. // Bones
  47518. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47519. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47520. }
  47521. }
  47522. // Draw
  47523. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  47524. }
  47525. };
  47526. // Render target texture callbacks
  47527. var savedSceneClearColor;
  47528. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  47529. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  47530. savedSceneClearColor = scene.clearColor;
  47531. scene.clearColor = sceneClearColor;
  47532. });
  47533. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  47534. scene.clearColor = savedSceneClearColor;
  47535. });
  47536. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47537. var engine = scene.getEngine();
  47538. var index;
  47539. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47540. renderSubMesh(opaqueSubMeshes.data[index]);
  47541. }
  47542. engine.setAlphaTesting(true);
  47543. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47544. renderSubMesh(alphaTestSubMeshes.data[index]);
  47545. }
  47546. engine.setAlphaTesting(false);
  47547. if (transparentSubMeshes.length) {
  47548. // Sort sub meshes
  47549. for (index = 0; index < transparentSubMeshes.length; index++) {
  47550. var submesh = transparentSubMeshes.data[index];
  47551. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  47552. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  47553. }
  47554. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  47555. sortedArray.sort(function (a, b) {
  47556. // Alpha index first
  47557. if (a._alphaIndex > b._alphaIndex) {
  47558. return 1;
  47559. }
  47560. if (a._alphaIndex < b._alphaIndex) {
  47561. return -1;
  47562. }
  47563. // Then distance to camera
  47564. if (a._distanceToCamera < b._distanceToCamera) {
  47565. return 1;
  47566. }
  47567. if (a._distanceToCamera > b._distanceToCamera) {
  47568. return -1;
  47569. }
  47570. return 0;
  47571. });
  47572. // Render sub meshes
  47573. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47574. for (index = 0; index < sortedArray.length; index++) {
  47575. renderSubMesh(sortedArray[index]);
  47576. }
  47577. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47578. }
  47579. };
  47580. };
  47581. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  47582. var transform = scene.getTransformMatrix();
  47583. var meshPosition;
  47584. if (this.useCustomMeshPosition) {
  47585. meshPosition = this.customMeshPosition;
  47586. }
  47587. else if (this.attachedNode) {
  47588. meshPosition = this.attachedNode.position;
  47589. }
  47590. else {
  47591. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  47592. }
  47593. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  47594. this._screenCoordinates.x = pos.x / this._viewPort.width;
  47595. this._screenCoordinates.y = pos.y / this._viewPort.height;
  47596. if (this.invert)
  47597. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  47598. };
  47599. // Static methods
  47600. /**
  47601. * Creates a default mesh for the Volumeric Light Scattering post-process
  47602. * @param {string} The mesh name
  47603. * @param {BABYLON.Scene} The scene where to create the mesh
  47604. * @return {BABYLON.Mesh} the default mesh
  47605. */
  47606. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  47607. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  47608. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  47609. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  47610. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  47611. mesh.material = material;
  47612. return mesh;
  47613. };
  47614. return VolumetricLightScatteringPostProcess;
  47615. }(BABYLON.PostProcess));
  47616. __decorate([
  47617. BABYLON.serializeAsVector3()
  47618. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  47619. __decorate([
  47620. BABYLON.serialize()
  47621. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  47622. __decorate([
  47623. BABYLON.serialize()
  47624. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  47625. __decorate([
  47626. BABYLON.serializeAsMeshReference()
  47627. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  47628. __decorate([
  47629. BABYLON.serialize()
  47630. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  47631. __decorate([
  47632. BABYLON.serialize()
  47633. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  47634. __decorate([
  47635. BABYLON.serialize()
  47636. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  47637. __decorate([
  47638. BABYLON.serialize()
  47639. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  47640. __decorate([
  47641. BABYLON.serialize()
  47642. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  47643. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  47644. })(BABYLON || (BABYLON = {}));
  47645. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  47646. var BABYLON;
  47647. (function (BABYLON) {
  47648. var StereoscopicInterlacePostProcess = (function (_super) {
  47649. __extends(StereoscopicInterlacePostProcess, _super);
  47650. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  47651. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  47652. _this._passedProcess = rigCameras[0]._rigPostProcess;
  47653. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  47654. _this.onSizeChangedObservable.add(function () {
  47655. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  47656. });
  47657. _this.onApplyObservable.add(function (effect) {
  47658. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  47659. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  47660. });
  47661. return _this;
  47662. }
  47663. return StereoscopicInterlacePostProcess;
  47664. }(BABYLON.PostProcess));
  47665. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  47666. })(BABYLON || (BABYLON = {}));
  47667. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  47668. //
  47669. // This post-process allows the modification of rendered colors by using
  47670. // a 'look-up table' (LUT). This effect is also called Color Grading.
  47671. //
  47672. // The object needs to be provided an url to a texture containing the color
  47673. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  47674. // Use an image editing software to tweak the LUT to match your needs.
  47675. //
  47676. // For an example of a color LUT, see here:
  47677. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  47678. // For explanations on color grading, see here:
  47679. // http://udn.epicgames.com/Three/ColorGrading.html
  47680. //
  47681. var BABYLON;
  47682. (function (BABYLON) {
  47683. var ColorCorrectionPostProcess = (function (_super) {
  47684. __extends(ColorCorrectionPostProcess, _super);
  47685. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  47686. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  47687. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47688. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  47689. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47690. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47691. _this.onApply = function (effect) {
  47692. effect.setTexture("colorTable", _this._colorTableTexture);
  47693. };
  47694. return _this;
  47695. }
  47696. return ColorCorrectionPostProcess;
  47697. }(BABYLON.PostProcess));
  47698. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  47699. })(BABYLON || (BABYLON = {}));
  47700. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  47701. var BABYLON;
  47702. (function (BABYLON) {
  47703. var TonemappingOperator;
  47704. (function (TonemappingOperator) {
  47705. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  47706. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  47707. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  47708. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  47709. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  47710. ;
  47711. var TonemapPostProcess = (function (_super) {
  47712. __extends(TonemapPostProcess, _super);
  47713. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  47714. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47715. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47716. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  47717. _this._operator = _operator;
  47718. _this.exposureAdjustment = exposureAdjustment;
  47719. var defines = "#define ";
  47720. if (_this._operator === TonemappingOperator.Hable)
  47721. defines += "HABLE_TONEMAPPING";
  47722. else if (_this._operator === TonemappingOperator.Reinhard)
  47723. defines += "REINHARD_TONEMAPPING";
  47724. else if (_this._operator === TonemappingOperator.HejiDawson)
  47725. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  47726. else if (_this._operator === TonemappingOperator.Photographic)
  47727. defines += "PHOTOGRAPHIC_TONEMAPPING";
  47728. //sadly a second call to create the effect.
  47729. _this.updateEffect(defines);
  47730. _this.onApply = function (effect) {
  47731. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  47732. };
  47733. return _this;
  47734. }
  47735. return TonemapPostProcess;
  47736. }(BABYLON.PostProcess));
  47737. BABYLON.TonemapPostProcess = TonemapPostProcess;
  47738. })(BABYLON || (BABYLON = {}));
  47739. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  47740. var BABYLON;
  47741. (function (BABYLON) {
  47742. var DisplayPassPostProcess = (function (_super) {
  47743. __extends(DisplayPassPostProcess, _super);
  47744. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  47745. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  47746. }
  47747. return DisplayPassPostProcess;
  47748. }(BABYLON.PostProcess));
  47749. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  47750. })(BABYLON || (BABYLON = {}));
  47751. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  47752. /// <reference path="..\babylon.node.ts" />
  47753. var BABYLON;
  47754. (function (BABYLON) {
  47755. var Bone = (function (_super) {
  47756. __extends(Bone, _super);
  47757. function Bone(name, skeleton, parentBone, matrix, restPose) {
  47758. var _this = _super.call(this, name, skeleton.getScene()) || this;
  47759. _this.name = name;
  47760. _this.children = new Array();
  47761. _this.animations = new Array();
  47762. _this._worldTransform = new BABYLON.Matrix();
  47763. _this._absoluteTransform = new BABYLON.Matrix();
  47764. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  47765. _this._scaleMatrix = BABYLON.Matrix.Identity();
  47766. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  47767. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  47768. _this._scalingDeterminant = 1;
  47769. _this._skeleton = skeleton;
  47770. _this._localMatrix = matrix;
  47771. _this._baseMatrix = matrix.clone();
  47772. _this._restPose = restPose ? restPose : matrix.clone();
  47773. skeleton.bones.push(_this);
  47774. if (parentBone) {
  47775. _this._parent = parentBone;
  47776. parentBone.children.push(_this);
  47777. }
  47778. else {
  47779. _this._parent = null;
  47780. }
  47781. _this._updateDifferenceMatrix();
  47782. if (_this.getAbsoluteTransform().determinant() < 0) {
  47783. _this._scalingDeterminant *= -1;
  47784. }
  47785. return _this;
  47786. }
  47787. Object.defineProperty(Bone.prototype, "_matrix", {
  47788. get: function () {
  47789. return this._localMatrix;
  47790. },
  47791. set: function (val) {
  47792. if (this._localMatrix) {
  47793. this._localMatrix.copyFrom(val);
  47794. }
  47795. else {
  47796. this._localMatrix = val;
  47797. }
  47798. },
  47799. enumerable: true,
  47800. configurable: true
  47801. });
  47802. // Members
  47803. Bone.prototype.getParent = function () {
  47804. return this._parent;
  47805. };
  47806. Bone.prototype.getLocalMatrix = function () {
  47807. return this._localMatrix;
  47808. };
  47809. Bone.prototype.getBaseMatrix = function () {
  47810. return this._baseMatrix;
  47811. };
  47812. Bone.prototype.getRestPose = function () {
  47813. return this._restPose;
  47814. };
  47815. Bone.prototype.returnToRest = function () {
  47816. this.updateMatrix(this._restPose.clone());
  47817. };
  47818. Bone.prototype.getWorldMatrix = function () {
  47819. return this._worldTransform;
  47820. };
  47821. Bone.prototype.getInvertedAbsoluteTransform = function () {
  47822. return this._invertedAbsoluteTransform;
  47823. };
  47824. Bone.prototype.getAbsoluteTransform = function () {
  47825. return this._absoluteTransform;
  47826. };
  47827. // Methods
  47828. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  47829. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  47830. this._baseMatrix = matrix.clone();
  47831. this._localMatrix = matrix.clone();
  47832. this._skeleton._markAsDirty();
  47833. if (updateDifferenceMatrix) {
  47834. this._updateDifferenceMatrix();
  47835. }
  47836. };
  47837. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  47838. if (!rootMatrix) {
  47839. rootMatrix = this._baseMatrix;
  47840. }
  47841. if (this._parent) {
  47842. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  47843. }
  47844. else {
  47845. this._absoluteTransform.copyFrom(rootMatrix);
  47846. }
  47847. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  47848. for (var index = 0; index < this.children.length; index++) {
  47849. this.children[index]._updateDifferenceMatrix();
  47850. }
  47851. };
  47852. Bone.prototype.markAsDirty = function () {
  47853. this._currentRenderId++;
  47854. this._skeleton._markAsDirty();
  47855. };
  47856. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  47857. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  47858. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  47859. // all animation may be coming from a library skeleton, so may need to create animation
  47860. if (this.animations.length === 0) {
  47861. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  47862. this.animations[0].setKeys([]);
  47863. }
  47864. // get animation info / verify there is such a range from the source bone
  47865. var sourceRange = source.animations[0].getRange(rangeName);
  47866. if (!sourceRange) {
  47867. return false;
  47868. }
  47869. var from = sourceRange.from;
  47870. var to = sourceRange.to;
  47871. var sourceKeys = source.animations[0].getKeys();
  47872. // rescaling prep
  47873. var sourceBoneLength = source.length;
  47874. var sourceParent = source.getParent();
  47875. var parent = this.getParent();
  47876. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  47877. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  47878. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  47879. var destKeys = this.animations[0].getKeys();
  47880. // loop vars declaration
  47881. var orig;
  47882. var origTranslation;
  47883. var mat;
  47884. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  47885. orig = sourceKeys[key];
  47886. if (orig.frame >= from && orig.frame <= to) {
  47887. if (rescaleAsRequired) {
  47888. mat = orig.value.clone();
  47889. // scale based on parent ratio, when bone has parent
  47890. if (parentScalingReqd) {
  47891. origTranslation = mat.getTranslation();
  47892. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  47893. // scale based on skeleton dimension ratio when root bone, and value is passed
  47894. }
  47895. else if (dimensionsScalingReqd) {
  47896. origTranslation = mat.getTranslation();
  47897. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  47898. // use original when root bone, and no data for skelDimensionsRatio
  47899. }
  47900. else {
  47901. mat = orig.value;
  47902. }
  47903. }
  47904. else {
  47905. mat = orig.value;
  47906. }
  47907. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  47908. }
  47909. }
  47910. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  47911. return true;
  47912. };
  47913. /**
  47914. * Translate the bone in local or world space.
  47915. * @param vec The amount to translate the bone.
  47916. * @param space The space that the translation is in.
  47917. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  47918. */
  47919. Bone.prototype.translate = function (vec, space, mesh) {
  47920. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  47921. var lm = this.getLocalMatrix();
  47922. if (space == BABYLON.Space.LOCAL) {
  47923. lm.m[12] += vec.x;
  47924. lm.m[13] += vec.y;
  47925. lm.m[14] += vec.z;
  47926. }
  47927. else {
  47928. var wm;
  47929. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  47930. if (mesh) {
  47931. wm = mesh.getWorldMatrix();
  47932. }
  47933. this._skeleton.computeAbsoluteTransforms();
  47934. var tmat = Bone._tmpMats[0];
  47935. var tvec = Bone._tmpVecs[0];
  47936. if (mesh) {
  47937. tmat.copyFrom(this._parent.getAbsoluteTransform());
  47938. tmat.multiplyToRef(wm, tmat);
  47939. }
  47940. else {
  47941. tmat.copyFrom(this._parent.getAbsoluteTransform());
  47942. }
  47943. tmat.m[12] = 0;
  47944. tmat.m[13] = 0;
  47945. tmat.m[14] = 0;
  47946. tmat.invert();
  47947. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  47948. lm.m[12] += tvec.x;
  47949. lm.m[13] += tvec.y;
  47950. lm.m[14] += tvec.z;
  47951. }
  47952. this.markAsDirty();
  47953. };
  47954. /**
  47955. * Set the postion of the bone in local or world space.
  47956. * @param position The position to set the bone.
  47957. * @param space The space that the position is in.
  47958. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  47959. */
  47960. Bone.prototype.setPosition = function (position, space, mesh) {
  47961. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  47962. var lm = this.getLocalMatrix();
  47963. if (space == BABYLON.Space.LOCAL) {
  47964. lm.m[12] = position.x;
  47965. lm.m[13] = position.y;
  47966. lm.m[14] = position.z;
  47967. }
  47968. else {
  47969. var wm;
  47970. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  47971. if (mesh) {
  47972. wm = mesh.getWorldMatrix();
  47973. }
  47974. this._skeleton.computeAbsoluteTransforms();
  47975. var tmat = Bone._tmpMats[0];
  47976. var vec = Bone._tmpVecs[0];
  47977. if (mesh) {
  47978. tmat.copyFrom(this._parent.getAbsoluteTransform());
  47979. tmat.multiplyToRef(wm, tmat);
  47980. }
  47981. else {
  47982. tmat.copyFrom(this._parent.getAbsoluteTransform());
  47983. }
  47984. tmat.invert();
  47985. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  47986. lm.m[12] = vec.x;
  47987. lm.m[13] = vec.y;
  47988. lm.m[14] = vec.z;
  47989. }
  47990. this.markAsDirty();
  47991. };
  47992. /**
  47993. * Set the absolute postion of the bone (world space).
  47994. * @param position The position to set the bone.
  47995. * @param mesh The mesh that this bone is attached to.
  47996. */
  47997. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  47998. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  47999. };
  48000. /**
  48001. * Set the scale of the bone on the x, y and z axes.
  48002. * @param x The scale of the bone on the x axis.
  48003. * @param x The scale of the bone on the y axis.
  48004. * @param z The scale of the bone on the z axis.
  48005. * @param scaleChildren Set this to true if children of the bone should be scaled.
  48006. */
  48007. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  48008. if (scaleChildren === void 0) { scaleChildren = false; }
  48009. if (this.animations[0] && !this.animations[0].isStopped()) {
  48010. if (!scaleChildren) {
  48011. this._negateScaleChildren.x = 1 / x;
  48012. this._negateScaleChildren.y = 1 / y;
  48013. this._negateScaleChildren.z = 1 / z;
  48014. }
  48015. this._syncScaleVector();
  48016. }
  48017. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  48018. };
  48019. /**
  48020. * Scale the bone on the x, y and z axes.
  48021. * @param x The amount to scale the bone on the x axis.
  48022. * @param x The amount to scale the bone on the y axis.
  48023. * @param z The amount to scale the bone on the z axis.
  48024. * @param scaleChildren Set this to true if children of the bone should be scaled.
  48025. */
  48026. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  48027. if (scaleChildren === void 0) { scaleChildren = false; }
  48028. var locMat = this.getLocalMatrix();
  48029. var origLocMat = Bone._tmpMats[0];
  48030. origLocMat.copyFrom(locMat);
  48031. var origLocMatInv = Bone._tmpMats[1];
  48032. origLocMatInv.copyFrom(origLocMat);
  48033. origLocMatInv.invert();
  48034. var scaleMat = Bone._tmpMats[2];
  48035. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  48036. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  48037. this._scaleVector.x *= x;
  48038. this._scaleVector.y *= y;
  48039. this._scaleVector.z *= z;
  48040. locMat.multiplyToRef(origLocMatInv, locMat);
  48041. locMat.multiplyToRef(scaleMat, locMat);
  48042. locMat.multiplyToRef(origLocMat, locMat);
  48043. var parent = this.getParent();
  48044. if (parent) {
  48045. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  48046. }
  48047. else {
  48048. this.getAbsoluteTransform().copyFrom(locMat);
  48049. }
  48050. var len = this.children.length;
  48051. scaleMat.invert();
  48052. for (var i = 0; i < len; i++) {
  48053. var child = this.children[i];
  48054. var cm = child.getLocalMatrix();
  48055. cm.multiplyToRef(scaleMat, cm);
  48056. var lm = child.getLocalMatrix();
  48057. lm.m[12] *= x;
  48058. lm.m[13] *= y;
  48059. lm.m[14] *= z;
  48060. }
  48061. this.computeAbsoluteTransforms();
  48062. if (scaleChildren) {
  48063. for (var i = 0; i < len; i++) {
  48064. this.children[i].scale(x, y, z, scaleChildren);
  48065. }
  48066. }
  48067. this.markAsDirty();
  48068. };
  48069. /**
  48070. * Set the yaw, pitch, and roll of the bone in local or world space.
  48071. * @param yaw The rotation of the bone on the y axis.
  48072. * @param pitch The rotation of the bone on the x axis.
  48073. * @param roll The rotation of the bone on the z axis.
  48074. * @param space The space that the axes of rotation are in.
  48075. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48076. */
  48077. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  48078. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48079. var rotMat = Bone._tmpMats[0];
  48080. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  48081. var rotMatInv = Bone._tmpMats[1];
  48082. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  48083. rotMatInv.multiplyToRef(rotMat, rotMat);
  48084. this._rotateWithMatrix(rotMat, space, mesh);
  48085. };
  48086. /**
  48087. * Rotate the bone on an axis in local or world space.
  48088. * @param axis The axis to rotate the bone on.
  48089. * @param amount The amount to rotate the bone.
  48090. * @param space The space that the axis is in.
  48091. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48092. */
  48093. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  48094. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48095. var rmat = Bone._tmpMats[0];
  48096. rmat.m[12] = 0;
  48097. rmat.m[13] = 0;
  48098. rmat.m[14] = 0;
  48099. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  48100. this._rotateWithMatrix(rmat, space, mesh);
  48101. };
  48102. /**
  48103. * Set the rotation of the bone to a particular axis angle in local or world space.
  48104. * @param axis The axis to rotate the bone on.
  48105. * @param angle The angle that the bone should be rotated to.
  48106. * @param space The space that the axis is in.
  48107. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48108. */
  48109. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  48110. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48111. var rotMat = Bone._tmpMats[0];
  48112. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  48113. var rotMatInv = Bone._tmpMats[1];
  48114. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  48115. rotMatInv.multiplyToRef(rotMat, rotMat);
  48116. this._rotateWithMatrix(rotMat, space, mesh);
  48117. };
  48118. /**
  48119. * Set the euler rotation of the bone in local of world space.
  48120. * @param rotation The euler rotation that the bone should be set to.
  48121. * @param space The space that the rotation is in.
  48122. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48123. */
  48124. Bone.prototype.setRotation = function (rotation, space, mesh) {
  48125. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48126. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  48127. };
  48128. /**
  48129. * Set the quaternion rotation of the bone in local of world space.
  48130. * @param quat The quaternion rotation that the bone should be set to.
  48131. * @param space The space that the rotation is in.
  48132. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48133. */
  48134. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  48135. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48136. var rotMatInv = Bone._tmpMats[0];
  48137. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  48138. var rotMat = Bone._tmpMats[1];
  48139. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  48140. rotMatInv.multiplyToRef(rotMat, rotMat);
  48141. this._rotateWithMatrix(rotMat, space, mesh);
  48142. };
  48143. /**
  48144. * Set the rotation matrix of the bone in local of world space.
  48145. * @param rotMat The rotation matrix that the bone should be set to.
  48146. * @param space The space that the rotation is in.
  48147. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48148. */
  48149. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  48150. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48151. var rotMatInv = Bone._tmpMats[0];
  48152. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  48153. var rotMat2 = Bone._tmpMats[1];
  48154. rotMat2.copyFrom(rotMat);
  48155. rotMatInv.multiplyToRef(rotMat, rotMat2);
  48156. this._rotateWithMatrix(rotMat2, space, mesh);
  48157. };
  48158. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  48159. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48160. var lmat = this.getLocalMatrix();
  48161. var lx = lmat.m[12];
  48162. var ly = lmat.m[13];
  48163. var lz = lmat.m[14];
  48164. var parent = this.getParent();
  48165. var parentScale = Bone._tmpMats[3];
  48166. var parentScaleInv = Bone._tmpMats[4];
  48167. if (parent) {
  48168. if (space == BABYLON.Space.WORLD) {
  48169. if (mesh) {
  48170. parentScale.copyFrom(mesh.getWorldMatrix());
  48171. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  48172. }
  48173. else {
  48174. parentScale.copyFrom(parent.getAbsoluteTransform());
  48175. }
  48176. }
  48177. else {
  48178. parentScale = parent._scaleMatrix;
  48179. }
  48180. parentScaleInv.copyFrom(parentScale);
  48181. parentScaleInv.invert();
  48182. lmat.multiplyToRef(parentScale, lmat);
  48183. lmat.multiplyToRef(rmat, lmat);
  48184. lmat.multiplyToRef(parentScaleInv, lmat);
  48185. }
  48186. else {
  48187. if (space == BABYLON.Space.WORLD && mesh) {
  48188. parentScale.copyFrom(mesh.getWorldMatrix());
  48189. parentScaleInv.copyFrom(parentScale);
  48190. parentScaleInv.invert();
  48191. lmat.multiplyToRef(parentScale, lmat);
  48192. lmat.multiplyToRef(rmat, lmat);
  48193. lmat.multiplyToRef(parentScaleInv, lmat);
  48194. }
  48195. else {
  48196. lmat.multiplyToRef(rmat, lmat);
  48197. }
  48198. }
  48199. lmat.m[12] = lx;
  48200. lmat.m[13] = ly;
  48201. lmat.m[14] = lz;
  48202. this.computeAbsoluteTransforms();
  48203. this.markAsDirty();
  48204. };
  48205. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  48206. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48207. if (space == BABYLON.Space.WORLD) {
  48208. var scaleMatrix = Bone._tmpMats[2];
  48209. scaleMatrix.copyFrom(this._scaleMatrix);
  48210. rotMatInv.copyFrom(this.getAbsoluteTransform());
  48211. if (mesh) {
  48212. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  48213. var meshScale = Bone._tmpMats[3];
  48214. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  48215. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  48216. }
  48217. rotMatInv.invert();
  48218. scaleMatrix.m[0] *= this._scalingDeterminant;
  48219. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  48220. }
  48221. else {
  48222. rotMatInv.copyFrom(this.getLocalMatrix());
  48223. rotMatInv.invert();
  48224. var scaleMatrix = Bone._tmpMats[2];
  48225. scaleMatrix.copyFrom(this._scaleMatrix);
  48226. if (this._parent) {
  48227. var pscaleMatrix = Bone._tmpMats[3];
  48228. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  48229. pscaleMatrix.invert();
  48230. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  48231. }
  48232. else {
  48233. scaleMatrix.m[0] *= this._scalingDeterminant;
  48234. }
  48235. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  48236. }
  48237. };
  48238. /**
  48239. * Get the scale of the bone
  48240. * @returns the scale of the bone
  48241. */
  48242. Bone.prototype.getScale = function () {
  48243. return this._scaleVector.clone();
  48244. };
  48245. /**
  48246. * Copy the scale of the bone to a vector3.
  48247. * @param result The vector3 to copy the scale to
  48248. */
  48249. Bone.prototype.getScaleToRef = function (result) {
  48250. result.copyFrom(this._scaleVector);
  48251. };
  48252. /**
  48253. * Get the position of the bone in local or world space.
  48254. * @param space The space that the returned position is in.
  48255. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48256. * @returns The position of the bone
  48257. */
  48258. Bone.prototype.getPosition = function (space, mesh) {
  48259. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48260. var pos = BABYLON.Vector3.Zero();
  48261. this.getPositionToRef(space, mesh, pos);
  48262. return pos;
  48263. };
  48264. /**
  48265. * Copy the position of the bone to a vector3 in local or world space.
  48266. * @param space The space that the returned position is in.
  48267. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48268. * @param result The vector3 to copy the position to.
  48269. */
  48270. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  48271. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48272. if (space == BABYLON.Space.LOCAL) {
  48273. var lm = this.getLocalMatrix();
  48274. result.x = lm.m[12];
  48275. result.y = lm.m[13];
  48276. result.z = lm.m[14];
  48277. }
  48278. else {
  48279. var wm;
  48280. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  48281. if (mesh) {
  48282. wm = mesh.getWorldMatrix();
  48283. }
  48284. this._skeleton.computeAbsoluteTransforms();
  48285. var tmat = Bone._tmpMats[0];
  48286. if (mesh) {
  48287. tmat.copyFrom(this.getAbsoluteTransform());
  48288. tmat.multiplyToRef(wm, tmat);
  48289. }
  48290. else {
  48291. tmat = this.getAbsoluteTransform();
  48292. }
  48293. result.x = tmat.m[12];
  48294. result.y = tmat.m[13];
  48295. result.z = tmat.m[14];
  48296. }
  48297. };
  48298. /**
  48299. * Get the absolute position of the bone (world space).
  48300. * @param mesh The mesh that this bone is attached to.
  48301. * @returns The absolute position of the bone
  48302. */
  48303. Bone.prototype.getAbsolutePosition = function (mesh) {
  48304. var pos = BABYLON.Vector3.Zero();
  48305. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  48306. return pos;
  48307. };
  48308. /**
  48309. * Copy the absolute position of the bone (world space) to the result param.
  48310. * @param mesh The mesh that this bone is attached to.
  48311. * @param result The vector3 to copy the absolute position to.
  48312. */
  48313. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  48314. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  48315. };
  48316. /**
  48317. * Compute the absolute transforms of this bone and its children.
  48318. */
  48319. Bone.prototype.computeAbsoluteTransforms = function () {
  48320. if (this._parent) {
  48321. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  48322. }
  48323. else {
  48324. this._absoluteTransform.copyFrom(this._localMatrix);
  48325. var poseMatrix = this._skeleton.getPoseMatrix();
  48326. if (poseMatrix) {
  48327. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  48328. }
  48329. }
  48330. var children = this.children;
  48331. var len = children.length;
  48332. for (var i = 0; i < len; i++) {
  48333. children[i].computeAbsoluteTransforms();
  48334. }
  48335. };
  48336. Bone.prototype._syncScaleVector = function () {
  48337. var lm = this.getLocalMatrix();
  48338. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  48339. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  48340. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  48341. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  48342. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  48343. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  48344. this._scaleVector.x = xs * Math.sqrt(xsq);
  48345. this._scaleVector.y = ys * Math.sqrt(ysq);
  48346. this._scaleVector.z = zs * Math.sqrt(zsq);
  48347. if (this._parent) {
  48348. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  48349. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  48350. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  48351. }
  48352. 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);
  48353. };
  48354. /**
  48355. * Get the world direction from an axis that is in the local space of the bone.
  48356. * @param localAxis The local direction that is used to compute the world direction.
  48357. * @param mesh The mesh that this bone is attached to.
  48358. * @returns The world direction
  48359. */
  48360. Bone.prototype.getDirection = function (localAxis, mesh) {
  48361. var result = BABYLON.Vector3.Zero();
  48362. this.getDirectionToRef(localAxis, mesh, result);
  48363. return result;
  48364. };
  48365. /**
  48366. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  48367. * @param localAxis The local direction that is used to compute the world direction.
  48368. * @param mesh The mesh that this bone is attached to.
  48369. * @param result The vector3 that the world direction will be copied to.
  48370. */
  48371. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  48372. var wm;
  48373. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  48374. if (mesh) {
  48375. wm = mesh.getWorldMatrix();
  48376. }
  48377. this._skeleton.computeAbsoluteTransforms();
  48378. var mat = Bone._tmpMats[0];
  48379. mat.copyFrom(this.getAbsoluteTransform());
  48380. if (mesh) {
  48381. mat.multiplyToRef(wm, mat);
  48382. }
  48383. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  48384. result.normalize();
  48385. };
  48386. /**
  48387. * Get the euler rotation of the bone in local or world space.
  48388. * @param space The space that the rotation should be in.
  48389. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48390. * @returns The euler rotation
  48391. */
  48392. Bone.prototype.getRotation = function (space, mesh) {
  48393. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48394. var result = BABYLON.Vector3.Zero();
  48395. this.getRotationToRef(space, mesh, result);
  48396. return result;
  48397. };
  48398. /**
  48399. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  48400. * @param space The space that the rotation should be in.
  48401. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48402. * @param result The vector3 that the rotation should be copied to.
  48403. */
  48404. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  48405. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48406. var quat = Bone._tmpQuat;
  48407. this.getRotationQuaternionToRef(space, mesh, quat);
  48408. quat.toEulerAnglesToRef(result);
  48409. };
  48410. /**
  48411. * Get the quaternion rotation of the bone in either local or world space.
  48412. * @param space The space that the rotation should be in.
  48413. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48414. * @returns The quaternion rotation
  48415. */
  48416. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  48417. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48418. var result = BABYLON.Quaternion.Identity();
  48419. this.getRotationQuaternionToRef(space, mesh, result);
  48420. return result;
  48421. };
  48422. /**
  48423. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  48424. * @param space The space that the rotation should be in.
  48425. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48426. * @param result The quaternion that the rotation should be copied to.
  48427. */
  48428. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  48429. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48430. if (space == BABYLON.Space.LOCAL) {
  48431. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  48432. }
  48433. else {
  48434. var mat = Bone._tmpMats[0];
  48435. var amat = this.getAbsoluteTransform();
  48436. if (mesh) {
  48437. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  48438. }
  48439. else {
  48440. mat.copyFrom(amat);
  48441. }
  48442. mat.m[0] *= this._scalingDeterminant;
  48443. mat.m[1] *= this._scalingDeterminant;
  48444. mat.m[2] *= this._scalingDeterminant;
  48445. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  48446. }
  48447. };
  48448. /**
  48449. * Get the rotation matrix of the bone in local or world space.
  48450. * @param space The space that the rotation should be in.
  48451. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48452. * @returns The rotation matrix
  48453. */
  48454. Bone.prototype.getRotationMatrix = function (space, mesh) {
  48455. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48456. var result = BABYLON.Matrix.Identity();
  48457. this.getRotationMatrixToRef(space, mesh, result);
  48458. return result;
  48459. };
  48460. /**
  48461. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  48462. * @param space The space that the rotation should be in.
  48463. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48464. * @param result The quaternion that the rotation should be copied to.
  48465. */
  48466. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  48467. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48468. if (space == BABYLON.Space.LOCAL) {
  48469. this.getLocalMatrix().getRotationMatrixToRef(result);
  48470. }
  48471. else {
  48472. var mat = Bone._tmpMats[0];
  48473. var amat = this.getAbsoluteTransform();
  48474. if (mesh) {
  48475. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  48476. }
  48477. else {
  48478. mat.copyFrom(amat);
  48479. }
  48480. mat.m[0] *= this._scalingDeterminant;
  48481. mat.m[1] *= this._scalingDeterminant;
  48482. mat.m[2] *= this._scalingDeterminant;
  48483. mat.getRotationMatrixToRef(result);
  48484. }
  48485. };
  48486. /**
  48487. * Get the world position of a point that is in the local space of the bone.
  48488. * @param position The local position
  48489. * @param mesh The mesh that this bone is attached to.
  48490. * @returns The world position
  48491. */
  48492. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  48493. var result = BABYLON.Vector3.Zero();
  48494. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  48495. return result;
  48496. };
  48497. /**
  48498. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  48499. * @param position The local position
  48500. * @param mesh The mesh that this bone is attached to.
  48501. * @param result The vector3 that the world position should be copied to.
  48502. */
  48503. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  48504. var wm;
  48505. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  48506. if (mesh) {
  48507. wm = mesh.getWorldMatrix();
  48508. }
  48509. this._skeleton.computeAbsoluteTransforms();
  48510. var tmat = Bone._tmpMats[0];
  48511. if (mesh) {
  48512. tmat.copyFrom(this.getAbsoluteTransform());
  48513. tmat.multiplyToRef(wm, tmat);
  48514. }
  48515. else {
  48516. tmat = this.getAbsoluteTransform();
  48517. }
  48518. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  48519. };
  48520. /**
  48521. * Get the local position of a point that is in world space.
  48522. * @param position The world position
  48523. * @param mesh The mesh that this bone is attached to.
  48524. * @returns The local position
  48525. */
  48526. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  48527. var result = BABYLON.Vector3.Zero();
  48528. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  48529. return result;
  48530. };
  48531. /**
  48532. * Get the local position of a point that is in world space and copy it to the result param.
  48533. * @param position The world position
  48534. * @param mesh The mesh that this bone is attached to.
  48535. * @param result The vector3 that the local position should be copied to.
  48536. */
  48537. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  48538. var wm;
  48539. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  48540. if (mesh) {
  48541. wm = mesh.getWorldMatrix();
  48542. }
  48543. this._skeleton.computeAbsoluteTransforms();
  48544. var tmat = Bone._tmpMats[0];
  48545. tmat.copyFrom(this.getAbsoluteTransform());
  48546. if (mesh) {
  48547. tmat.multiplyToRef(wm, tmat);
  48548. }
  48549. tmat.invert();
  48550. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  48551. };
  48552. return Bone;
  48553. }(BABYLON.Node));
  48554. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  48555. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  48556. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  48557. BABYLON.Bone = Bone;
  48558. })(BABYLON || (BABYLON = {}));
  48559. //# sourceMappingURL=babylon.bone.js.map
  48560. var BABYLON;
  48561. (function (BABYLON) {
  48562. var BoneIKController = (function () {
  48563. function BoneIKController(mesh, bone, options) {
  48564. this.targetPosition = BABYLON.Vector3.Zero();
  48565. this.poleTargetPosition = BABYLON.Vector3.Zero();
  48566. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  48567. this.poleAngle = 0;
  48568. this.slerpAmount = 1;
  48569. this._bone1Quat = BABYLON.Quaternion.Identity();
  48570. this._bone1Mat = BABYLON.Matrix.Identity();
  48571. this._bone2Ang = Math.PI;
  48572. this._maxAngle = Math.PI;
  48573. this._rightHandedSystem = false;
  48574. this._bendAxis = BABYLON.Vector3.Right();
  48575. this._slerping = false;
  48576. this._adjustRoll = 0;
  48577. this._bone2 = bone;
  48578. this._bone1 = bone.getParent();
  48579. this.mesh = mesh;
  48580. var bonePos = bone.getPosition();
  48581. if (bone.getAbsoluteTransform().determinant() > 0) {
  48582. this._rightHandedSystem = true;
  48583. this._bendAxis.x = 0;
  48584. this._bendAxis.y = 0;
  48585. this._bendAxis.z = -1;
  48586. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  48587. this._adjustRoll = Math.PI * .5;
  48588. this._bendAxis.z = 1;
  48589. }
  48590. }
  48591. if (this._bone1.length) {
  48592. var boneScale1 = this._bone1.getScale();
  48593. var boneScale2 = this._bone2.getScale();
  48594. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  48595. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  48596. }
  48597. else if (this._bone1.children[0]) {
  48598. mesh.computeWorldMatrix(true);
  48599. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  48600. var pos2 = this._bone2.getAbsolutePosition(mesh);
  48601. var pos3 = this._bone1.getAbsolutePosition(mesh);
  48602. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  48603. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  48604. }
  48605. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  48606. this.maxAngle = Math.PI;
  48607. if (options) {
  48608. if (options.targetMesh) {
  48609. this.targetMesh = options.targetMesh;
  48610. this.targetMesh.computeWorldMatrix(true);
  48611. }
  48612. if (options.poleTargetMesh) {
  48613. this.poleTargetMesh = options.poleTargetMesh;
  48614. this.poleTargetMesh.computeWorldMatrix(true);
  48615. }
  48616. else if (options.poleTargetBone) {
  48617. this.poleTargetBone = options.poleTargetBone;
  48618. }
  48619. else if (this._bone1.getParent()) {
  48620. this.poleTargetBone = this._bone1.getParent();
  48621. }
  48622. if (options.poleTargetLocalOffset) {
  48623. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  48624. }
  48625. if (options.poleAngle) {
  48626. this.poleAngle = options.poleAngle;
  48627. }
  48628. if (options.bendAxis) {
  48629. this._bendAxis.copyFrom(options.bendAxis);
  48630. }
  48631. if (options.maxAngle) {
  48632. this.maxAngle = options.maxAngle;
  48633. }
  48634. if (options.slerpAmount) {
  48635. this.slerpAmount = options.slerpAmount;
  48636. }
  48637. }
  48638. }
  48639. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  48640. get: function () {
  48641. return this._maxAngle;
  48642. },
  48643. set: function (value) {
  48644. this._setMaxAngle(value);
  48645. },
  48646. enumerable: true,
  48647. configurable: true
  48648. });
  48649. BoneIKController.prototype._setMaxAngle = function (ang) {
  48650. if (ang < 0) {
  48651. ang = 0;
  48652. }
  48653. if (ang > Math.PI || ang == undefined) {
  48654. ang = Math.PI;
  48655. }
  48656. this._maxAngle = ang;
  48657. var a = this._bone1Length;
  48658. var b = this._bone2Length;
  48659. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  48660. };
  48661. BoneIKController.prototype.update = function () {
  48662. var bone1 = this._bone1;
  48663. var target = this.targetPosition;
  48664. var poleTarget = this.poleTargetPosition;
  48665. var mat1 = BoneIKController._tmpMats[0];
  48666. var mat2 = BoneIKController._tmpMats[1];
  48667. if (this.targetMesh) {
  48668. target.copyFrom(this.targetMesh.getAbsolutePosition());
  48669. }
  48670. if (this.poleTargetBone) {
  48671. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  48672. }
  48673. else if (this.poleTargetMesh) {
  48674. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  48675. }
  48676. var bonePos = BoneIKController._tmpVecs[0];
  48677. var zaxis = BoneIKController._tmpVecs[1];
  48678. var xaxis = BoneIKController._tmpVecs[2];
  48679. var yaxis = BoneIKController._tmpVecs[3];
  48680. var upAxis = BoneIKController._tmpVecs[4];
  48681. var _tmpQuat = BoneIKController._tmpQuat;
  48682. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  48683. poleTarget.subtractToRef(bonePos, upAxis);
  48684. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  48685. upAxis.y = 1;
  48686. }
  48687. else {
  48688. upAxis.normalize();
  48689. }
  48690. target.subtractToRef(bonePos, yaxis);
  48691. yaxis.normalize();
  48692. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  48693. zaxis.normalize();
  48694. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  48695. xaxis.normalize();
  48696. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  48697. var a = this._bone1Length;
  48698. var b = this._bone2Length;
  48699. var c = BABYLON.Vector3.Distance(bonePos, target);
  48700. if (this._maxReach > 0) {
  48701. c = Math.min(this._maxReach, c);
  48702. }
  48703. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  48704. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  48705. if (acosa > 1) {
  48706. acosa = 1;
  48707. }
  48708. if (acosb > 1) {
  48709. acosb = 1;
  48710. }
  48711. if (acosa < -1) {
  48712. acosa = -1;
  48713. }
  48714. if (acosb < -1) {
  48715. acosb = -1;
  48716. }
  48717. var angA = Math.acos(acosa);
  48718. var angB = Math.acos(acosb);
  48719. var angC = -angA - angB;
  48720. if (this._rightHandedSystem) {
  48721. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  48722. mat2.multiplyToRef(mat1, mat1);
  48723. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  48724. mat2.multiplyToRef(mat1, mat1);
  48725. }
  48726. else {
  48727. var _tmpVec = BoneIKController._tmpVecs[5];
  48728. _tmpVec.copyFrom(this._bendAxis);
  48729. _tmpVec.x *= -1;
  48730. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  48731. mat2.multiplyToRef(mat1, mat1);
  48732. }
  48733. if (this.poleAngle) {
  48734. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  48735. mat1.multiplyToRef(mat2, mat1);
  48736. }
  48737. if (this.slerpAmount < 1) {
  48738. if (!this._slerping) {
  48739. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  48740. }
  48741. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  48742. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  48743. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  48744. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  48745. this._slerping = true;
  48746. }
  48747. else {
  48748. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  48749. this._bone1Mat.copyFrom(mat1);
  48750. this._slerping = false;
  48751. }
  48752. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  48753. this._bone2Ang = angC;
  48754. };
  48755. return BoneIKController;
  48756. }());
  48757. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  48758. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  48759. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  48760. BABYLON.BoneIKController = BoneIKController;
  48761. })(BABYLON || (BABYLON = {}));
  48762. //# sourceMappingURL=babylon.boneIKController.js.map
  48763. var BABYLON;
  48764. (function (BABYLON) {
  48765. var BoneLookController = (function () {
  48766. /**
  48767. * Create a BoneLookController
  48768. * @param mesh the mesh that the bone belongs to
  48769. * @param bone the bone that will be looking to the target
  48770. * @param target the target Vector3 to look at
  48771. * @param settings optional settings:
  48772. * - maxYaw: the maximum angle the bone will yaw to
  48773. * - minYaw: the minimum angle the bone will yaw to
  48774. * - maxPitch: the maximum angle the bone will pitch to
  48775. * - minPitch: the minimum angle the bone will yaw to
  48776. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  48777. * - upAxis: the up axis of the coordinate system
  48778. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  48779. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  48780. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  48781. * - adjustYaw: used to make an adjustment to the yaw of the bone
  48782. * - adjustPitch: used to make an adjustment to the pitch of the bone
  48783. * - adjustRoll: used to make an adjustment to the roll of the bone
  48784. **/
  48785. function BoneLookController(mesh, bone, target, options) {
  48786. /**
  48787. * The up axis of the coordinate system that is used when the bone is rotated.
  48788. */
  48789. this.upAxis = BABYLON.Vector3.Up();
  48790. /**
  48791. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  48792. */
  48793. this.upAxisSpace = BABYLON.Space.LOCAL;
  48794. /**
  48795. * Used to make an adjustment to the yaw of the bone.
  48796. */
  48797. this.adjustYaw = 0;
  48798. /**
  48799. * Used to make an adjustment to the pitch of the bone.
  48800. */
  48801. this.adjustPitch = 0;
  48802. /**
  48803. * Used to make an adjustment to the roll of the bone.
  48804. */
  48805. this.adjustRoll = 0;
  48806. /**
  48807. * 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).
  48808. */
  48809. this.slerpAmount = 1;
  48810. this._boneQuat = BABYLON.Quaternion.Identity();
  48811. this._slerping = false;
  48812. this._firstFrameSkipped = false;
  48813. this._fowardAxis = BABYLON.Vector3.Forward();
  48814. this.mesh = mesh;
  48815. this.bone = bone;
  48816. this.target = target;
  48817. if (options) {
  48818. if (options.adjustYaw) {
  48819. this.adjustYaw = options.adjustYaw;
  48820. }
  48821. if (options.adjustPitch) {
  48822. this.adjustPitch = options.adjustPitch;
  48823. }
  48824. if (options.adjustRoll) {
  48825. this.adjustRoll = options.adjustRoll;
  48826. }
  48827. if (options.maxYaw != null) {
  48828. this.maxYaw = options.maxYaw;
  48829. }
  48830. else {
  48831. this.maxYaw = Math.PI;
  48832. }
  48833. if (options.minYaw != null) {
  48834. this.minYaw = options.minYaw;
  48835. }
  48836. else {
  48837. this.minYaw = -Math.PI;
  48838. }
  48839. if (options.maxPitch != null) {
  48840. this.maxPitch = options.maxPitch;
  48841. }
  48842. else {
  48843. this.maxPitch = Math.PI;
  48844. }
  48845. if (options.minPitch != null) {
  48846. this.minPitch = options.minPitch;
  48847. }
  48848. else {
  48849. this.minPitch = -Math.PI;
  48850. }
  48851. if (options.slerpAmount != null) {
  48852. this.slerpAmount = options.slerpAmount;
  48853. }
  48854. if (options.upAxis != null) {
  48855. this.upAxis = options.upAxis;
  48856. }
  48857. if (options.upAxisSpace != null) {
  48858. this.upAxisSpace = options.upAxisSpace;
  48859. }
  48860. if (options.yawAxis != null || options.pitchAxis != null) {
  48861. var newYawAxis = BABYLON.Axis.Y;
  48862. var newPitchAxis = BABYLON.Axis.X;
  48863. if (options.yawAxis != null) {
  48864. newYawAxis = options.yawAxis.clone();
  48865. newYawAxis.normalize();
  48866. }
  48867. if (options.pitchAxis != null) {
  48868. newPitchAxis = options.pitchAxis.clone();
  48869. newPitchAxis.normalize();
  48870. }
  48871. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  48872. this._transformYawPitch = BABYLON.Matrix.Identity();
  48873. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  48874. this._transformYawPitchInv = this._transformYawPitch.clone();
  48875. this._transformYawPitch.invert();
  48876. }
  48877. }
  48878. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  48879. this.upAxisSpace = BABYLON.Space.LOCAL;
  48880. }
  48881. }
  48882. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  48883. /**
  48884. * Get/set the minimum yaw angle that the bone can look to.
  48885. */
  48886. get: function () {
  48887. return this._minYaw;
  48888. },
  48889. set: function (value) {
  48890. this._minYaw = value;
  48891. this._minYawSin = Math.sin(value);
  48892. this._minYawCos = Math.cos(value);
  48893. if (this._maxYaw != null) {
  48894. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  48895. this._yawRange = this._maxYaw - this._minYaw;
  48896. }
  48897. },
  48898. enumerable: true,
  48899. configurable: true
  48900. });
  48901. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  48902. /**
  48903. * Get/set the maximum yaw angle that the bone can look to.
  48904. */
  48905. get: function () {
  48906. return this._maxYaw;
  48907. },
  48908. set: function (value) {
  48909. this._maxYaw = value;
  48910. this._maxYawSin = Math.sin(value);
  48911. this._maxYawCos = Math.cos(value);
  48912. if (this._minYaw != null) {
  48913. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  48914. this._yawRange = this._maxYaw - this._minYaw;
  48915. }
  48916. },
  48917. enumerable: true,
  48918. configurable: true
  48919. });
  48920. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  48921. /**
  48922. * Get/set the minimum pitch angle that the bone can look to.
  48923. */
  48924. get: function () {
  48925. return this._minPitch;
  48926. },
  48927. set: function (value) {
  48928. this._minPitch = value;
  48929. this._minPitchTan = Math.tan(value);
  48930. },
  48931. enumerable: true,
  48932. configurable: true
  48933. });
  48934. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  48935. /**
  48936. * Get/set the maximum pitch angle that the bone can look to.
  48937. */
  48938. get: function () {
  48939. return this._maxPitch;
  48940. },
  48941. set: function (value) {
  48942. this._maxPitch = value;
  48943. this._maxPitchTan = Math.tan(value);
  48944. },
  48945. enumerable: true,
  48946. configurable: true
  48947. });
  48948. /**
  48949. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  48950. */
  48951. BoneLookController.prototype.update = function () {
  48952. //skip the first frame when slerping so that the mesh rotation is correct
  48953. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  48954. this._firstFrameSkipped = true;
  48955. return;
  48956. }
  48957. var bone = this.bone;
  48958. var bonePos = BoneLookController._tmpVecs[0];
  48959. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  48960. var target = this.target;
  48961. var _tmpMat1 = BoneLookController._tmpMats[0];
  48962. var _tmpMat2 = BoneLookController._tmpMats[1];
  48963. var mesh = this.mesh;
  48964. var parentBone = bone.getParent();
  48965. var upAxis = BoneLookController._tmpVecs[1];
  48966. upAxis.copyFrom(this.upAxis);
  48967. if (this.upAxisSpace == BABYLON.Space.BONE) {
  48968. if (this._transformYawPitch) {
  48969. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  48970. }
  48971. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  48972. }
  48973. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  48974. mesh.getDirectionToRef(upAxis, upAxis);
  48975. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  48976. upAxis.normalize();
  48977. }
  48978. }
  48979. var checkYaw = false;
  48980. var checkPitch = false;
  48981. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  48982. checkYaw = true;
  48983. }
  48984. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  48985. checkPitch = true;
  48986. }
  48987. if (checkYaw || checkPitch) {
  48988. var spaceMat = BoneLookController._tmpMats[2];
  48989. var spaceMatInv = BoneLookController._tmpMats[3];
  48990. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  48991. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  48992. }
  48993. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  48994. spaceMat.copyFrom(mesh.getWorldMatrix());
  48995. }
  48996. else {
  48997. var forwardAxis = BoneLookController._tmpVecs[2];
  48998. forwardAxis.copyFrom(this._fowardAxis);
  48999. if (this._transformYawPitch) {
  49000. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  49001. }
  49002. if (parentBone) {
  49003. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  49004. }
  49005. else {
  49006. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  49007. }
  49008. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  49009. rightAxis.normalize();
  49010. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  49011. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  49012. }
  49013. spaceMat.invertToRef(spaceMatInv);
  49014. var xzlen;
  49015. if (checkPitch) {
  49016. var localTarget = BoneLookController._tmpVecs[3];
  49017. target.subtractToRef(bonePos, localTarget);
  49018. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  49019. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  49020. var pitch = Math.atan2(localTarget.y, xzlen);
  49021. var newPitch = pitch;
  49022. if (pitch > this._maxPitch) {
  49023. localTarget.y = this._maxPitchTan * xzlen;
  49024. newPitch = this._maxPitch;
  49025. }
  49026. else if (pitch < this._minPitch) {
  49027. localTarget.y = this._minPitchTan * xzlen;
  49028. newPitch = this._minPitch;
  49029. }
  49030. if (pitch != newPitch) {
  49031. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  49032. localTarget.addInPlace(bonePos);
  49033. target = localTarget;
  49034. }
  49035. }
  49036. if (checkYaw) {
  49037. var localTarget = BoneLookController._tmpVecs[4];
  49038. target.subtractToRef(bonePos, localTarget);
  49039. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  49040. var yaw = Math.atan2(localTarget.x, localTarget.z);
  49041. var newYaw = yaw;
  49042. if (yaw > this._maxYaw || yaw < this._minYaw) {
  49043. if (xzlen == null) {
  49044. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  49045. }
  49046. if (this._yawRange > Math.PI) {
  49047. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  49048. localTarget.z = this._maxYawCos * xzlen;
  49049. localTarget.x = this._maxYawSin * xzlen;
  49050. newYaw = this._maxYaw;
  49051. }
  49052. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  49053. localTarget.z = this._minYawCos * xzlen;
  49054. localTarget.x = this._minYawSin * xzlen;
  49055. newYaw = this._minYaw;
  49056. }
  49057. }
  49058. else {
  49059. if (yaw > this._maxYaw) {
  49060. localTarget.z = this._maxYawCos * xzlen;
  49061. localTarget.x = this._maxYawSin * xzlen;
  49062. newYaw = this._maxYaw;
  49063. }
  49064. else if (yaw < this._minYaw) {
  49065. localTarget.z = this._minYawCos * xzlen;
  49066. localTarget.x = this._minYawSin * xzlen;
  49067. newYaw = this._minYaw;
  49068. }
  49069. }
  49070. }
  49071. if (this._slerping && this._yawRange > Math.PI) {
  49072. //are we going to be crossing into the min/max region?
  49073. var boneFwd = BoneLookController._tmpVecs[8];
  49074. boneFwd.copyFrom(BABYLON.Axis.Z);
  49075. if (this._transformYawPitch) {
  49076. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  49077. }
  49078. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  49079. this._boneQuat.toRotationMatrix(boneRotMat);
  49080. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  49081. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  49082. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  49083. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  49084. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  49085. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  49086. if (angBtwTar > angBtwMidYaw) {
  49087. if (xzlen == null) {
  49088. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  49089. }
  49090. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  49091. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  49092. if (angBtwMin < angBtwMax) {
  49093. newYaw = boneYaw + Math.PI * .75;
  49094. localTarget.z = Math.cos(newYaw) * xzlen;
  49095. localTarget.x = Math.sin(newYaw) * xzlen;
  49096. }
  49097. else {
  49098. newYaw = boneYaw - Math.PI * .75;
  49099. localTarget.z = Math.cos(newYaw) * xzlen;
  49100. localTarget.x = Math.sin(newYaw) * xzlen;
  49101. }
  49102. }
  49103. }
  49104. if (yaw != newYaw) {
  49105. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  49106. localTarget.addInPlace(bonePos);
  49107. target = localTarget;
  49108. }
  49109. }
  49110. }
  49111. var zaxis = BoneLookController._tmpVecs[5];
  49112. var xaxis = BoneLookController._tmpVecs[6];
  49113. var yaxis = BoneLookController._tmpVecs[7];
  49114. var _tmpQuat = BoneLookController._tmpQuat;
  49115. target.subtractToRef(bonePos, zaxis);
  49116. zaxis.normalize();
  49117. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  49118. xaxis.normalize();
  49119. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  49120. yaxis.normalize();
  49121. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  49122. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  49123. return;
  49124. }
  49125. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  49126. return;
  49127. }
  49128. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  49129. return;
  49130. }
  49131. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  49132. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  49133. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  49134. }
  49135. if (this.slerpAmount < 1) {
  49136. if (!this._slerping) {
  49137. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  49138. }
  49139. if (this._transformYawPitch) {
  49140. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  49141. }
  49142. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  49143. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  49144. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  49145. this._slerping = true;
  49146. }
  49147. else {
  49148. if (this._transformYawPitch) {
  49149. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  49150. }
  49151. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  49152. this._slerping = false;
  49153. }
  49154. };
  49155. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  49156. var angDiff = ang2 - ang1;
  49157. angDiff %= Math.PI * 2;
  49158. if (angDiff > Math.PI) {
  49159. angDiff -= Math.PI * 2;
  49160. }
  49161. else if (angDiff < -Math.PI) {
  49162. angDiff += Math.PI * 2;
  49163. }
  49164. return angDiff;
  49165. };
  49166. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  49167. ang1 %= (2 * Math.PI);
  49168. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  49169. ang2 %= (2 * Math.PI);
  49170. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  49171. var ab = 0;
  49172. if (ang1 < ang2) {
  49173. ab = ang2 - ang1;
  49174. }
  49175. else {
  49176. ab = ang1 - ang2;
  49177. }
  49178. if (ab > Math.PI) {
  49179. ab = Math.PI * 2 - ab;
  49180. }
  49181. return ab;
  49182. };
  49183. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  49184. ang %= (2 * Math.PI);
  49185. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  49186. ang1 %= (2 * Math.PI);
  49187. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  49188. ang2 %= (2 * Math.PI);
  49189. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  49190. if (ang1 < ang2) {
  49191. if (ang > ang1 && ang < ang2) {
  49192. return true;
  49193. }
  49194. }
  49195. else {
  49196. if (ang > ang2 && ang < ang1) {
  49197. return true;
  49198. }
  49199. }
  49200. return false;
  49201. };
  49202. return BoneLookController;
  49203. }());
  49204. 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()];
  49205. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  49206. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  49207. BABYLON.BoneLookController = BoneLookController;
  49208. })(BABYLON || (BABYLON = {}));
  49209. //# sourceMappingURL=babylon.boneLookController.js.map
  49210. var BABYLON;
  49211. (function (BABYLON) {
  49212. var Skeleton = (function () {
  49213. function Skeleton(name, id, scene) {
  49214. this.name = name;
  49215. this.id = id;
  49216. this.bones = new Array();
  49217. this.needInitialSkinMatrix = false;
  49218. this._isDirty = true;
  49219. this._meshesWithPoseMatrix = new Array();
  49220. this._identity = BABYLON.Matrix.Identity();
  49221. this._ranges = {};
  49222. this._lastAbsoluteTransformsUpdateId = -1;
  49223. // Events
  49224. /**
  49225. * An event triggered before computing the skeleton's matrices
  49226. * @type {BABYLON.Observable}
  49227. */
  49228. this.onBeforeComputeObservable = new BABYLON.Observable();
  49229. this.bones = [];
  49230. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49231. scene.skeletons.push(this);
  49232. //make sure it will recalculate the matrix next time prepare is called.
  49233. this._isDirty = true;
  49234. }
  49235. // Members
  49236. Skeleton.prototype.getTransformMatrices = function (mesh) {
  49237. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  49238. return mesh._bonesTransformMatrices;
  49239. }
  49240. if (!this._transformMatrices) {
  49241. this.prepare();
  49242. }
  49243. return this._transformMatrices;
  49244. };
  49245. Skeleton.prototype.getScene = function () {
  49246. return this._scene;
  49247. };
  49248. // Methods
  49249. /**
  49250. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  49251. */
  49252. Skeleton.prototype.toString = function (fullDetails) {
  49253. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  49254. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49255. if (fullDetails) {
  49256. ret += ", Ranges: {";
  49257. var first = true;
  49258. for (var name_1 in this._ranges) {
  49259. if (first) {
  49260. ret += ", ";
  49261. first = false;
  49262. }
  49263. ret += name_1;
  49264. }
  49265. ret += "}";
  49266. }
  49267. return ret;
  49268. };
  49269. /**
  49270. * Get bone's index searching by name
  49271. * @param {string} name is bone's name to search for
  49272. * @return {number} Indice of the bone. Returns -1 if not found
  49273. */
  49274. Skeleton.prototype.getBoneIndexByName = function (name) {
  49275. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  49276. if (this.bones[boneIndex].name === name) {
  49277. return boneIndex;
  49278. }
  49279. }
  49280. return -1;
  49281. };
  49282. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  49283. // check name not already in use
  49284. if (!this._ranges[name]) {
  49285. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  49286. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  49287. if (this.bones[i].animations[0]) {
  49288. this.bones[i].animations[0].createRange(name, from, to);
  49289. }
  49290. }
  49291. }
  49292. };
  49293. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  49294. if (deleteFrames === void 0) { deleteFrames = true; }
  49295. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  49296. if (this.bones[i].animations[0]) {
  49297. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  49298. }
  49299. }
  49300. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  49301. };
  49302. Skeleton.prototype.getAnimationRange = function (name) {
  49303. return this._ranges[name];
  49304. };
  49305. /**
  49306. * Returns as an Array, all AnimationRanges defined on this skeleton
  49307. */
  49308. Skeleton.prototype.getAnimationRanges = function () {
  49309. var animationRanges = [];
  49310. var name;
  49311. var i = 0;
  49312. for (name in this._ranges) {
  49313. animationRanges[i] = this._ranges[name];
  49314. i++;
  49315. }
  49316. return animationRanges;
  49317. };
  49318. /**
  49319. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  49320. */
  49321. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  49322. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  49323. if (this._ranges[name] || !source.getAnimationRange(name)) {
  49324. return false;
  49325. }
  49326. var ret = true;
  49327. var frameOffset = this._getHighestAnimationFrame() + 1;
  49328. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  49329. var boneDict = {};
  49330. var sourceBones = source.bones;
  49331. var nBones;
  49332. var i;
  49333. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  49334. boneDict[sourceBones[i].name] = sourceBones[i];
  49335. }
  49336. if (this.bones.length !== sourceBones.length) {
  49337. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  49338. ret = false;
  49339. }
  49340. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  49341. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  49342. var boneName = this.bones[i].name;
  49343. var sourceBone = boneDict[boneName];
  49344. if (sourceBone) {
  49345. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  49346. }
  49347. else {
  49348. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  49349. ret = false;
  49350. }
  49351. }
  49352. // do not call createAnimationRange(), since it also is done to bones, which was already done
  49353. var range = source.getAnimationRange(name);
  49354. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  49355. return ret;
  49356. };
  49357. Skeleton.prototype.returnToRest = function () {
  49358. for (var index = 0; index < this.bones.length; index++) {
  49359. this.bones[index].returnToRest();
  49360. }
  49361. };
  49362. Skeleton.prototype._getHighestAnimationFrame = function () {
  49363. var ret = 0;
  49364. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  49365. if (this.bones[i].animations[0]) {
  49366. var highest = this.bones[i].animations[0].getHighestFrame();
  49367. if (ret < highest) {
  49368. ret = highest;
  49369. }
  49370. }
  49371. }
  49372. return ret;
  49373. };
  49374. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  49375. var range = this.getAnimationRange(name);
  49376. if (!range) {
  49377. return null;
  49378. }
  49379. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  49380. };
  49381. Skeleton.prototype._markAsDirty = function () {
  49382. this._isDirty = true;
  49383. };
  49384. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  49385. this._meshesWithPoseMatrix.push(mesh);
  49386. };
  49387. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  49388. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  49389. if (index > -1) {
  49390. this._meshesWithPoseMatrix.splice(index, 1);
  49391. }
  49392. };
  49393. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  49394. this.onBeforeComputeObservable.notifyObservers(this);
  49395. for (var index = 0; index < this.bones.length; index++) {
  49396. var bone = this.bones[index];
  49397. var parentBone = bone.getParent();
  49398. if (parentBone) {
  49399. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  49400. }
  49401. else {
  49402. if (initialSkinMatrix) {
  49403. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  49404. }
  49405. else {
  49406. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  49407. }
  49408. }
  49409. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  49410. }
  49411. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  49412. };
  49413. Skeleton.prototype.prepare = function () {
  49414. if (!this._isDirty) {
  49415. return;
  49416. }
  49417. if (this.needInitialSkinMatrix) {
  49418. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  49419. var mesh = this._meshesWithPoseMatrix[index];
  49420. var poseMatrix = mesh.getPoseMatrix();
  49421. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  49422. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  49423. }
  49424. if (this._synchronizedWithMesh !== mesh) {
  49425. this._synchronizedWithMesh = mesh;
  49426. // Prepare bones
  49427. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  49428. var bone = this.bones[boneIndex];
  49429. if (!bone.getParent()) {
  49430. var matrix = bone.getBaseMatrix();
  49431. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  49432. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  49433. }
  49434. }
  49435. }
  49436. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  49437. }
  49438. }
  49439. else {
  49440. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  49441. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  49442. }
  49443. this._computeTransformMatrices(this._transformMatrices, null);
  49444. }
  49445. this._isDirty = false;
  49446. this._scene._activeBones.addCount(this.bones.length, false);
  49447. };
  49448. Skeleton.prototype.getAnimatables = function () {
  49449. if (!this._animatables || this._animatables.length !== this.bones.length) {
  49450. this._animatables = [];
  49451. for (var index = 0; index < this.bones.length; index++) {
  49452. this._animatables.push(this.bones[index]);
  49453. }
  49454. }
  49455. return this._animatables;
  49456. };
  49457. Skeleton.prototype.clone = function (name, id) {
  49458. var result = new Skeleton(name, id || name, this._scene);
  49459. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  49460. for (var index = 0; index < this.bones.length; index++) {
  49461. var source = this.bones[index];
  49462. var parentBone = null;
  49463. if (source.getParent()) {
  49464. var parentIndex = this.bones.indexOf(source.getParent());
  49465. parentBone = result.bones[parentIndex];
  49466. }
  49467. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  49468. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  49469. }
  49470. if (this._ranges) {
  49471. result._ranges = {};
  49472. for (var rangeName in this._ranges) {
  49473. result._ranges[rangeName] = this._ranges[rangeName].clone();
  49474. }
  49475. }
  49476. this._isDirty = true;
  49477. return result;
  49478. };
  49479. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  49480. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  49481. this.bones.forEach(function (bone) {
  49482. bone.animations.forEach(function (animation) {
  49483. animation.enableBlending = true;
  49484. animation.blendingSpeed = blendingSpeed;
  49485. });
  49486. });
  49487. };
  49488. Skeleton.prototype.dispose = function () {
  49489. this._meshesWithPoseMatrix = [];
  49490. // Animations
  49491. this.getScene().stopAnimation(this);
  49492. // Remove from scene
  49493. this.getScene().removeSkeleton(this);
  49494. };
  49495. Skeleton.prototype.serialize = function () {
  49496. var serializationObject = {};
  49497. serializationObject.name = this.name;
  49498. serializationObject.id = this.id;
  49499. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  49500. serializationObject.bones = [];
  49501. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  49502. for (var index = 0; index < this.bones.length; index++) {
  49503. var bone = this.bones[index];
  49504. var serializedBone = {
  49505. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  49506. name: bone.name,
  49507. matrix: bone.getBaseMatrix().toArray(),
  49508. rest: bone.getRestPose().toArray()
  49509. };
  49510. serializationObject.bones.push(serializedBone);
  49511. if (bone.length) {
  49512. serializedBone.length = bone.length;
  49513. }
  49514. if (bone.animations && bone.animations.length > 0) {
  49515. serializedBone.animation = bone.animations[0].serialize();
  49516. }
  49517. serializationObject.ranges = [];
  49518. for (var name in this._ranges) {
  49519. var range = {};
  49520. range.name = name;
  49521. range.from = this._ranges[name].from;
  49522. range.to = this._ranges[name].to;
  49523. serializationObject.ranges.push(range);
  49524. }
  49525. }
  49526. return serializationObject;
  49527. };
  49528. Skeleton.Parse = function (parsedSkeleton, scene) {
  49529. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  49530. if (parsedSkeleton.dimensionsAtRest) {
  49531. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  49532. }
  49533. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  49534. var index;
  49535. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  49536. var parsedBone = parsedSkeleton.bones[index];
  49537. var parentBone = null;
  49538. if (parsedBone.parentBoneIndex > -1) {
  49539. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  49540. }
  49541. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  49542. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  49543. if (parsedBone.length) {
  49544. bone.length = parsedBone.length;
  49545. }
  49546. if (parsedBone.animation) {
  49547. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  49548. }
  49549. }
  49550. // placed after bones, so createAnimationRange can cascade down
  49551. if (parsedSkeleton.ranges) {
  49552. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  49553. var data = parsedSkeleton.ranges[index];
  49554. skeleton.createAnimationRange(data.name, data.from, data.to);
  49555. }
  49556. }
  49557. return skeleton;
  49558. };
  49559. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  49560. if (forceUpdate === void 0) { forceUpdate = false; }
  49561. var renderId = this._scene.getRenderId();
  49562. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  49563. this.bones[0].computeAbsoluteTransforms();
  49564. this._lastAbsoluteTransformsUpdateId = renderId;
  49565. }
  49566. };
  49567. Skeleton.prototype.getPoseMatrix = function () {
  49568. var poseMatrix;
  49569. if (this._meshesWithPoseMatrix.length > 0) {
  49570. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  49571. }
  49572. return poseMatrix;
  49573. };
  49574. return Skeleton;
  49575. }());
  49576. BABYLON.Skeleton = Skeleton;
  49577. })(BABYLON || (BABYLON = {}));
  49578. //# sourceMappingURL=babylon.skeleton.js.map
  49579. var BABYLON;
  49580. (function (BABYLON) {
  49581. var Internals;
  49582. (function (Internals) {
  49583. var FileFaceOrientation = (function () {
  49584. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  49585. this.name = name;
  49586. this.worldAxisForNormal = worldAxisForNormal;
  49587. this.worldAxisForFileX = worldAxisForFileX;
  49588. this.worldAxisForFileY = worldAxisForFileY;
  49589. }
  49590. return FileFaceOrientation;
  49591. }());
  49592. ;
  49593. /**
  49594. * Helper class dealing with the extraction of spherical polynomial dataArray
  49595. * from a cube map.
  49596. */
  49597. var CubeMapToSphericalPolynomialTools = (function () {
  49598. function CubeMapToSphericalPolynomialTools() {
  49599. }
  49600. /**
  49601. * Converts a cubemap to the according Spherical Polynomial data.
  49602. * This extracts the first 3 orders only as they are the only one used in the lighting.
  49603. *
  49604. * @param cubeInfo The Cube map to extract the information from.
  49605. * @return The Spherical Polynomial data.
  49606. */
  49607. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  49608. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  49609. var totalSolidAngle = 0.0;
  49610. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  49611. var du = 2.0 / cubeInfo.size;
  49612. var dv = du;
  49613. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  49614. var minUV = du * 0.5 - 1.0;
  49615. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  49616. var fileFace = this.FileFaces[faceIndex];
  49617. var dataArray = cubeInfo[fileFace.name];
  49618. var v = minUV;
  49619. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  49620. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  49621. // Because SP is still linear, so summation is fine in that basis.
  49622. for (var y = 0; y < cubeInfo.size; y++) {
  49623. var u = minUV;
  49624. for (var x = 0; x < cubeInfo.size; x++) {
  49625. // World direction (not normalised)
  49626. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  49627. worldDirection.normalize();
  49628. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  49629. if (1) {
  49630. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  49631. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  49632. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  49633. var color = new BABYLON.Color3(r, g, b);
  49634. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49635. }
  49636. else {
  49637. if (faceIndex == 0) {
  49638. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49639. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49640. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49641. }
  49642. else if (faceIndex == 1) {
  49643. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49644. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49645. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49646. }
  49647. else if (faceIndex == 2) {
  49648. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49649. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49650. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49651. }
  49652. else if (faceIndex == 3) {
  49653. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49654. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49655. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49656. }
  49657. else if (faceIndex == 4) {
  49658. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49659. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49660. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49661. }
  49662. else if (faceIndex == 5) {
  49663. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49664. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49665. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49666. }
  49667. 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]);
  49668. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49669. }
  49670. totalSolidAngle += deltaSolidAngle;
  49671. u += du;
  49672. }
  49673. v += dv;
  49674. }
  49675. }
  49676. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  49677. var correction = correctSolidAngle / totalSolidAngle;
  49678. sphericalHarmonics.scale(correction);
  49679. // Additionally scale by pi -- audit needed
  49680. sphericalHarmonics.scale(1.0 / Math.PI);
  49681. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  49682. };
  49683. return CubeMapToSphericalPolynomialTools;
  49684. }());
  49685. CubeMapToSphericalPolynomialTools.FileFaces = [
  49686. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  49687. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  49688. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  49689. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  49690. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  49691. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  49692. ];
  49693. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  49694. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49695. })(BABYLON || (BABYLON = {}));
  49696. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  49697. var BABYLON;
  49698. (function (BABYLON) {
  49699. var Internals;
  49700. (function (Internals) {
  49701. /**
  49702. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  49703. */
  49704. var PanoramaToCubeMapTools = (function () {
  49705. function PanoramaToCubeMapTools() {
  49706. }
  49707. /**
  49708. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  49709. *
  49710. * @param float32Array The source data.
  49711. * @param inputWidth The width of the input panorama.
  49712. * @param inputhHeight The height of the input panorama.
  49713. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  49714. * @return The cubemap data
  49715. */
  49716. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  49717. if (!float32Array) {
  49718. throw "ConvertPanoramaToCubemap: input cannot be null";
  49719. }
  49720. if (float32Array.length != inputWidth * inputHeight * 3) {
  49721. throw "ConvertPanoramaToCubemap: input size is wrong";
  49722. }
  49723. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  49724. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  49725. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  49726. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  49727. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  49728. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  49729. return {
  49730. front: textureFront,
  49731. back: textureBack,
  49732. left: textureLeft,
  49733. right: textureRight,
  49734. up: textureUp,
  49735. down: textureDown,
  49736. size: size
  49737. };
  49738. };
  49739. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  49740. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  49741. var textureArray = new Float32Array(buffer);
  49742. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  49743. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  49744. var dy = 1 / texSize;
  49745. var fy = 0;
  49746. for (var y = 0; y < texSize; y++) {
  49747. var xv1 = faceData[0];
  49748. var xv2 = faceData[2];
  49749. for (var x = 0; x < texSize; x++) {
  49750. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  49751. v.normalize();
  49752. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  49753. // 3 channels per pixels
  49754. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  49755. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  49756. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  49757. xv1 = xv1.add(rotDX1);
  49758. xv2 = xv2.add(rotDX2);
  49759. }
  49760. fy += dy;
  49761. }
  49762. return textureArray;
  49763. };
  49764. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  49765. var theta = Math.atan2(vDir.z, vDir.x);
  49766. var phi = Math.acos(vDir.y);
  49767. while (theta < -Math.PI)
  49768. theta += 2 * Math.PI;
  49769. while (theta > Math.PI)
  49770. theta -= 2 * Math.PI;
  49771. var dx = theta / Math.PI;
  49772. var dy = phi / Math.PI;
  49773. // recenter.
  49774. dx = dx * 0.5 + 0.5;
  49775. var px = Math.round(dx * inputWidth);
  49776. if (px < 0)
  49777. px = 0;
  49778. else if (px >= inputWidth)
  49779. px = inputWidth - 1;
  49780. var py = Math.round(dy * inputHeight);
  49781. if (py < 0)
  49782. py = 0;
  49783. else if (py >= inputHeight)
  49784. py = inputHeight - 1;
  49785. var inputY = (inputHeight - py - 1);
  49786. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  49787. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  49788. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  49789. return {
  49790. r: r,
  49791. g: g,
  49792. b: b
  49793. };
  49794. };
  49795. return PanoramaToCubeMapTools;
  49796. }());
  49797. PanoramaToCubeMapTools.FACE_FRONT = [
  49798. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  49799. new BABYLON.Vector3(1.0, -1.0, -1.0),
  49800. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  49801. new BABYLON.Vector3(1.0, 1.0, -1.0)
  49802. ];
  49803. PanoramaToCubeMapTools.FACE_BACK = [
  49804. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49805. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  49806. new BABYLON.Vector3(1.0, 1.0, 1.0),
  49807. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  49808. ];
  49809. PanoramaToCubeMapTools.FACE_RIGHT = [
  49810. new BABYLON.Vector3(1.0, -1.0, -1.0),
  49811. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49812. new BABYLON.Vector3(1.0, 1.0, -1.0),
  49813. new BABYLON.Vector3(1.0, 1.0, 1.0)
  49814. ];
  49815. PanoramaToCubeMapTools.FACE_LEFT = [
  49816. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  49817. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  49818. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  49819. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  49820. ];
  49821. PanoramaToCubeMapTools.FACE_DOWN = [
  49822. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  49823. new BABYLON.Vector3(1.0, 1.0, -1.0),
  49824. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  49825. new BABYLON.Vector3(1.0, 1.0, 1.0)
  49826. ];
  49827. PanoramaToCubeMapTools.FACE_UP = [
  49828. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  49829. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49830. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  49831. new BABYLON.Vector3(1.0, -1.0, -1.0)
  49832. ];
  49833. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  49834. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49835. })(BABYLON || (BABYLON = {}));
  49836. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  49837. var BABYLON;
  49838. (function (BABYLON) {
  49839. var Internals;
  49840. (function (Internals) {
  49841. ;
  49842. /**
  49843. * This groups tools to convert HDR texture to native colors array.
  49844. */
  49845. var HDRTools = (function () {
  49846. function HDRTools() {
  49847. }
  49848. HDRTools.Ldexp = function (mantissa, exponent) {
  49849. if (exponent > 1023) {
  49850. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  49851. }
  49852. if (exponent < -1074) {
  49853. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  49854. }
  49855. return mantissa * Math.pow(2, exponent);
  49856. };
  49857. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  49858. if (exponent > 0) {
  49859. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  49860. float32array[index + 0] = red * exponent;
  49861. float32array[index + 1] = green * exponent;
  49862. float32array[index + 2] = blue * exponent;
  49863. }
  49864. else {
  49865. float32array[index + 0] = 0;
  49866. float32array[index + 1] = 0;
  49867. float32array[index + 2] = 0;
  49868. }
  49869. };
  49870. HDRTools.readStringLine = function (uint8array, startIndex) {
  49871. var line = "";
  49872. var character = "";
  49873. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  49874. character = String.fromCharCode(uint8array[i]);
  49875. if (character == "\n") {
  49876. break;
  49877. }
  49878. line += character;
  49879. }
  49880. return line;
  49881. };
  49882. /**
  49883. * Reads header information from an RGBE texture stored in a native array.
  49884. * More information on this format are available here:
  49885. * https://en.wikipedia.org/wiki/RGBE_image_format
  49886. *
  49887. * @param uint8array The binary file stored in native array.
  49888. * @return The header information.
  49889. */
  49890. HDRTools.RGBE_ReadHeader = function (uint8array) {
  49891. var height = 0;
  49892. var width = 0;
  49893. var line = this.readStringLine(uint8array, 0);
  49894. if (line[0] != '#' || line[1] != '?') {
  49895. throw "Bad HDR Format.";
  49896. }
  49897. var endOfHeader = false;
  49898. var findFormat = false;
  49899. var lineIndex = 0;
  49900. do {
  49901. lineIndex += (line.length + 1);
  49902. line = this.readStringLine(uint8array, lineIndex);
  49903. if (line == "FORMAT=32-bit_rle_rgbe") {
  49904. findFormat = true;
  49905. }
  49906. else if (line.length == 0) {
  49907. endOfHeader = true;
  49908. }
  49909. } while (!endOfHeader);
  49910. if (!findFormat) {
  49911. throw "HDR Bad header format, unsupported FORMAT";
  49912. }
  49913. lineIndex += (line.length + 1);
  49914. line = this.readStringLine(uint8array, lineIndex);
  49915. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  49916. var match = sizeRegexp.exec(line);
  49917. // TODO. Support +Y and -X if needed.
  49918. if (match.length < 3) {
  49919. throw "HDR Bad header format, no size";
  49920. }
  49921. width = parseInt(match[2]);
  49922. height = parseInt(match[1]);
  49923. if (width < 8 || width > 0x7fff) {
  49924. throw "HDR Bad header format, unsupported size";
  49925. }
  49926. lineIndex += (line.length + 1);
  49927. return {
  49928. height: height,
  49929. width: width,
  49930. dataPosition: lineIndex
  49931. };
  49932. };
  49933. /**
  49934. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  49935. * This RGBE texture needs to store the information as a panorama.
  49936. *
  49937. * More information on this format are available here:
  49938. * https://en.wikipedia.org/wiki/RGBE_image_format
  49939. *
  49940. * @param buffer The binary file stored in an array buffer.
  49941. * @param size The expected size of the extracted cubemap.
  49942. * @return The Cube Map information.
  49943. */
  49944. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  49945. var uint8array = new Uint8Array(buffer);
  49946. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  49947. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  49948. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  49949. return cubeMapData;
  49950. };
  49951. /**
  49952. * Returns the pixels data extracted from an RGBE texture.
  49953. * This pixels will be stored left to right up to down in the R G B order in one array.
  49954. *
  49955. * More information on this format are available here:
  49956. * https://en.wikipedia.org/wiki/RGBE_image_format
  49957. *
  49958. * @param uint8array The binary file stored in an array buffer.
  49959. * @param hdrInfo The header information of the file.
  49960. * @return The pixels data in RGB right to left up to down order.
  49961. */
  49962. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  49963. // Keep for multi format supports.
  49964. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  49965. };
  49966. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  49967. var num_scanlines = hdrInfo.height;
  49968. var scanline_width = hdrInfo.width;
  49969. var a, b, c, d, count;
  49970. var dataIndex = hdrInfo.dataPosition;
  49971. var index = 0, endIndex = 0, i = 0;
  49972. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  49973. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  49974. // 3 channels of 4 bytes per pixel in float.
  49975. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  49976. var resultArray = new Float32Array(resultBuffer);
  49977. // read in each successive scanline
  49978. while (num_scanlines > 0) {
  49979. a = uint8array[dataIndex++];
  49980. b = uint8array[dataIndex++];
  49981. c = uint8array[dataIndex++];
  49982. d = uint8array[dataIndex++];
  49983. if (a != 2 || b != 2 || (c & 0x80)) {
  49984. // this file is not run length encoded
  49985. throw "HDR Bad header format, not RLE";
  49986. }
  49987. if (((c << 8) | d) != scanline_width) {
  49988. throw "HDR Bad header format, wrong scan line width";
  49989. }
  49990. index = 0;
  49991. // read each of the four channels for the scanline into the buffer
  49992. for (i = 0; i < 4; i++) {
  49993. endIndex = (i + 1) * scanline_width;
  49994. while (index < endIndex) {
  49995. a = uint8array[dataIndex++];
  49996. b = uint8array[dataIndex++];
  49997. if (a > 128) {
  49998. // a run of the same value
  49999. count = a - 128;
  50000. if ((count == 0) || (count > endIndex - index)) {
  50001. throw "HDR Bad Format, bad scanline data (run)";
  50002. }
  50003. while (count-- > 0) {
  50004. scanLineArray[index++] = b;
  50005. }
  50006. }
  50007. else {
  50008. // a non-run
  50009. count = a;
  50010. if ((count == 0) || (count > endIndex - index)) {
  50011. throw "HDR Bad Format, bad scanline data (non-run)";
  50012. }
  50013. scanLineArray[index++] = b;
  50014. if (--count > 0) {
  50015. for (var j = 0; j < count; j++) {
  50016. scanLineArray[index++] = uint8array[dataIndex++];
  50017. }
  50018. }
  50019. }
  50020. }
  50021. }
  50022. // now convert data from buffer into floats
  50023. for (i = 0; i < scanline_width; i++) {
  50024. a = scanLineArray[i];
  50025. b = scanLineArray[i + scanline_width];
  50026. c = scanLineArray[i + 2 * scanline_width];
  50027. d = scanLineArray[i + 3 * scanline_width];
  50028. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  50029. }
  50030. num_scanlines--;
  50031. }
  50032. return resultArray;
  50033. };
  50034. return HDRTools;
  50035. }());
  50036. Internals.HDRTools = HDRTools;
  50037. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50038. })(BABYLON || (BABYLON = {}));
  50039. //# sourceMappingURL=babylon.hdr.js.map
  50040. //_______________________________________________________________
  50041. // Extracted from CubeMapGen:
  50042. // https://code.google.com/archive/p/cubemapgen/
  50043. //
  50044. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50045. //_______________________________________________________________
  50046. var BABYLON;
  50047. (function (BABYLON) {
  50048. var Internals;
  50049. (function (Internals) {
  50050. /**
  50051. * The bounding box information used during the conversion process.
  50052. */
  50053. var CMGBoundinBox = (function () {
  50054. function CMGBoundinBox() {
  50055. this.min = new BABYLON.Vector3(0, 0, 0);
  50056. this.max = new BABYLON.Vector3(0, 0, 0);
  50057. this.clear();
  50058. }
  50059. CMGBoundinBox.prototype.clear = function () {
  50060. this.min.x = CMGBoundinBox.MAX;
  50061. this.min.y = CMGBoundinBox.MAX;
  50062. this.min.z = CMGBoundinBox.MAX;
  50063. this.max.x = CMGBoundinBox.MIN;
  50064. this.max.y = CMGBoundinBox.MIN;
  50065. this.max.z = CMGBoundinBox.MIN;
  50066. };
  50067. CMGBoundinBox.prototype.augment = function (x, y, z) {
  50068. this.min.x = Math.min(this.min.x, x);
  50069. this.min.y = Math.min(this.min.y, y);
  50070. this.min.z = Math.min(this.min.z, z);
  50071. this.max.x = Math.max(this.max.x, x);
  50072. this.max.y = Math.max(this.max.y, y);
  50073. this.max.z = Math.max(this.max.z, z);
  50074. };
  50075. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  50076. this.min.x = Math.max(this.min.x, x);
  50077. this.min.y = Math.max(this.min.y, y);
  50078. this.min.z = Math.max(this.min.z, z);
  50079. };
  50080. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  50081. this.max.x = Math.min(this.max.x, x);
  50082. this.max.y = Math.min(this.max.y, y);
  50083. this.max.z = Math.min(this.max.z, z);
  50084. };
  50085. CMGBoundinBox.prototype.empty = function () {
  50086. if ((this.min.x > this.max.y) ||
  50087. (this.min.y > this.max.y) ||
  50088. (this.min.z > this.max.y)) {
  50089. return true;
  50090. }
  50091. else {
  50092. return false;
  50093. }
  50094. };
  50095. return CMGBoundinBox;
  50096. }());
  50097. CMGBoundinBox.MAX = Number.MAX_VALUE;
  50098. CMGBoundinBox.MIN = Number.MIN_VALUE;
  50099. /**
  50100. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  50101. * required by the glossinees of a material.
  50102. *
  50103. * This only supports the cosine drop power as well as Warp fixup generation method.
  50104. *
  50105. * This is using the process from CubeMapGen described here:
  50106. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50107. */
  50108. var PMREMGenerator = (function () {
  50109. /**
  50110. * Constructor of the generator.
  50111. *
  50112. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  50113. * @param inputSize The size of the cubemap faces
  50114. * @param outputSize The size of the output cubemap faces
  50115. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  50116. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  50117. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  50118. * @param specularPower The max specular level of the desired cubemap
  50119. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  50120. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  50121. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  50122. */
  50123. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  50124. this.input = input;
  50125. this.inputSize = inputSize;
  50126. this.outputSize = outputSize;
  50127. this.maxNumMipLevels = maxNumMipLevels;
  50128. this.numChannels = numChannels;
  50129. this.isFloat = isFloat;
  50130. this.specularPower = specularPower;
  50131. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  50132. this.excludeBase = excludeBase;
  50133. this.fixup = fixup;
  50134. this._outputSurface = [];
  50135. this._numMipLevels = 0;
  50136. }
  50137. /**
  50138. * Launches the filter process and return the result.
  50139. *
  50140. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  50141. */
  50142. PMREMGenerator.prototype.filterCubeMap = function () {
  50143. // Init cubemap processor
  50144. this.init();
  50145. // Filters the cubemap
  50146. this.filterCubeMapMipChain();
  50147. // Returns the filtered mips.
  50148. return this._outputSurface;
  50149. };
  50150. PMREMGenerator.prototype.init = function () {
  50151. var i;
  50152. var j;
  50153. var mipLevelSize;
  50154. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  50155. if (this.maxNumMipLevels == 0) {
  50156. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  50157. }
  50158. //first miplevel size
  50159. mipLevelSize = this.outputSize;
  50160. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  50161. for (j = 0; j < this.maxNumMipLevels; j++) {
  50162. this._outputSurface.length++;
  50163. this._outputSurface[j] = [];
  50164. //Iterate over faces for output images
  50165. for (i = 0; i < 6; i++) {
  50166. this._outputSurface[j].length++;
  50167. // Initializes a new array for the output.
  50168. if (this.isFloat) {
  50169. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50170. }
  50171. else {
  50172. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50173. }
  50174. }
  50175. //next mip level is half size
  50176. mipLevelSize >>= 1;
  50177. this._numMipLevels++;
  50178. //terminate if mip chain becomes too small
  50179. if (mipLevelSize == 0) {
  50180. this.maxNumMipLevels = j;
  50181. return;
  50182. }
  50183. }
  50184. };
  50185. //--------------------------------------------------------------------------------------
  50186. //Cube map filtering and mip chain generation.
  50187. // the cube map filtereing is specified using a number of parameters:
  50188. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  50189. // indicates the region of the hemisphere to filter over for each tap.
  50190. //
  50191. // Note that the top mip level is also a filtered version of the original input images
  50192. // as well in order to create mip chains for diffuse environment illumination.
  50193. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  50194. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  50195. //
  50196. // Then the mip angle used to genreate the next level of the mip chain from the first level
  50197. // is a_InitialMipAngle
  50198. //
  50199. // The angle for the subsequent levels of the mip chain are specified by their parents
  50200. // filtering angle and a per-level scale and bias
  50201. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  50202. //
  50203. //--------------------------------------------------------------------------------------
  50204. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  50205. // First, take count of the lighting model to modify SpecularPower
  50206. // 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;
  50207. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  50208. //Cone angle start (for generating subsequent mip levels)
  50209. var currentSpecularPower = this.specularPower;
  50210. //Build filter lookup tables based on the source miplevel size
  50211. this.precomputeFilterLookupTables(this.inputSize);
  50212. // Note that we need to filter the first level before generating mipmap
  50213. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  50214. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  50215. // TODO : Write a function to copy and scale the base mipmap in output
  50216. // I am just lazy here and just put a high specular power value, and do some if.
  50217. if (this.excludeBase && (levelIndex == 0)) {
  50218. // 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).
  50219. currentSpecularPower = 100000.0;
  50220. }
  50221. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  50222. var srcCubeImage = this.input;
  50223. var dstCubeImage = this._outputSurface[levelIndex];
  50224. var dstSize = this.outputSize >> levelIndex;
  50225. // Compute required angle.
  50226. var angle = this.getBaseFilterAngle(currentSpecularPower);
  50227. // filter cube surfaces
  50228. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  50229. // fix seams
  50230. if (this.fixup) {
  50231. this.fixupCubeEdges(dstCubeImage, dstSize);
  50232. }
  50233. // Decrease the specular power to generate the mipmap chain
  50234. // TODO : Use another method for Exclude (see first comment at start of the function
  50235. if (this.excludeBase && (levelIndex == 0)) {
  50236. currentSpecularPower = this.specularPower;
  50237. }
  50238. currentSpecularPower *= this.cosinePowerDropPerMip;
  50239. }
  50240. };
  50241. //--------------------------------------------------------------------------------------
  50242. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  50243. // It allow to optimize the texel to access base on the specular power.
  50244. //--------------------------------------------------------------------------------------
  50245. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  50246. // We want to find the alpha such that:
  50247. // cos(alpha)^cosinePower = epsilon
  50248. // That's: acos(epsilon^(1/cosinePower))
  50249. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  50250. var angle = 180.0;
  50251. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  50252. angle *= 180.0 / Math.PI; // Convert to degree
  50253. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  50254. return angle;
  50255. };
  50256. //--------------------------------------------------------------------------------------
  50257. //Builds the following lookup tables prior to filtering:
  50258. // -normalizer cube map
  50259. // -tap weight lookup table
  50260. //
  50261. //--------------------------------------------------------------------------------------
  50262. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  50263. var srcTexelAngle;
  50264. var iCubeFace;
  50265. //clear pre-existing normalizer cube map
  50266. this._normCubeMap = [];
  50267. //Normalized vectors per cubeface and per-texel solid angle
  50268. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  50269. };
  50270. //--------------------------------------------------------------------------------------
  50271. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  50272. //
  50273. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  50274. //
  50275. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  50276. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  50277. // below
  50278. //--------------------------------------------------------------------------------------
  50279. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  50280. var iCubeFace;
  50281. var u;
  50282. var v;
  50283. //iterate over cube faces
  50284. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50285. //First three channels for norm cube, and last channel for solid angle
  50286. this._normCubeMap.push(new Float32Array(size * size * 4));
  50287. //fast texture walk, build normalizer cube map
  50288. var facesData = this.input[iCubeFace];
  50289. for (v = 0; v < size; v++) {
  50290. for (u = 0; u < size; u++) {
  50291. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  50292. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  50293. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  50294. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  50295. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  50296. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  50297. }
  50298. }
  50299. }
  50300. };
  50301. //--------------------------------------------------------------------------------------
  50302. // Convert cubemap face texel coordinates and face idx to 3D vector
  50303. // note the U and V coords are integer coords and range from 0 to size-1
  50304. // this routine can be used to generate a normalizer cube map
  50305. //--------------------------------------------------------------------------------------
  50306. // SL BEGIN
  50307. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  50308. var nvcU;
  50309. var nvcV;
  50310. var tempVec;
  50311. // Change from original AMD code
  50312. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50313. // + 0.5f is for texel center addressing
  50314. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  50315. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  50316. // warp fixup
  50317. if (fixup && size > 1) {
  50318. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  50319. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  50320. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  50321. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  50322. }
  50323. // Get current vector
  50324. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  50325. // U contribution
  50326. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50327. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  50328. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  50329. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  50330. // V contribution and Sum
  50331. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50332. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  50333. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  50334. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  50335. //add face axis
  50336. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  50337. PMREMGenerator._vectorTemp.x += faceAxis[0];
  50338. PMREMGenerator._vectorTemp.y += faceAxis[1];
  50339. PMREMGenerator._vectorTemp.z += faceAxis[2];
  50340. //normalize vector
  50341. PMREMGenerator._vectorTemp.normalize();
  50342. return PMREMGenerator._vectorTemp;
  50343. };
  50344. //--------------------------------------------------------------------------------------
  50345. // Convert 3D vector to cubemap face texel coordinates and face idx
  50346. // note the U and V coords are integer coords and range from 0 to size-1
  50347. // this routine can be used to generate a normalizer cube map
  50348. //
  50349. // returns face IDX and texel coords
  50350. //--------------------------------------------------------------------------------------
  50351. // SL BEGIN
  50352. /*
  50353. Mapping Texture Coordinates to Cube Map Faces
  50354. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  50355. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  50356. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  50357. map arrangement in Pixar's RenderMan package.
  50358. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  50359. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  50360. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  50361. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  50362. the major axis direction). The target column in the table below explains how the major axis direction
  50363. maps to the 2D image of a particular cube map target.
  50364. major axis
  50365. direction target sc tc ma
  50366. ---------- --------------------------------- --- --- ---
  50367. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  50368. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  50369. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  50370. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  50371. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  50372. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  50373. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  50374. an updated (s,t) is calculated as follows
  50375. s = ( sc/|ma| + 1 ) / 2
  50376. t = ( tc/|ma| + 1 ) / 2
  50377. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  50378. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  50379. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  50380. */
  50381. // Note this method return U and V in range from 0 to size-1
  50382. // SL END
  50383. // Store the information in vector3 for convenience (faceindex, u, v)
  50384. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  50385. var maxCoord;
  50386. var faceIdx;
  50387. //absolute value 3
  50388. var absX = Math.abs(x);
  50389. var absY = Math.abs(y);
  50390. var absZ = Math.abs(z);
  50391. if (absX >= absY && absX >= absZ) {
  50392. maxCoord = absX;
  50393. if (x >= 0) {
  50394. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  50395. }
  50396. else {
  50397. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50398. }
  50399. }
  50400. else if (absY >= absX && absY >= absZ) {
  50401. maxCoord = absY;
  50402. if (y >= 0) {
  50403. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50404. }
  50405. else {
  50406. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50407. }
  50408. }
  50409. else {
  50410. maxCoord = absZ;
  50411. if (z >= 0) {
  50412. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50413. }
  50414. else {
  50415. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50416. }
  50417. }
  50418. //divide through by max coord so face vector lies on cube face
  50419. var scale = 1 / maxCoord;
  50420. x *= scale;
  50421. y *= scale;
  50422. z *= scale;
  50423. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50424. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  50425. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50426. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  50427. // Modify original AMD code to return value from 0 to Size - 1
  50428. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  50429. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  50430. PMREMGenerator._vectorTemp.x = faceIdx;
  50431. PMREMGenerator._vectorTemp.y = u;
  50432. PMREMGenerator._vectorTemp.z = v;
  50433. return PMREMGenerator._vectorTemp;
  50434. };
  50435. //--------------------------------------------------------------------------------------
  50436. //Original code from Ignacio CastaÒo
  50437. // This formula is from Manne ÷hrstrˆm's thesis.
  50438. // Take two coordiantes in the range [-1, 1] that define a portion of a
  50439. // cube face and return the area of the projection of that portion on the
  50440. // surface of the sphere.
  50441. //--------------------------------------------------------------------------------------
  50442. PMREMGenerator.prototype.areaElement = function (x, y) {
  50443. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  50444. };
  50445. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  50446. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50447. // (+ 0.5f is for texel center addressing)
  50448. u = (2.0 * (u + 0.5) / size) - 1.0;
  50449. v = (2.0 * (v + 0.5) / size) - 1.0;
  50450. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  50451. var invResolution = 1.0 / size;
  50452. // U and V are the -1..1 texture coordinate on the current face.
  50453. // Get projected area for this texel
  50454. var x0 = u - invResolution;
  50455. var y0 = v - invResolution;
  50456. var x1 = u + invResolution;
  50457. var y1 = v + invResolution;
  50458. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  50459. return solidAngle;
  50460. };
  50461. //--------------------------------------------------------------------------------------
  50462. //The key to the speed of these filtering routines is to quickly define a per-face
  50463. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  50464. // Later these pixels are selectively processed based on their dot products to see if
  50465. // they reside within the filtering cone.
  50466. //
  50467. //This is done by computing the smallest per-texel angle to get a conservative estimate
  50468. // of the number of texels needed to be covered in width and height order to filter the
  50469. // region. the bounding box for the center taps face is defined first, and if the
  50470. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  50471. // defined next
  50472. //--------------------------------------------------------------------------------------
  50473. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  50474. // note that pixels within these regions may be rejected
  50475. // based on the anlge
  50476. var iCubeFace;
  50477. var u;
  50478. var v;
  50479. // bounding box per face to specify region to process
  50480. var filterExtents = [];
  50481. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50482. filterExtents.push(new CMGBoundinBox());
  50483. }
  50484. // min angle a src texel can cover (in degrees)
  50485. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  50486. // angle about center tap to define filter cone
  50487. // filter angle is 1/2 the cone angle
  50488. var filterAngle = filterConeAngle / 2.0;
  50489. //ensure filter angle is larger than a texel
  50490. if (filterAngle < srcTexelAngle) {
  50491. filterAngle = srcTexelAngle;
  50492. }
  50493. //ensure filter cone is always smaller than the hemisphere
  50494. if (filterAngle > 90.0) {
  50495. filterAngle = 90.0;
  50496. }
  50497. // the maximum number of texels in 1D the filter cone angle will cover
  50498. // used to determine bounding box size for filter extents
  50499. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  50500. // ensure conservative region always covers at least one texel
  50501. if (filterSize < 1) {
  50502. filterSize = 1;
  50503. }
  50504. // dotProdThresh threshold based on cone angle to determine whether or not taps
  50505. // reside within the cone angle
  50506. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  50507. // process required faces
  50508. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50509. //iterate over dst cube map face texel
  50510. for (v = 0; v < dstSize; v++) {
  50511. for (u = 0; u < dstSize; u++) {
  50512. //get center tap direction
  50513. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  50514. //clear old per-face filter extents
  50515. this.clearFilterExtents(filterExtents);
  50516. //define per-face filter extents
  50517. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  50518. //perform filtering of src faces using filter extents
  50519. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  50520. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  50521. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  50522. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  50523. }
  50524. }
  50525. }
  50526. };
  50527. //--------------------------------------------------------------------------------------
  50528. //Clear filter extents for the 6 cube map faces
  50529. //--------------------------------------------------------------------------------------
  50530. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  50531. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  50532. filterExtents[iCubeFaces].clear();
  50533. }
  50534. };
  50535. //--------------------------------------------------------------------------------------
  50536. //Define per-face bounding box filter extents
  50537. //
  50538. // These define conservative texel regions in each of the faces the filter can possibly
  50539. // process. When the pixels in the regions are actually processed, the dot product
  50540. // between the tap vector and the center tap vector is used to determine the weight of
  50541. // the tap and whether or not the tap is within the cone.
  50542. //
  50543. //--------------------------------------------------------------------------------------
  50544. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  50545. //neighboring face and bleed over amount, and width of BBOX for
  50546. // left, right, top, and bottom edges of this face
  50547. var bleedOverAmount = [0, 0, 0, 0];
  50548. var bleedOverBBoxMin = [0, 0, 0, 0];
  50549. var bleedOverBBoxMax = [0, 0, 0, 0];
  50550. var neighborFace;
  50551. var neighborEdge;
  50552. var oppositeFaceIdx;
  50553. //get face idx, and u, v info from center tap dir
  50554. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  50555. var faceIdx = result.x;
  50556. var u = result.y;
  50557. var v = result.z;
  50558. //define bbox size within face
  50559. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  50560. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  50561. filterExtents[faceIdx].clampMin(0, 0, 0);
  50562. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  50563. //u and v extent in face corresponding to center tap
  50564. var minU = filterExtents[faceIdx].min.x;
  50565. var minV = filterExtents[faceIdx].min.y;
  50566. var maxU = filterExtents[faceIdx].max.x;
  50567. var maxV = filterExtents[faceIdx].max.y;
  50568. //bleed over amounts for face across u=0 edge (left)
  50569. bleedOverAmount[0] = (bboxSize - u);
  50570. bleedOverBBoxMin[0] = minV;
  50571. bleedOverBBoxMax[0] = maxV;
  50572. //bleed over amounts for face across u=1 edge (right)
  50573. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  50574. bleedOverBBoxMin[1] = minV;
  50575. bleedOverBBoxMax[1] = maxV;
  50576. //bleed over to face across v=0 edge (up)
  50577. bleedOverAmount[2] = (bboxSize - v);
  50578. bleedOverBBoxMin[2] = minU;
  50579. bleedOverBBoxMax[2] = maxU;
  50580. //bleed over to face across v=1 edge (down)
  50581. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  50582. bleedOverBBoxMin[3] = minU;
  50583. bleedOverBBoxMax[3] = maxU;
  50584. //compute bleed over regions in neighboring faces
  50585. for (var i = 0; i < 4; i++) {
  50586. if (bleedOverAmount[i] > 0) {
  50587. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  50588. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  50589. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  50590. // be flipped: the cases are
  50591. // if a left edge mates with a left or bottom edge on the neighbor
  50592. // if a top edge mates with a top or right edge on the neighbor
  50593. // if a right edge mates with a right or top edge on the neighbor
  50594. // if a bottom edge mates with a bottom or left edge on the neighbor
  50595. //Seeing as the edges are enumerated as follows
  50596. // left =0
  50597. // right =1
  50598. // top =2
  50599. // bottom =3
  50600. //
  50601. // so if the edge enums are the same, or the sum of the enums == 3,
  50602. // the bbox needs to be flipped
  50603. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  50604. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  50605. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  50606. }
  50607. //The way the bounding box is extended onto the neighboring face
  50608. // depends on which edge of neighboring face abuts with this one
  50609. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  50610. case PMREMGenerator.CP_EDGE_LEFT:
  50611. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  50612. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50613. break;
  50614. case PMREMGenerator.CP_EDGE_RIGHT:
  50615. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  50616. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50617. break;
  50618. case PMREMGenerator.CP_EDGE_TOP:
  50619. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  50620. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  50621. break;
  50622. case PMREMGenerator.CP_EDGE_BOTTOM:
  50623. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  50624. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  50625. break;
  50626. }
  50627. //clamp filter extents in non-center tap faces to remain within surface
  50628. filterExtents[neighborFace].clampMin(0, 0, 0);
  50629. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  50630. }
  50631. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  50632. // from the center tap face, then process the opposite face entirely for now.
  50633. //Note that the cases in which this happens, what usually happens is that
  50634. // more than one edge bleeds onto the opposite face, and the bounding box
  50635. // encompasses the entire cube map face.
  50636. if (bleedOverAmount[i] > srcSize) {
  50637. //determine opposite face
  50638. switch (faceIdx) {
  50639. case PMREMGenerator.CP_FACE_X_POS:
  50640. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50641. break;
  50642. case PMREMGenerator.CP_FACE_X_NEG:
  50643. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  50644. break;
  50645. case PMREMGenerator.CP_FACE_Y_POS:
  50646. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50647. break;
  50648. case PMREMGenerator.CP_FACE_Y_NEG:
  50649. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50650. break;
  50651. case PMREMGenerator.CP_FACE_Z_POS:
  50652. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50653. break;
  50654. case PMREMGenerator.CP_FACE_Z_NEG:
  50655. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50656. break;
  50657. default:
  50658. break;
  50659. }
  50660. //just encompass entire face for now
  50661. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  50662. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  50663. }
  50664. }
  50665. };
  50666. //--------------------------------------------------------------------------------------
  50667. //ProcessFilterExtents
  50668. // Process bounding box in each cube face
  50669. //
  50670. //--------------------------------------------------------------------------------------
  50671. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  50672. //accumulators are 64-bit floats in order to have the precision needed
  50673. // over a summation of a large number of pixels
  50674. var dstAccum = [0, 0, 0, 0];
  50675. var weightAccum = 0;
  50676. var k = 0;
  50677. var nSrcChannels = this.numChannels;
  50678. // norm cube map and srcCubeMap have same face width
  50679. var faceWidth = srcSize;
  50680. //amount to add to pointer to move to next scanline in images
  50681. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  50682. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  50683. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  50684. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  50685. // iterate over cubefaces
  50686. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  50687. //if bbox is non empty
  50688. if (!filterExtents[iFaceIdx].empty()) {
  50689. var uStart = filterExtents[iFaceIdx].min.x;
  50690. var vStart = filterExtents[iFaceIdx].min.y;
  50691. var uEnd = filterExtents[iFaceIdx].max.x;
  50692. var vEnd = filterExtents[iFaceIdx].max.y;
  50693. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  50694. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  50695. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  50696. for (var v = vStart; v <= vEnd; v++) {
  50697. var normCubeRowWalk = 0;
  50698. var srcCubeRowWalk = 0;
  50699. for (var u = uStart; u <= uEnd; u++) {
  50700. //pointer to direction in cube map associated with texel
  50701. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  50702. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  50703. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  50704. //check dot product to see if texel is within cone
  50705. var tapDotProd = texelVectX * centerTapDir.x +
  50706. texelVectY * centerTapDir.y +
  50707. texelVectZ * centerTapDir.z;
  50708. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  50709. //solid angle stored in 4th channel of normalizer/solid angle cube map
  50710. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  50711. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  50712. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  50713. // so just adding one to specularpower do the trick.
  50714. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  50715. //iterate over channels
  50716. for (k = 0; k < nSrcChannels; k++) {
  50717. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  50718. srcCubeRowWalk++;
  50719. }
  50720. weightAccum += weight; //accumulate weight
  50721. }
  50722. else {
  50723. //step across source pixel
  50724. srcCubeRowWalk += nSrcChannels;
  50725. }
  50726. normCubeRowWalk += 4; // 4 channels per norm cube map.
  50727. }
  50728. startIndexNormCubeMap += normCubePitch;
  50729. startIndexSrcCubeMap += srcCubePitch;
  50730. }
  50731. }
  50732. }
  50733. //divide through by weights if weight is non zero
  50734. if (weightAccum != 0.0) {
  50735. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  50736. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  50737. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  50738. if (this.numChannels > 3) {
  50739. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  50740. }
  50741. }
  50742. else {
  50743. // otherwise sample nearest
  50744. // get face idx and u, v texel coordinate in face
  50745. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  50746. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  50747. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  50748. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  50749. if (this.numChannels > 3) {
  50750. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  50751. }
  50752. }
  50753. return PMREMGenerator._vectorTemp;
  50754. };
  50755. //--------------------------------------------------------------------------------------
  50756. // Fixup cube edges
  50757. //
  50758. // average texels on cube map faces across the edges
  50759. // WARP/BENT Method Only.
  50760. //--------------------------------------------------------------------------------------
  50761. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  50762. var k;
  50763. var j;
  50764. var i;
  50765. var iFace;
  50766. var iCorner = 0;
  50767. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  50768. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  50769. // note that if functionality to filter across the three texels for each corner, then
  50770. //indexed by corner and face idx. the array contains the face the start points belongs to.
  50771. var cornerPtr = [
  50772. [[], [], []],
  50773. [[], [], []],
  50774. [[], [], []],
  50775. [[], [], []],
  50776. [[], [], []],
  50777. [[], [], []],
  50778. [[], [], []],
  50779. [[], [], []]
  50780. ];
  50781. //if there is no fixup, or fixup width = 0, do nothing
  50782. if (cubeMapSize < 1) {
  50783. return;
  50784. }
  50785. //special case 1x1 cubemap, average face colors
  50786. if (cubeMapSize == 1) {
  50787. //iterate over channels
  50788. for (k = 0; k < this.numChannels; k++) {
  50789. var accum = 0.0;
  50790. //iterate over faces to accumulate face colors
  50791. for (iFace = 0; iFace < 6; iFace++) {
  50792. accum += cubeMap[iFace][k];
  50793. }
  50794. //compute average over 6 face colors
  50795. accum /= 6.0;
  50796. //iterate over faces to distribute face colors
  50797. for (iFace = 0; iFace < 6; iFace++) {
  50798. cubeMap[iFace][k] = accum;
  50799. }
  50800. }
  50801. return;
  50802. }
  50803. //iterate over faces to collect list of corner texel pointers
  50804. for (iFace = 0; iFace < 6; iFace++) {
  50805. //the 4 corner pointers for this face
  50806. faceCornerStartIndicies[0] = [iFace, 0];
  50807. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  50808. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  50809. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  50810. //iterate over face corners to collect cube corner pointers
  50811. for (iCorner = 0; iCorner < 4; iCorner++) {
  50812. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  50813. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  50814. cornerNumPtrs[corner]++;
  50815. }
  50816. }
  50817. //iterate over corners to average across corner tap values
  50818. for (iCorner = 0; iCorner < 8; iCorner++) {
  50819. for (k = 0; k < this.numChannels; k++) {
  50820. var cornerTapAccum = 0.0;
  50821. //iterate over corner texels and average results
  50822. for (i = 0; i < 3; i++) {
  50823. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  50824. }
  50825. //divide by 3 to compute average of corner tap values
  50826. cornerTapAccum *= (1.0 / 3.0);
  50827. //iterate over corner texels and average results
  50828. for (i = 0; i < 3; i++) {
  50829. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  50830. }
  50831. }
  50832. }
  50833. //iterate over the twelve edges of the cube to average across edges
  50834. for (i = 0; i < 12; i++) {
  50835. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  50836. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  50837. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  50838. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  50839. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  50840. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  50841. var edgeWalk = 0;
  50842. var neighborEdgeWalk = 0;
  50843. //Determine walking pointers based on edge type
  50844. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  50845. switch (edge) {
  50846. case PMREMGenerator.CP_EDGE_LEFT:
  50847. // no change to faceEdgeStartPtr
  50848. edgeWalk = this.numChannels * cubeMapSize;
  50849. break;
  50850. case PMREMGenerator.CP_EDGE_RIGHT:
  50851. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  50852. edgeWalk = this.numChannels * cubeMapSize;
  50853. break;
  50854. case PMREMGenerator.CP_EDGE_TOP:
  50855. // no change to faceEdgeStartPtr
  50856. edgeWalk = this.numChannels;
  50857. break;
  50858. case PMREMGenerator.CP_EDGE_BOTTOM:
  50859. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  50860. edgeWalk = this.numChannels;
  50861. break;
  50862. }
  50863. //For certain types of edge abutments, the neighbor edge walk needs to
  50864. // be flipped: the cases are
  50865. // if a left edge mates with a left or bottom edge on the neighbor
  50866. // if a top edge mates with a top or right edge on the neighbor
  50867. // if a right edge mates with a right or top edge on the neighbor
  50868. // if a bottom edge mates with a bottom or left edge on the neighbor
  50869. //Seeing as the edges are enumerated as follows
  50870. // left =0
  50871. // right =1
  50872. // top =2
  50873. // bottom =3
  50874. //
  50875. //If the edge enums are the same, or the sum of the enums == 3,
  50876. // the neighbor edge walk needs to be flipped
  50877. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  50878. switch (neighborEdge) {
  50879. case PMREMGenerator.CP_EDGE_LEFT:
  50880. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  50881. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  50882. break;
  50883. case PMREMGenerator.CP_EDGE_RIGHT:
  50884. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  50885. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  50886. break;
  50887. case PMREMGenerator.CP_EDGE_TOP:
  50888. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  50889. neighborEdgeWalk = -this.numChannels;
  50890. break;
  50891. case PMREMGenerator.CP_EDGE_BOTTOM:
  50892. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  50893. neighborEdgeWalk = -this.numChannels;
  50894. break;
  50895. }
  50896. }
  50897. else {
  50898. //swapped direction neighbor edge walk
  50899. switch (neighborEdge) {
  50900. case PMREMGenerator.CP_EDGE_LEFT:
  50901. //no change to neighborEdgeStartPtr for this case since it points
  50902. // to the upper left corner already
  50903. neighborEdgeWalk = this.numChannels * cubeMapSize;
  50904. break;
  50905. case PMREMGenerator.CP_EDGE_RIGHT:
  50906. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  50907. neighborEdgeWalk = this.numChannels * cubeMapSize;
  50908. break;
  50909. case PMREMGenerator.CP_EDGE_TOP:
  50910. //no change to neighborEdgeStartPtr for this case since it points
  50911. // to the upper left corner already
  50912. neighborEdgeWalk = this.numChannels;
  50913. break;
  50914. case PMREMGenerator.CP_EDGE_BOTTOM:
  50915. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  50916. neighborEdgeWalk = this.numChannels;
  50917. break;
  50918. }
  50919. }
  50920. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  50921. //nearby neighborhood
  50922. //step ahead one texel on edge
  50923. edgeStartIndex += edgeWalk;
  50924. neighborEdgeStartIndex += neighborEdgeWalk;
  50925. // note that this loop does not process the corner texels, since they have already been
  50926. // averaged across faces across earlier
  50927. for (j = 1; j < (cubeMapSize - 1); j++) {
  50928. //for each set of taps along edge, average them
  50929. // and rewrite the results into the edges
  50930. for (k = 0; k < this.numChannels; k++) {
  50931. var edgeTap = cubeMap[face][edgeStartIndex + k];
  50932. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  50933. //compute average of tap intensity values
  50934. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  50935. //propagate average of taps to edge taps
  50936. cubeMap[face][edgeStartIndex + k] = avgTap;
  50937. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  50938. }
  50939. edgeStartIndex += edgeWalk;
  50940. neighborEdgeStartIndex += neighborEdgeWalk;
  50941. }
  50942. }
  50943. };
  50944. return PMREMGenerator;
  50945. }());
  50946. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  50947. PMREMGenerator.CP_UDIR = 0;
  50948. PMREMGenerator.CP_VDIR = 1;
  50949. PMREMGenerator.CP_FACEAXIS = 2;
  50950. //used to index cube faces
  50951. PMREMGenerator.CP_FACE_X_POS = 0;
  50952. PMREMGenerator.CP_FACE_X_NEG = 1;
  50953. PMREMGenerator.CP_FACE_Y_POS = 2;
  50954. PMREMGenerator.CP_FACE_Y_NEG = 3;
  50955. PMREMGenerator.CP_FACE_Z_POS = 4;
  50956. PMREMGenerator.CP_FACE_Z_NEG = 5;
  50957. //used to index image edges
  50958. // NOTE.. the actual number corresponding to the edge is important
  50959. // do not change these, or the code will break
  50960. //
  50961. // CP_EDGE_LEFT is u = 0
  50962. // CP_EDGE_RIGHT is u = width-1
  50963. // CP_EDGE_TOP is v = 0
  50964. // CP_EDGE_BOTTOM is v = height-1
  50965. PMREMGenerator.CP_EDGE_LEFT = 0;
  50966. PMREMGenerator.CP_EDGE_RIGHT = 1;
  50967. PMREMGenerator.CP_EDGE_TOP = 2;
  50968. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  50969. //corners of CUBE map (P or N specifys if it corresponds to the
  50970. // positive or negative direction each of X, Y, and Z
  50971. PMREMGenerator.CP_CORNER_NNN = 0;
  50972. PMREMGenerator.CP_CORNER_NNP = 1;
  50973. PMREMGenerator.CP_CORNER_NPN = 2;
  50974. PMREMGenerator.CP_CORNER_NPP = 3;
  50975. PMREMGenerator.CP_CORNER_PNN = 4;
  50976. PMREMGenerator.CP_CORNER_PNP = 5;
  50977. PMREMGenerator.CP_CORNER_PPN = 6;
  50978. PMREMGenerator.CP_CORNER_PPP = 7;
  50979. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  50980. //3x2 matrices that map cube map indexing vectors in 3d
  50981. // (after face selection and divide through by the
  50982. // _ABSOLUTE VALUE_ of the max coord)
  50983. // into NVC space
  50984. //Note this currently assumes the D3D cube face ordering and orientation
  50985. PMREMGenerator._sgFace2DMapping = [
  50986. //XPOS face
  50987. [[0, 0, -1],
  50988. [0, -1, 0],
  50989. [1, 0, 0]],
  50990. //XNEG face
  50991. [[0, 0, 1],
  50992. [0, -1, 0],
  50993. [-1, 0, 0]],
  50994. //YPOS face
  50995. [[1, 0, 0],
  50996. [0, 0, 1],
  50997. [0, 1, 0]],
  50998. //YNEG face
  50999. [[1, 0, 0],
  51000. [0, 0, -1],
  51001. [0, -1, 0]],
  51002. //ZPOS face
  51003. [[1, 0, 0],
  51004. [0, -1, 0],
  51005. [0, 0, 1]],
  51006. //ZNEG face
  51007. [[-1, 0, 0],
  51008. [0, -1, 0],
  51009. [0, 0, -1]],
  51010. ];
  51011. //------------------------------------------------------------------------------
  51012. // D3D cube map face specification
  51013. // mapping from 3D x,y,z cube map lookup coordinates
  51014. // to 2D within face u,v coordinates
  51015. //
  51016. // --------------------> U direction
  51017. // | (within-face texture space)
  51018. // | _____
  51019. // | | |
  51020. // | | +Y |
  51021. // | _____|_____|_____ _____
  51022. // | | | | | |
  51023. // | | -X | +Z | +X | -Z |
  51024. // | |_____|_____|_____|_____|
  51025. // | | |
  51026. // | | -Y |
  51027. // | |_____|
  51028. // |
  51029. // v V direction
  51030. // (within-face texture space)
  51031. //------------------------------------------------------------------------------
  51032. //Information about neighbors and how texture coorrdinates change across faces
  51033. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  51034. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  51035. //Note this currently assumes the D3D cube face ordering and orientation
  51036. PMREMGenerator._sgCubeNgh = [
  51037. //XPOS face
  51038. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51039. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51040. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51041. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  51042. //XNEG face
  51043. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51044. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  51045. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  51046. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  51047. //YPOS face
  51048. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51049. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51050. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51051. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  51052. //YNEG face
  51053. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51054. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51055. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51056. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  51057. //ZPOS face
  51058. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51059. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51060. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51061. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  51062. //ZNEG face
  51063. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51064. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51065. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  51066. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  51067. ];
  51068. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  51069. // this table is used to average over the edges.
  51070. PMREMGenerator._sgCubeEdgeList = [
  51071. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51072. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51073. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51074. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51075. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51076. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51077. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51078. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51079. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  51080. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51081. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51082. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  51083. ];
  51084. //Information about which of the 8 cube corners are correspond to the
  51085. // the 4 corners in each cube face
  51086. // the order is upper left, upper right, lower left, lower right
  51087. PMREMGenerator._sgCubeCornerList = [
  51088. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  51089. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  51090. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  51091. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  51092. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  51093. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  51094. ];
  51095. Internals.PMREMGenerator = PMREMGenerator;
  51096. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51097. })(BABYLON || (BABYLON = {}));
  51098. //# sourceMappingURL=babylon.pmremgenerator.js.map
  51099. var BABYLON;
  51100. (function (BABYLON) {
  51101. /**
  51102. * This represents a texture coming from an HDR input.
  51103. *
  51104. * The only supported format is currently panorama picture stored in RGBE format.
  51105. * Example of such files can be found on HDRLib: http://hdrlib.com/
  51106. */
  51107. var HDRCubeTexture = (function (_super) {
  51108. __extends(HDRCubeTexture, _super);
  51109. /**
  51110. * Instantiates an HDRTexture from the following parameters.
  51111. *
  51112. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  51113. * @param scene The scene the texture will be used in
  51114. * @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.
  51115. * @param noMipmap Forces to not generate the mipmap if true
  51116. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  51117. * @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)
  51118. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  51119. */
  51120. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  51121. if (noMipmap === void 0) { noMipmap = false; }
  51122. if (generateHarmonics === void 0) { generateHarmonics = true; }
  51123. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  51124. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  51125. if (onLoad === void 0) { onLoad = null; }
  51126. if (onError === void 0) { onError = null; }
  51127. var _this = _super.call(this, scene) || this;
  51128. _this._useInGammaSpace = false;
  51129. _this._generateHarmonics = true;
  51130. _this._isBABYLONPreprocessed = false;
  51131. _this._onLoad = null;
  51132. _this._onError = null;
  51133. /**
  51134. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  51135. */
  51136. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51137. /**
  51138. * The spherical polynomial data extracted from the texture.
  51139. */
  51140. _this.sphericalPolynomial = null;
  51141. /**
  51142. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  51143. * This is usefull at run time to apply the good shader.
  51144. */
  51145. _this.isPMREM = false;
  51146. if (!url) {
  51147. return _this;
  51148. }
  51149. _this.name = url;
  51150. _this.url = url;
  51151. _this.hasAlpha = false;
  51152. _this.isCube = true;
  51153. _this._textureMatrix = BABYLON.Matrix.Identity();
  51154. _this._onLoad = onLoad;
  51155. _this._onError = onError;
  51156. if (size) {
  51157. _this._isBABYLONPreprocessed = false;
  51158. _this._noMipmap = noMipmap;
  51159. _this._size = size;
  51160. _this._useInGammaSpace = useInGammaSpace;
  51161. _this._usePMREMGenerator = usePMREMGenerator &&
  51162. scene.getEngine().getCaps().textureLOD &&
  51163. _this.getScene().getEngine().getCaps().textureFloat &&
  51164. !_this._useInGammaSpace;
  51165. }
  51166. else {
  51167. _this._isBABYLONPreprocessed = true;
  51168. _this._noMipmap = false;
  51169. _this._useInGammaSpace = false;
  51170. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  51171. _this.getScene().getEngine().getCaps().textureFloat &&
  51172. !_this._useInGammaSpace;
  51173. }
  51174. _this.isPMREM = _this._usePMREMGenerator;
  51175. _this._texture = _this._getFromCache(url, _this._noMipmap);
  51176. if (!_this._texture) {
  51177. if (!scene.useDelayedTextureLoading) {
  51178. _this.loadTexture();
  51179. }
  51180. else {
  51181. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51182. }
  51183. }
  51184. return _this;
  51185. }
  51186. /**
  51187. * Occurs when the file is a preprocessed .babylon.hdr file.
  51188. */
  51189. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  51190. var _this = this;
  51191. var mipLevels = 0;
  51192. var floatArrayView = null;
  51193. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  51194. var mips = [];
  51195. var startIndex = 30;
  51196. for (var level = 0; level < mipLevels; level++) {
  51197. mips.push([]);
  51198. // Fill each pixel of the mip level.
  51199. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  51200. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51201. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  51202. mips[level].push(faceData);
  51203. startIndex += faceSize;
  51204. }
  51205. }
  51206. return mips;
  51207. } : null;
  51208. var callback = function (buffer) {
  51209. // Create Native Array Views
  51210. var intArrayView = new Int32Array(buffer);
  51211. floatArrayView = new Float32Array(buffer);
  51212. // Fill header.
  51213. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  51214. _this._size = intArrayView[1]; // CubeMap max mip face size.
  51215. // Update Texture Information.
  51216. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  51217. // Fill polynomial information.
  51218. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  51219. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  51220. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  51221. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  51222. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  51223. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  51224. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  51225. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  51226. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  51227. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  51228. // Fill pixel data.
  51229. mipLevels = intArrayView[29]; // Number of mip levels.
  51230. var startIndex = 30;
  51231. var data = [];
  51232. var faceSize = Math.pow(_this._size, 2) * 3;
  51233. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51234. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  51235. startIndex += faceSize;
  51236. }
  51237. var results = [];
  51238. var byteArray = null;
  51239. // Push each faces.
  51240. for (var k = 0; k < 6; k++) {
  51241. var dataFace = null;
  51242. // If special cases.
  51243. if (!mipmapGenerator) {
  51244. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  51245. dataFace = data[j];
  51246. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51247. // 3 channels of 1 bytes per pixel in bytes.
  51248. var byteBuffer = new ArrayBuffer(faceSize);
  51249. byteArray = new Uint8Array(byteBuffer);
  51250. }
  51251. for (var i = 0; i < _this._size * _this._size; i++) {
  51252. // Put in gamma space if requested.
  51253. if (_this._useInGammaSpace) {
  51254. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51255. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51256. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51257. }
  51258. // Convert to int texture for fallback.
  51259. if (byteArray) {
  51260. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51261. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51262. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51263. // May use luminance instead if the result is not accurate.
  51264. var max = Math.max(Math.max(r, g), b);
  51265. if (max > 255) {
  51266. var scale = 255 / max;
  51267. r *= scale;
  51268. g *= scale;
  51269. b *= scale;
  51270. }
  51271. byteArray[(i * 3) + 0] = r;
  51272. byteArray[(i * 3) + 1] = g;
  51273. byteArray[(i * 3) + 2] = b;
  51274. }
  51275. }
  51276. }
  51277. else {
  51278. dataFace = data[k];
  51279. }
  51280. // Fill the array accordingly.
  51281. if (byteArray) {
  51282. results.push(byteArray);
  51283. }
  51284. else {
  51285. results.push(dataFace);
  51286. }
  51287. }
  51288. return results;
  51289. };
  51290. 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);
  51291. };
  51292. /**
  51293. * Occurs when the file is raw .hdr file.
  51294. */
  51295. HDRCubeTexture.prototype.loadHDRTexture = function () {
  51296. var _this = this;
  51297. var callback = function (buffer) {
  51298. // Extract the raw linear data.
  51299. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  51300. // Generate harmonics if needed.
  51301. if (_this._generateHarmonics) {
  51302. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  51303. }
  51304. var results = [];
  51305. var byteArray = null;
  51306. // Push each faces.
  51307. for (var j = 0; j < 6; j++) {
  51308. // Create uintarray fallback.
  51309. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51310. // 3 channels of 1 bytes per pixel in bytes.
  51311. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  51312. byteArray = new Uint8Array(byteBuffer);
  51313. }
  51314. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  51315. // If special cases.
  51316. if (_this._useInGammaSpace || byteArray) {
  51317. for (var i = 0; i < _this._size * _this._size; i++) {
  51318. // Put in gamma space if requested.
  51319. if (_this._useInGammaSpace) {
  51320. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51321. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51322. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51323. }
  51324. // Convert to int texture for fallback.
  51325. if (byteArray) {
  51326. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51327. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51328. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51329. // May use luminance instead if the result is not accurate.
  51330. var max = Math.max(Math.max(r, g), b);
  51331. if (max > 255) {
  51332. var scale = 255 / max;
  51333. r *= scale;
  51334. g *= scale;
  51335. b *= scale;
  51336. }
  51337. byteArray[(i * 3) + 0] = r;
  51338. byteArray[(i * 3) + 1] = g;
  51339. byteArray[(i * 3) + 2] = b;
  51340. }
  51341. }
  51342. }
  51343. if (byteArray) {
  51344. results.push(byteArray);
  51345. }
  51346. else {
  51347. results.push(dataFace);
  51348. }
  51349. }
  51350. return results;
  51351. };
  51352. var mipmapGenerator = null;
  51353. if (!this._noMipmap &&
  51354. this._usePMREMGenerator) {
  51355. mipmapGenerator = function (data) {
  51356. // Custom setup of the generator matching with the PBR shader values.
  51357. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  51358. return generator.filterCubeMap();
  51359. };
  51360. }
  51361. 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);
  51362. };
  51363. /**
  51364. * Starts the loading process of the texture.
  51365. */
  51366. HDRCubeTexture.prototype.loadTexture = function () {
  51367. if (this._isBABYLONPreprocessed) {
  51368. this.loadBabylonTexture();
  51369. }
  51370. else {
  51371. this.loadHDRTexture();
  51372. }
  51373. };
  51374. HDRCubeTexture.prototype.clone = function () {
  51375. var size = this._isBABYLONPreprocessed ? null : this._size;
  51376. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  51377. // Base texture
  51378. newTexture.level = this.level;
  51379. newTexture.wrapU = this.wrapU;
  51380. newTexture.wrapV = this.wrapV;
  51381. newTexture.coordinatesIndex = this.coordinatesIndex;
  51382. newTexture.coordinatesMode = this.coordinatesMode;
  51383. return newTexture;
  51384. };
  51385. // Methods
  51386. HDRCubeTexture.prototype.delayLoad = function () {
  51387. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51388. return;
  51389. }
  51390. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51391. this._texture = this._getFromCache(this.url, this._noMipmap);
  51392. if (!this._texture) {
  51393. this.loadTexture();
  51394. }
  51395. };
  51396. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  51397. return this._textureMatrix;
  51398. };
  51399. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51400. var texture = null;
  51401. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  51402. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  51403. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  51404. texture.name = parsedTexture.name;
  51405. texture.hasAlpha = parsedTexture.hasAlpha;
  51406. texture.level = parsedTexture.level;
  51407. texture.coordinatesMode = parsedTexture.coordinatesMode;
  51408. }
  51409. return texture;
  51410. };
  51411. HDRCubeTexture.prototype.serialize = function () {
  51412. if (!this.name) {
  51413. return null;
  51414. }
  51415. var serializationObject = {};
  51416. serializationObject.name = this.name;
  51417. serializationObject.hasAlpha = this.hasAlpha;
  51418. serializationObject.isCube = true;
  51419. serializationObject.level = this.level;
  51420. serializationObject.size = this._size;
  51421. serializationObject.coordinatesMode = this.coordinatesMode;
  51422. serializationObject.useInGammaSpace = this._useInGammaSpace;
  51423. serializationObject.generateHarmonics = this._generateHarmonics;
  51424. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  51425. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  51426. serializationObject.customType = "BABYLON.HDRCubeTexture";
  51427. serializationObject.noMipmap = this._noMipmap;
  51428. return serializationObject;
  51429. };
  51430. /**
  51431. * Saves as a file the data contained in the texture in a binary format.
  51432. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51433. * as the spherical used in the lighting.
  51434. * @param url The HDR file url.
  51435. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51436. * @param onError Method called if any error happens during download.
  51437. * @return The packed binary data.
  51438. */
  51439. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  51440. if (onError === void 0) { onError = null; }
  51441. var callback = function (buffer) {
  51442. var data = new Blob([buffer], { type: 'application/octet-stream' });
  51443. // Returns a URL you can use as a href.
  51444. var objUrl = window.URL.createObjectURL(data);
  51445. // Simulates a link to it and click to dowload.
  51446. var a = document.createElement("a");
  51447. document.body.appendChild(a);
  51448. a.style.display = "none";
  51449. a.href = objUrl;
  51450. a.download = "envmap.babylon.hdr";
  51451. a.click();
  51452. };
  51453. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  51454. };
  51455. /**
  51456. * Serializes the data contained in the texture in a binary format.
  51457. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51458. * as the spherical used in the lighting.
  51459. * @param url The HDR file url.
  51460. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51461. * @param onError Method called if any error happens during download.
  51462. * @return The packed binary data.
  51463. */
  51464. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  51465. if (onError === void 0) { onError = null; }
  51466. // Needs the url tho create the texture.
  51467. if (!url) {
  51468. return null;
  51469. }
  51470. // Check Power of two size.
  51471. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  51472. return null;
  51473. }
  51474. var getDataCallback = function (dataBuffer) {
  51475. // Extract the raw linear data.
  51476. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  51477. // Generate harmonics if needed.
  51478. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  51479. // Generate seamless faces
  51480. var mipGeneratorArray = [];
  51481. // Data are known to be in +X +Y +Z -X -Y -Z
  51482. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  51483. mipGeneratorArray.push(cubeData.right); // +X
  51484. mipGeneratorArray.push(cubeData.left); // -X
  51485. mipGeneratorArray.push(cubeData.up); // +Y
  51486. mipGeneratorArray.push(cubeData.down); // -Y
  51487. mipGeneratorArray.push(cubeData.front); // +Z
  51488. mipGeneratorArray.push(cubeData.back); // -Z
  51489. // Custom setup of the generator matching with the PBR shader values.
  51490. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  51491. var mippedData = generator.filterCubeMap();
  51492. // Compute required byte length.
  51493. var byteLength = 1 * 4; // Raw Data Version int32.
  51494. byteLength += 4; // CubeMap max mip face size int32.
  51495. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  51496. // Add data size.
  51497. byteLength += 4; // Number of mip levels int32.
  51498. for (var level = 0; level < mippedData.length; level++) {
  51499. var mipSize = size >> level;
  51500. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  51501. }
  51502. // Prepare binary structure.
  51503. var buffer = new ArrayBuffer(byteLength);
  51504. var intArrayView = new Int32Array(buffer);
  51505. var floatArrayView = new Float32Array(buffer);
  51506. // Fill header.
  51507. intArrayView[0] = 1; // Version 1.
  51508. intArrayView[1] = size; // CubeMap max mip face size.
  51509. // Fill polynomial information.
  51510. sphericalPolynomial.x.toArray(floatArrayView, 2);
  51511. sphericalPolynomial.y.toArray(floatArrayView, 5);
  51512. sphericalPolynomial.z.toArray(floatArrayView, 8);
  51513. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  51514. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  51515. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  51516. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  51517. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  51518. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  51519. // Fill pixel data.
  51520. intArrayView[29] = mippedData.length; // Number of mip levels.
  51521. var startIndex = 30;
  51522. for (var level = 0; level < mippedData.length; level++) {
  51523. // Fill each pixel of the mip level.
  51524. var faceSize = Math.pow(size >> level, 2) * 3;
  51525. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51526. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  51527. startIndex += faceSize;
  51528. }
  51529. }
  51530. // Callback.
  51531. callback(buffer);
  51532. };
  51533. // Download and process.
  51534. BABYLON.Tools.LoadFile(url, function (data) {
  51535. getDataCallback(data);
  51536. }, null, null, true, onError);
  51537. };
  51538. return HDRCubeTexture;
  51539. }(BABYLON.BaseTexture));
  51540. HDRCubeTexture._facesMapping = [
  51541. "right",
  51542. "up",
  51543. "front",
  51544. "left",
  51545. "down",
  51546. "back"
  51547. ];
  51548. BABYLON.HDRCubeTexture = HDRCubeTexture;
  51549. })(BABYLON || (BABYLON = {}));
  51550. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  51551. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  51552. // Huge respect for a such great lib.
  51553. // Earcut license:
  51554. // Copyright (c) 2016, Mapbox
  51555. //
  51556. // Permission to use, copy, modify, and/or distribute this software for any purpose
  51557. // with or without fee is hereby granted, provided that the above copyright notice
  51558. // and this permission notice appear in all copies.
  51559. //
  51560. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  51561. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  51562. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  51563. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  51564. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  51565. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  51566. // THIS SOFTWARE.
  51567. var Earcut;
  51568. (function (Earcut) {
  51569. /**
  51570. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  51571. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  51572. * @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).
  51573. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  51574. */
  51575. function earcut(data, holeIndices, dim) {
  51576. dim = dim || 2;
  51577. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  51578. if (!outerNode)
  51579. return triangles;
  51580. var minX, minY, maxX, maxY, x, y, size;
  51581. if (hasHoles)
  51582. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  51583. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  51584. if (data.length > 80 * dim) {
  51585. minX = maxX = data[0];
  51586. minY = maxY = data[1];
  51587. for (var i = dim; i < outerLen; i += dim) {
  51588. x = data[i];
  51589. y = data[i + 1];
  51590. if (x < minX)
  51591. minX = x;
  51592. if (y < minY)
  51593. minY = y;
  51594. if (x > maxX)
  51595. maxX = x;
  51596. if (y > maxY)
  51597. maxY = y;
  51598. }
  51599. // minX, minY and size are later used to transform coords into integers for z-order calculation
  51600. size = Math.max(maxX - minX, maxY - minY);
  51601. }
  51602. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  51603. return triangles;
  51604. }
  51605. Earcut.earcut = earcut;
  51606. // create a circular doubly linked list from polygon points in the specified winding order
  51607. function linkedList(data, start, end, dim, clockwise) {
  51608. var i, last;
  51609. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  51610. for (i = start; i < end; i += dim)
  51611. last = insertNode(i, data[i], data[i + 1], last);
  51612. }
  51613. else {
  51614. for (i = end - dim; i >= start; i -= dim)
  51615. last = insertNode(i, data[i], data[i + 1], last);
  51616. }
  51617. if (last && equals(last, last.next)) {
  51618. removeNode(last);
  51619. last = last.next;
  51620. }
  51621. return last;
  51622. }
  51623. // eliminate colinear or duplicate points
  51624. function filterPoints(start, end) {
  51625. if (!start)
  51626. return start;
  51627. if (!end)
  51628. end = start;
  51629. var p = start, again;
  51630. do {
  51631. again = false;
  51632. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  51633. removeNode(p);
  51634. p = end = p.prev;
  51635. if (p === p.next)
  51636. return null;
  51637. again = true;
  51638. }
  51639. else {
  51640. p = p.next;
  51641. }
  51642. } while (again || p !== end);
  51643. return end;
  51644. }
  51645. // main ear slicing loop which triangulates a polygon (given as a linked list)
  51646. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  51647. if (!ear)
  51648. return;
  51649. // interlink polygon nodes in z-order
  51650. if (!pass && size)
  51651. indexCurve(ear, minX, minY, size);
  51652. var stop = ear, prev, next;
  51653. // iterate through ears, slicing them one by one
  51654. while (ear.prev !== ear.next) {
  51655. prev = ear.prev;
  51656. next = ear.next;
  51657. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  51658. // cut off the triangle
  51659. triangles.push(prev.i / dim);
  51660. triangles.push(ear.i / dim);
  51661. triangles.push(next.i / dim);
  51662. removeNode(ear);
  51663. // skipping the next vertice leads to less sliver triangles
  51664. ear = next.next;
  51665. stop = next.next;
  51666. continue;
  51667. }
  51668. ear = next;
  51669. // if we looped through the whole remaining polygon and can't find any more ears
  51670. if (ear === stop) {
  51671. // try filtering points and slicing again
  51672. if (!pass) {
  51673. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  51674. // if this didn't work, try curing all small self-intersections locally
  51675. }
  51676. else if (pass === 1) {
  51677. ear = cureLocalIntersections(ear, triangles, dim);
  51678. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  51679. // as a last resort, try splitting the remaining polygon into two
  51680. }
  51681. else if (pass === 2) {
  51682. splitEarcut(ear, triangles, dim, minX, minY, size);
  51683. }
  51684. break;
  51685. }
  51686. }
  51687. }
  51688. // check whether a polygon node forms a valid ear with adjacent nodes
  51689. function isEar(ear) {
  51690. var a = ear.prev, b = ear, c = ear.next;
  51691. if (area(a, b, c) >= 0)
  51692. return false; // reflex, can't be an ear
  51693. // now make sure we don't have other points inside the potential ear
  51694. var p = ear.next.next;
  51695. while (p !== ear.prev) {
  51696. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51697. area(p.prev, p, p.next) >= 0)
  51698. return false;
  51699. p = p.next;
  51700. }
  51701. return true;
  51702. }
  51703. function isEarHashed(ear, minX, minY, size) {
  51704. var a = ear.prev, b = ear, c = ear.next;
  51705. if (area(a, b, c) >= 0)
  51706. return false; // reflex, can't be an ear
  51707. // triangle bbox; min & max are calculated like this for speed
  51708. 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);
  51709. // z-order range for the current triangle bbox;
  51710. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  51711. // first look for points inside the triangle in increasing z-order
  51712. var p = ear.nextZ;
  51713. while (p && p.z <= maxZ) {
  51714. if (p !== ear.prev &&
  51715. p !== ear.next &&
  51716. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51717. area(p.prev, p, p.next) >= 0)
  51718. return false;
  51719. p = p.nextZ;
  51720. }
  51721. // then look for points in decreasing z-order
  51722. p = ear.prevZ;
  51723. while (p && p.z >= minZ) {
  51724. if (p !== ear.prev &&
  51725. p !== ear.next &&
  51726. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51727. area(p.prev, p, p.next) >= 0)
  51728. return false;
  51729. p = p.prevZ;
  51730. }
  51731. return true;
  51732. }
  51733. // go through all polygon nodes and cure small local self-intersections
  51734. function cureLocalIntersections(start, triangles, dim) {
  51735. var p = start;
  51736. do {
  51737. var a = p.prev, b = p.next.next;
  51738. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  51739. triangles.push(a.i / dim);
  51740. triangles.push(p.i / dim);
  51741. triangles.push(b.i / dim);
  51742. // remove two nodes involved
  51743. removeNode(p);
  51744. removeNode(p.next);
  51745. p = start = b;
  51746. }
  51747. p = p.next;
  51748. } while (p !== start);
  51749. return p;
  51750. }
  51751. // try splitting polygon into two and triangulate them independently
  51752. function splitEarcut(start, triangles, dim, minX, minY, size) {
  51753. // look for a valid diagonal that divides the polygon into two
  51754. var a = start;
  51755. do {
  51756. var b = a.next.next;
  51757. while (b !== a.prev) {
  51758. if (a.i !== b.i && isValidDiagonal(a, b)) {
  51759. // split the polygon in two by the diagonal
  51760. var c = splitPolygon(a, b);
  51761. // filter colinear points around the cuts
  51762. a = filterPoints(a, a.next);
  51763. c = filterPoints(c, c.next);
  51764. // run earcut on each half
  51765. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  51766. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  51767. return;
  51768. }
  51769. b = b.next;
  51770. }
  51771. a = a.next;
  51772. } while (a !== start);
  51773. }
  51774. // link every hole into the outer loop, producing a single-ring polygon without holes
  51775. function eliminateHoles(data, holeIndices, outerNode, dim) {
  51776. var queue = [], i, len, start, end, list;
  51777. for (i = 0, len = holeIndices.length; i < len; i++) {
  51778. start = holeIndices[i] * dim;
  51779. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  51780. list = linkedList(data, start, end, dim, false);
  51781. if (list === list.next)
  51782. list.steiner = true;
  51783. queue.push(getLeftmost(list));
  51784. }
  51785. queue.sort(compareX);
  51786. // process holes from left to right
  51787. for (i = 0; i < queue.length; i++) {
  51788. eliminateHole(queue[i], outerNode);
  51789. outerNode = filterPoints(outerNode, outerNode.next);
  51790. }
  51791. return outerNode;
  51792. }
  51793. function compareX(a, b) {
  51794. return a.x - b.x;
  51795. }
  51796. // find a bridge between vertices that connects hole with an outer ring and and link it
  51797. function eliminateHole(hole, outerNode) {
  51798. outerNode = findHoleBridge(hole, outerNode);
  51799. if (outerNode) {
  51800. var b = splitPolygon(outerNode, hole);
  51801. filterPoints(b, b.next);
  51802. }
  51803. }
  51804. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  51805. function findHoleBridge(hole, outerNode) {
  51806. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  51807. // find a segment intersected by a ray from the hole's leftmost point to the left;
  51808. // segment's endpoint with lesser x will be potential connection point
  51809. do {
  51810. if (hy <= p.y && hy >= p.next.y) {
  51811. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  51812. if (x <= hx && x > qx) {
  51813. qx = x;
  51814. if (x === hx) {
  51815. if (hy === p.y)
  51816. return p;
  51817. if (hy === p.next.y)
  51818. return p.next;
  51819. }
  51820. m = p.x < p.next.x ? p : p.next;
  51821. }
  51822. }
  51823. p = p.next;
  51824. } while (p !== outerNode);
  51825. if (!m)
  51826. return null;
  51827. if (hx === qx)
  51828. return m.prev; // hole touches outer segment; pick lower endpoint
  51829. // look for points inside the triangle of hole point, segment intersection and endpoint;
  51830. // if there are no points found, we have a valid connection;
  51831. // otherwise choose the point of the minimum angle with the ray as connection point
  51832. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  51833. p = m.next;
  51834. while (p !== stop) {
  51835. if (hx >= p.x &&
  51836. p.x >= mx &&
  51837. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  51838. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  51839. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  51840. m = p;
  51841. tanMin = tan;
  51842. }
  51843. }
  51844. p = p.next;
  51845. }
  51846. return m;
  51847. }
  51848. // interlink polygon nodes in z-order
  51849. function indexCurve(start, minX, minY, size) {
  51850. var p = start;
  51851. do {
  51852. if (p.z === null)
  51853. p.z = zOrder(p.x, p.y, minX, minY, size);
  51854. p.prevZ = p.prev;
  51855. p.nextZ = p.next;
  51856. p = p.next;
  51857. } while (p !== start);
  51858. p.prevZ.nextZ = null;
  51859. p.prevZ = null;
  51860. sortLinked(p);
  51861. }
  51862. // Simon Tatham's linked list merge sort algorithm
  51863. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  51864. function sortLinked(list) {
  51865. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  51866. do {
  51867. p = list;
  51868. list = null;
  51869. tail = null;
  51870. numMerges = 0;
  51871. while (p) {
  51872. numMerges++;
  51873. q = p;
  51874. pSize = 0;
  51875. for (i = 0; i < inSize; i++) {
  51876. pSize++;
  51877. q = q.nextZ;
  51878. if (!q)
  51879. break;
  51880. }
  51881. qSize = inSize;
  51882. while (pSize > 0 || (qSize > 0 && q)) {
  51883. if (pSize === 0) {
  51884. e = q;
  51885. q = q.nextZ;
  51886. qSize--;
  51887. }
  51888. else if (qSize === 0 || !q) {
  51889. e = p;
  51890. p = p.nextZ;
  51891. pSize--;
  51892. }
  51893. else if (p.z <= q.z) {
  51894. e = p;
  51895. p = p.nextZ;
  51896. pSize--;
  51897. }
  51898. else {
  51899. e = q;
  51900. q = q.nextZ;
  51901. qSize--;
  51902. }
  51903. if (tail)
  51904. tail.nextZ = e;
  51905. else
  51906. list = e;
  51907. e.prevZ = tail;
  51908. tail = e;
  51909. }
  51910. p = q;
  51911. }
  51912. tail.nextZ = null;
  51913. inSize *= 2;
  51914. } while (numMerges > 1);
  51915. return list;
  51916. }
  51917. // z-order of a point given coords and size of the data bounding box
  51918. function zOrder(x, y, minX, minY, size) {
  51919. // coords are transformed into non-negative 15-bit integer range
  51920. x = 32767 * (x - minX) / size;
  51921. y = 32767 * (y - minY) / size;
  51922. x = (x | (x << 8)) & 0x00FF00FF;
  51923. x = (x | (x << 4)) & 0x0F0F0F0F;
  51924. x = (x | (x << 2)) & 0x33333333;
  51925. x = (x | (x << 1)) & 0x55555555;
  51926. y = (y | (y << 8)) & 0x00FF00FF;
  51927. y = (y | (y << 4)) & 0x0F0F0F0F;
  51928. y = (y | (y << 2)) & 0x33333333;
  51929. y = (y | (y << 1)) & 0x55555555;
  51930. return x | (y << 1);
  51931. }
  51932. // find the leftmost node of a polygon ring
  51933. function getLeftmost(start) {
  51934. var p = start, leftmost = start;
  51935. do {
  51936. if (p.x < leftmost.x)
  51937. leftmost = p;
  51938. p = p.next;
  51939. } while (p !== start);
  51940. return leftmost;
  51941. }
  51942. // check if a point lies within a convex triangle
  51943. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  51944. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  51945. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  51946. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  51947. }
  51948. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  51949. function isValidDiagonal(a, b) {
  51950. return a.next.i !== b.i &&
  51951. a.prev.i !== b.i &&
  51952. !intersectsPolygon(a, b) &&
  51953. locallyInside(a, b) &&
  51954. locallyInside(b, a) &&
  51955. middleInside(a, b);
  51956. }
  51957. // signed area of a triangle
  51958. function area(p, q, r) {
  51959. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  51960. }
  51961. // check if two points are equal
  51962. function equals(p1, p2) {
  51963. return p1.x === p2.x && p1.y === p2.y;
  51964. }
  51965. // check if two segments intersect
  51966. function intersects(p1, q1, p2, q2) {
  51967. if ((equals(p1, q1) && equals(p2, q2)) ||
  51968. (equals(p1, q2) && equals(p2, q1)))
  51969. return true;
  51970. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  51971. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  51972. }
  51973. // check if a polygon diagonal intersects any polygon segments
  51974. function intersectsPolygon(a, b) {
  51975. var p = a;
  51976. do {
  51977. if (p.i !== a.i &&
  51978. p.next.i !== a.i &&
  51979. p.i !== b.i &&
  51980. p.next.i !== b.i &&
  51981. intersects(p, p.next, a, b))
  51982. return true;
  51983. p = p.next;
  51984. } while (p !== a);
  51985. return false;
  51986. }
  51987. // check if a polygon diagonal is locally inside the polygon
  51988. function locallyInside(a, b) {
  51989. return area(a.prev, a, a.next) < 0
  51990. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  51991. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  51992. }
  51993. // check if the middle point of a polygon diagonal is inside the polygon
  51994. function middleInside(a, b) {
  51995. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  51996. do {
  51997. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  51998. inside = !inside;
  51999. p = p.next;
  52000. } while (p !== a);
  52001. return inside;
  52002. }
  52003. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  52004. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  52005. function splitPolygon(a, b) {
  52006. 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;
  52007. a.next = b;
  52008. b.prev = a;
  52009. a2.next = an;
  52010. an.prev = a2;
  52011. b2.next = a2;
  52012. a2.prev = b2;
  52013. bp.next = b2;
  52014. b2.prev = bp;
  52015. return b2;
  52016. }
  52017. // create a node and optionally link it with previous one (in a circular doubly linked list)
  52018. function insertNode(i, x, y, last) {
  52019. var p = new Node(i, x, y);
  52020. if (!last) {
  52021. p.prev = p;
  52022. p.next = p;
  52023. }
  52024. else {
  52025. p.next = last.next;
  52026. p.prev = last;
  52027. last.next.prev = p;
  52028. last.next = p;
  52029. }
  52030. return p;
  52031. }
  52032. function removeNode(p) {
  52033. p.next.prev = p.prev;
  52034. p.prev.next = p.next;
  52035. if (p.prevZ)
  52036. p.prevZ.nextZ = p.nextZ;
  52037. if (p.nextZ)
  52038. p.nextZ.prevZ = p.prevZ;
  52039. }
  52040. function Node(i, x, y) {
  52041. // vertice index in coordinates array
  52042. this.i = i;
  52043. // vertex coordinates
  52044. this.x = x;
  52045. this.y = y;
  52046. // previous and next vertice nodes in a polygon ring
  52047. this.prev = null;
  52048. this.next = null;
  52049. // z-order curve value
  52050. this.z = null;
  52051. // previous and next nodes in z-order
  52052. this.prevZ = null;
  52053. this.nextZ = null;
  52054. // indicates whether this is a steiner point
  52055. this.steiner = false;
  52056. }
  52057. /**
  52058. * return a percentage difference between the polygon area and its triangulation area;
  52059. * used to verify correctness of triangulation
  52060. */
  52061. function deviation(data, holeIndices, dim, triangles) {
  52062. var hasHoles = holeIndices && holeIndices.length;
  52063. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  52064. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  52065. if (hasHoles) {
  52066. for (var i = 0, len = holeIndices.length; i < len; i++) {
  52067. var start = holeIndices[i] * dim;
  52068. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  52069. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  52070. }
  52071. }
  52072. var trianglesArea = 0;
  52073. for (i = 0; i < triangles.length; i += 3) {
  52074. var a = triangles[i] * dim;
  52075. var b = triangles[i + 1] * dim;
  52076. var c = triangles[i + 2] * dim;
  52077. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  52078. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  52079. }
  52080. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  52081. }
  52082. Earcut.deviation = deviation;
  52083. ;
  52084. function signedArea(data, start, end, dim) {
  52085. var sum = 0;
  52086. for (var i = start, j = end - dim; i < end; i += dim) {
  52087. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  52088. j = i;
  52089. }
  52090. return sum;
  52091. }
  52092. /**
  52093. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  52094. */
  52095. function flatten(data) {
  52096. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  52097. for (var i = 0; i < data.length; i++) {
  52098. for (var j = 0; j < data[i].length; j++) {
  52099. for (var d = 0; d < dim; d++)
  52100. result.vertices.push(data[i][j][d]);
  52101. }
  52102. if (i > 0) {
  52103. holeIndex += data[i - 1].length;
  52104. result.holes.push(holeIndex);
  52105. }
  52106. }
  52107. return result;
  52108. }
  52109. Earcut.flatten = flatten;
  52110. ;
  52111. })(Earcut || (Earcut = {}));
  52112. //# sourceMappingURL=babylon.earcut.js.map
  52113. /// <reference path="..\Math\babylon.math.ts" />
  52114. var BABYLON;
  52115. (function (BABYLON) {
  52116. var IndexedVector2 = (function (_super) {
  52117. __extends(IndexedVector2, _super);
  52118. function IndexedVector2(original, index) {
  52119. var _this = _super.call(this, original.x, original.y) || this;
  52120. _this.index = index;
  52121. return _this;
  52122. }
  52123. return IndexedVector2;
  52124. }(BABYLON.Vector2));
  52125. var PolygonPoints = (function () {
  52126. function PolygonPoints() {
  52127. this.elements = new Array();
  52128. }
  52129. PolygonPoints.prototype.add = function (originalPoints) {
  52130. var _this = this;
  52131. var result = new Array();
  52132. originalPoints.forEach(function (point) {
  52133. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  52134. var newPoint = new IndexedVector2(point, _this.elements.length);
  52135. result.push(newPoint);
  52136. _this.elements.push(newPoint);
  52137. }
  52138. });
  52139. return result;
  52140. };
  52141. PolygonPoints.prototype.computeBounds = function () {
  52142. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  52143. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  52144. this.elements.forEach(function (point) {
  52145. // x
  52146. if (point.x < lmin.x) {
  52147. lmin.x = point.x;
  52148. }
  52149. else if (point.x > lmax.x) {
  52150. lmax.x = point.x;
  52151. }
  52152. // y
  52153. if (point.y < lmin.y) {
  52154. lmin.y = point.y;
  52155. }
  52156. else if (point.y > lmax.y) {
  52157. lmax.y = point.y;
  52158. }
  52159. });
  52160. return {
  52161. min: lmin,
  52162. max: lmax,
  52163. width: lmax.x - lmin.x,
  52164. height: lmax.y - lmin.y
  52165. };
  52166. };
  52167. return PolygonPoints;
  52168. }());
  52169. var Polygon = (function () {
  52170. function Polygon() {
  52171. }
  52172. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  52173. return [
  52174. new BABYLON.Vector2(xmin, ymin),
  52175. new BABYLON.Vector2(xmax, ymin),
  52176. new BABYLON.Vector2(xmax, ymax),
  52177. new BABYLON.Vector2(xmin, ymax)
  52178. ];
  52179. };
  52180. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  52181. if (cx === void 0) { cx = 0; }
  52182. if (cy === void 0) { cy = 0; }
  52183. if (numberOfSides === void 0) { numberOfSides = 32; }
  52184. var result = new Array();
  52185. var angle = 0;
  52186. var increment = (Math.PI * 2) / numberOfSides;
  52187. for (var i = 0; i < numberOfSides; i++) {
  52188. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  52189. angle -= increment;
  52190. }
  52191. return result;
  52192. };
  52193. Polygon.Parse = function (input) {
  52194. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  52195. var i, result = [];
  52196. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  52197. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  52198. }
  52199. return result;
  52200. };
  52201. Polygon.StartingAt = function (x, y) {
  52202. return BABYLON.Path2.StartingAt(x, y);
  52203. };
  52204. return Polygon;
  52205. }());
  52206. BABYLON.Polygon = Polygon;
  52207. var PolygonMeshBuilder = (function () {
  52208. function PolygonMeshBuilder(name, contours, scene) {
  52209. this._points = new PolygonPoints();
  52210. this._outlinepoints = new PolygonPoints();
  52211. this._holes = [];
  52212. this._epoints = new Array();
  52213. this._eholes = new Array();
  52214. this._name = name;
  52215. this._scene = scene;
  52216. var points;
  52217. if (contours instanceof BABYLON.Path2) {
  52218. points = contours.getPoints();
  52219. }
  52220. else {
  52221. points = contours;
  52222. }
  52223. this._addToepoint(points);
  52224. this._points.add(points);
  52225. this._outlinepoints.add(points);
  52226. }
  52227. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  52228. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  52229. var p = points_1[_i];
  52230. this._epoints.push(p.x, p.y);
  52231. }
  52232. };
  52233. PolygonMeshBuilder.prototype.addHole = function (hole) {
  52234. this._points.add(hole);
  52235. var holepoints = new PolygonPoints();
  52236. holepoints.add(hole);
  52237. this._holes.push(holepoints);
  52238. this._eholes.push(this._epoints.length / 2);
  52239. this._addToepoint(hole);
  52240. return this;
  52241. };
  52242. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  52243. var _this = this;
  52244. if (updatable === void 0) { updatable = false; }
  52245. var result = new BABYLON.Mesh(this._name, this._scene);
  52246. var normals = [];
  52247. var positions = [];
  52248. var uvs = [];
  52249. var bounds = this._points.computeBounds();
  52250. this._points.elements.forEach(function (p) {
  52251. normals.push(0, 1.0, 0);
  52252. positions.push(p.x, 0, p.y);
  52253. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  52254. });
  52255. var indices = [];
  52256. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  52257. for (var i = 0; i < res.length; i++) {
  52258. indices.push(res[i]);
  52259. }
  52260. if (depth > 0) {
  52261. var positionscount = (positions.length / 3); //get the current pointcount
  52262. this._points.elements.forEach(function (p) {
  52263. normals.push(0, -1.0, 0);
  52264. positions.push(p.x, -depth, p.y);
  52265. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  52266. });
  52267. var totalCount = indices.length;
  52268. for (var i = 0; i < totalCount; i += 3) {
  52269. var i0 = indices[i + 0];
  52270. var i1 = indices[i + 1];
  52271. var i2 = indices[i + 2];
  52272. indices.push(i2 + positionscount);
  52273. indices.push(i1 + positionscount);
  52274. indices.push(i0 + positionscount);
  52275. }
  52276. //Add the sides
  52277. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  52278. this._holes.forEach(function (hole) {
  52279. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  52280. });
  52281. }
  52282. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  52283. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  52284. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  52285. result.setIndices(indices);
  52286. return result;
  52287. };
  52288. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  52289. var StartIndex = positions.length / 3;
  52290. var ulength = 0;
  52291. for (var i = 0; i < points.elements.length; i++) {
  52292. var p = points.elements[i];
  52293. var p1;
  52294. if ((i + 1) > points.elements.length - 1) {
  52295. p1 = points.elements[0];
  52296. }
  52297. else {
  52298. p1 = points.elements[i + 1];
  52299. }
  52300. positions.push(p.x, 0, p.y);
  52301. positions.push(p.x, -depth, p.y);
  52302. positions.push(p1.x, 0, p1.y);
  52303. positions.push(p1.x, -depth, p1.y);
  52304. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  52305. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  52306. var v3 = v2.subtract(v1);
  52307. var v4 = new BABYLON.Vector3(0, 1, 0);
  52308. var vn = BABYLON.Vector3.Cross(v3, v4);
  52309. vn = vn.normalize();
  52310. uvs.push(ulength / bounds.width, 0);
  52311. uvs.push(ulength / bounds.width, 1);
  52312. ulength += v3.length();
  52313. uvs.push((ulength / bounds.width), 0);
  52314. uvs.push((ulength / bounds.width), 1);
  52315. if (!flip) {
  52316. normals.push(-vn.x, -vn.y, -vn.z);
  52317. normals.push(-vn.x, -vn.y, -vn.z);
  52318. normals.push(-vn.x, -vn.y, -vn.z);
  52319. normals.push(-vn.x, -vn.y, -vn.z);
  52320. indices.push(StartIndex);
  52321. indices.push(StartIndex + 1);
  52322. indices.push(StartIndex + 2);
  52323. indices.push(StartIndex + 1);
  52324. indices.push(StartIndex + 3);
  52325. indices.push(StartIndex + 2);
  52326. }
  52327. else {
  52328. normals.push(vn.x, vn.y, vn.z);
  52329. normals.push(vn.x, vn.y, vn.z);
  52330. normals.push(vn.x, vn.y, vn.z);
  52331. normals.push(vn.x, vn.y, vn.z);
  52332. indices.push(StartIndex);
  52333. indices.push(StartIndex + 2);
  52334. indices.push(StartIndex + 1);
  52335. indices.push(StartIndex + 1);
  52336. indices.push(StartIndex + 2);
  52337. indices.push(StartIndex + 3);
  52338. }
  52339. StartIndex += 4;
  52340. }
  52341. ;
  52342. };
  52343. return PolygonMeshBuilder;
  52344. }());
  52345. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  52346. })(BABYLON || (BABYLON = {}));
  52347. //# sourceMappingURL=babylon.polygonMesh.js.map
  52348. var BABYLON;
  52349. (function (BABYLON) {
  52350. // Unique ID when we import meshes from Babylon to CSG
  52351. var currentCSGMeshId = 0;
  52352. // # class Vertex
  52353. // Represents a vertex of a polygon. Use your own vertex class instead of this
  52354. // one to provide additional features like texture coordinates and vertex
  52355. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  52356. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  52357. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  52358. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  52359. // is not used anywhere else.
  52360. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  52361. var Vertex = (function () {
  52362. function Vertex(pos, normal, uv) {
  52363. this.pos = pos;
  52364. this.normal = normal;
  52365. this.uv = uv;
  52366. }
  52367. Vertex.prototype.clone = function () {
  52368. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  52369. };
  52370. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  52371. // orientation of a polygon is flipped.
  52372. Vertex.prototype.flip = function () {
  52373. this.normal = this.normal.scale(-1);
  52374. };
  52375. // Create a new vertex between this vertex and `other` by linearly
  52376. // interpolating all properties using a parameter of `t`. Subclasses should
  52377. // override this to interpolate additional properties.
  52378. Vertex.prototype.interpolate = function (other, t) {
  52379. 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));
  52380. };
  52381. return Vertex;
  52382. }());
  52383. // # class Plane
  52384. // Represents a plane in 3D space.
  52385. var Plane = (function () {
  52386. function Plane(normal, w) {
  52387. this.normal = normal;
  52388. this.w = w;
  52389. }
  52390. Plane.FromPoints = function (a, b, c) {
  52391. var v0 = c.subtract(a);
  52392. var v1 = b.subtract(a);
  52393. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  52394. return null;
  52395. }
  52396. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  52397. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  52398. };
  52399. Plane.prototype.clone = function () {
  52400. return new Plane(this.normal.clone(), this.w);
  52401. };
  52402. Plane.prototype.flip = function () {
  52403. this.normal.scaleInPlace(-1);
  52404. this.w = -this.w;
  52405. };
  52406. // Split `polygon` by this plane if needed, then put the polygon or polygon
  52407. // fragments in the appropriate lists. Coplanar polygons go into either
  52408. // `coplanarFront` or `coplanarBack` depending on their orientation with
  52409. // respect to this plane. Polygons in front or in back of this plane go into
  52410. // either `front` or `back`.
  52411. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  52412. var COPLANAR = 0;
  52413. var FRONT = 1;
  52414. var BACK = 2;
  52415. var SPANNING = 3;
  52416. // Classify each point as well as the entire polygon into one of the above
  52417. // four classes.
  52418. var polygonType = 0;
  52419. var types = [];
  52420. var i;
  52421. var t;
  52422. for (i = 0; i < polygon.vertices.length; i++) {
  52423. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  52424. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  52425. polygonType |= type;
  52426. types.push(type);
  52427. }
  52428. // Put the polygon in the correct list, splitting it when necessary.
  52429. switch (polygonType) {
  52430. case COPLANAR:
  52431. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  52432. break;
  52433. case FRONT:
  52434. front.push(polygon);
  52435. break;
  52436. case BACK:
  52437. back.push(polygon);
  52438. break;
  52439. case SPANNING:
  52440. var f = [], b = [];
  52441. for (i = 0; i < polygon.vertices.length; i++) {
  52442. var j = (i + 1) % polygon.vertices.length;
  52443. var ti = types[i], tj = types[j];
  52444. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  52445. if (ti !== BACK)
  52446. f.push(vi);
  52447. if (ti !== FRONT)
  52448. b.push(ti !== BACK ? vi.clone() : vi);
  52449. if ((ti | tj) === SPANNING) {
  52450. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  52451. var v = vi.interpolate(vj, t);
  52452. f.push(v);
  52453. b.push(v.clone());
  52454. }
  52455. }
  52456. var poly;
  52457. if (f.length >= 3) {
  52458. poly = new Polygon(f, polygon.shared);
  52459. if (poly.plane)
  52460. front.push(poly);
  52461. }
  52462. if (b.length >= 3) {
  52463. poly = new Polygon(b, polygon.shared);
  52464. if (poly.plane)
  52465. back.push(poly);
  52466. }
  52467. break;
  52468. }
  52469. };
  52470. return Plane;
  52471. }());
  52472. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  52473. // point is on the plane.
  52474. Plane.EPSILON = 1e-5;
  52475. // # class Polygon
  52476. // Represents a convex polygon. The vertices used to initialize a polygon must
  52477. // be coplanar and form a convex loop.
  52478. //
  52479. // Each convex polygon has a `shared` property, which is shared between all
  52480. // polygons that are clones of each other or were split from the same polygon.
  52481. // This can be used to define per-polygon properties (such as surface color).
  52482. var Polygon = (function () {
  52483. function Polygon(vertices, shared) {
  52484. this.vertices = vertices;
  52485. this.shared = shared;
  52486. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  52487. }
  52488. Polygon.prototype.clone = function () {
  52489. var vertices = this.vertices.map(function (v) { return v.clone(); });
  52490. return new Polygon(vertices, this.shared);
  52491. };
  52492. Polygon.prototype.flip = function () {
  52493. this.vertices.reverse().map(function (v) { v.flip(); });
  52494. this.plane.flip();
  52495. };
  52496. return Polygon;
  52497. }());
  52498. // # class Node
  52499. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  52500. // by picking a polygon to split along. That polygon (and all other coplanar
  52501. // polygons) are added directly to that node and the other polygons are added to
  52502. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  52503. // no distinction between internal and leaf nodes.
  52504. var Node = (function () {
  52505. function Node(polygons) {
  52506. this.plane = null;
  52507. this.front = null;
  52508. this.back = null;
  52509. this.polygons = [];
  52510. if (polygons) {
  52511. this.build(polygons);
  52512. }
  52513. }
  52514. Node.prototype.clone = function () {
  52515. var node = new Node();
  52516. node.plane = this.plane && this.plane.clone();
  52517. node.front = this.front && this.front.clone();
  52518. node.back = this.back && this.back.clone();
  52519. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  52520. return node;
  52521. };
  52522. // Convert solid space to empty space and empty space to solid space.
  52523. Node.prototype.invert = function () {
  52524. for (var i = 0; i < this.polygons.length; i++) {
  52525. this.polygons[i].flip();
  52526. }
  52527. if (this.plane) {
  52528. this.plane.flip();
  52529. }
  52530. if (this.front) {
  52531. this.front.invert();
  52532. }
  52533. if (this.back) {
  52534. this.back.invert();
  52535. }
  52536. var temp = this.front;
  52537. this.front = this.back;
  52538. this.back = temp;
  52539. };
  52540. // Recursively remove all polygons in `polygons` that are inside this BSP
  52541. // tree.
  52542. Node.prototype.clipPolygons = function (polygons) {
  52543. if (!this.plane)
  52544. return polygons.slice();
  52545. var front = [], back = [];
  52546. for (var i = 0; i < polygons.length; i++) {
  52547. this.plane.splitPolygon(polygons[i], front, back, front, back);
  52548. }
  52549. if (this.front) {
  52550. front = this.front.clipPolygons(front);
  52551. }
  52552. if (this.back) {
  52553. back = this.back.clipPolygons(back);
  52554. }
  52555. else {
  52556. back = [];
  52557. }
  52558. return front.concat(back);
  52559. };
  52560. // Remove all polygons in this BSP tree that are inside the other BSP tree
  52561. // `bsp`.
  52562. Node.prototype.clipTo = function (bsp) {
  52563. this.polygons = bsp.clipPolygons(this.polygons);
  52564. if (this.front)
  52565. this.front.clipTo(bsp);
  52566. if (this.back)
  52567. this.back.clipTo(bsp);
  52568. };
  52569. // Return a list of all polygons in this BSP tree.
  52570. Node.prototype.allPolygons = function () {
  52571. var polygons = this.polygons.slice();
  52572. if (this.front)
  52573. polygons = polygons.concat(this.front.allPolygons());
  52574. if (this.back)
  52575. polygons = polygons.concat(this.back.allPolygons());
  52576. return polygons;
  52577. };
  52578. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  52579. // new polygons are filtered down to the bottom of the tree and become new
  52580. // nodes there. Each set of polygons is partitioned using the first polygon
  52581. // (no heuristic is used to pick a good split).
  52582. Node.prototype.build = function (polygons) {
  52583. if (!polygons.length)
  52584. return;
  52585. if (!this.plane)
  52586. this.plane = polygons[0].plane.clone();
  52587. var front = [], back = [];
  52588. for (var i = 0; i < polygons.length; i++) {
  52589. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  52590. }
  52591. if (front.length) {
  52592. if (!this.front)
  52593. this.front = new Node();
  52594. this.front.build(front);
  52595. }
  52596. if (back.length) {
  52597. if (!this.back)
  52598. this.back = new Node();
  52599. this.back.build(back);
  52600. }
  52601. };
  52602. return Node;
  52603. }());
  52604. var CSG = (function () {
  52605. function CSG() {
  52606. this.polygons = new Array();
  52607. }
  52608. // Convert BABYLON.Mesh to BABYLON.CSG
  52609. CSG.FromMesh = function (mesh) {
  52610. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  52611. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  52612. if (mesh instanceof BABYLON.Mesh) {
  52613. mesh.computeWorldMatrix(true);
  52614. matrix = mesh.getWorldMatrix();
  52615. meshPosition = mesh.position.clone();
  52616. meshRotation = mesh.rotation.clone();
  52617. if (mesh.rotationQuaternion) {
  52618. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  52619. }
  52620. meshScaling = mesh.scaling.clone();
  52621. }
  52622. else {
  52623. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  52624. }
  52625. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52626. var subMeshes = mesh.subMeshes;
  52627. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  52628. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  52629. vertices = [];
  52630. for (var j = 0; j < 3; j++) {
  52631. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  52632. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  52633. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  52634. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  52635. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  52636. vertex = new Vertex(position, normal, uv);
  52637. vertices.push(vertex);
  52638. }
  52639. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  52640. // To handle the case of degenerated triangle
  52641. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  52642. if (polygon.plane)
  52643. polygons.push(polygon);
  52644. }
  52645. }
  52646. var csg = CSG.FromPolygons(polygons);
  52647. csg.matrix = matrix;
  52648. csg.position = meshPosition;
  52649. csg.rotation = meshRotation;
  52650. csg.scaling = meshScaling;
  52651. csg.rotationQuaternion = meshRotationQuaternion;
  52652. currentCSGMeshId++;
  52653. return csg;
  52654. };
  52655. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  52656. CSG.FromPolygons = function (polygons) {
  52657. var csg = new CSG();
  52658. csg.polygons = polygons;
  52659. return csg;
  52660. };
  52661. CSG.prototype.clone = function () {
  52662. var csg = new CSG();
  52663. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  52664. csg.copyTransformAttributes(this);
  52665. return csg;
  52666. };
  52667. CSG.prototype.toPolygons = function () {
  52668. return this.polygons;
  52669. };
  52670. CSG.prototype.union = function (csg) {
  52671. var a = new Node(this.clone().polygons);
  52672. var b = new Node(csg.clone().polygons);
  52673. a.clipTo(b);
  52674. b.clipTo(a);
  52675. b.invert();
  52676. b.clipTo(a);
  52677. b.invert();
  52678. a.build(b.allPolygons());
  52679. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52680. };
  52681. CSG.prototype.unionInPlace = function (csg) {
  52682. var a = new Node(this.polygons);
  52683. var b = new Node(csg.polygons);
  52684. a.clipTo(b);
  52685. b.clipTo(a);
  52686. b.invert();
  52687. b.clipTo(a);
  52688. b.invert();
  52689. a.build(b.allPolygons());
  52690. this.polygons = a.allPolygons();
  52691. };
  52692. CSG.prototype.subtract = function (csg) {
  52693. var a = new Node(this.clone().polygons);
  52694. var b = new Node(csg.clone().polygons);
  52695. a.invert();
  52696. a.clipTo(b);
  52697. b.clipTo(a);
  52698. b.invert();
  52699. b.clipTo(a);
  52700. b.invert();
  52701. a.build(b.allPolygons());
  52702. a.invert();
  52703. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52704. };
  52705. CSG.prototype.subtractInPlace = function (csg) {
  52706. var a = new Node(this.polygons);
  52707. var b = new Node(csg.polygons);
  52708. a.invert();
  52709. a.clipTo(b);
  52710. b.clipTo(a);
  52711. b.invert();
  52712. b.clipTo(a);
  52713. b.invert();
  52714. a.build(b.allPolygons());
  52715. a.invert();
  52716. this.polygons = a.allPolygons();
  52717. };
  52718. CSG.prototype.intersect = function (csg) {
  52719. var a = new Node(this.clone().polygons);
  52720. var b = new Node(csg.clone().polygons);
  52721. a.invert();
  52722. b.clipTo(a);
  52723. b.invert();
  52724. a.clipTo(b);
  52725. b.clipTo(a);
  52726. a.build(b.allPolygons());
  52727. a.invert();
  52728. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  52729. };
  52730. CSG.prototype.intersectInPlace = function (csg) {
  52731. var a = new Node(this.polygons);
  52732. var b = new Node(csg.polygons);
  52733. a.invert();
  52734. b.clipTo(a);
  52735. b.invert();
  52736. a.clipTo(b);
  52737. b.clipTo(a);
  52738. a.build(b.allPolygons());
  52739. a.invert();
  52740. this.polygons = a.allPolygons();
  52741. };
  52742. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  52743. // not modified.
  52744. CSG.prototype.inverse = function () {
  52745. var csg = this.clone();
  52746. csg.inverseInPlace();
  52747. return csg;
  52748. };
  52749. CSG.prototype.inverseInPlace = function () {
  52750. this.polygons.map(function (p) { p.flip(); });
  52751. };
  52752. // This is used to keep meshes transformations so they can be restored
  52753. // when we build back a Babylon Mesh
  52754. // NB : All CSG operations are performed in world coordinates
  52755. CSG.prototype.copyTransformAttributes = function (csg) {
  52756. this.matrix = csg.matrix;
  52757. this.position = csg.position;
  52758. this.rotation = csg.rotation;
  52759. this.scaling = csg.scaling;
  52760. this.rotationQuaternion = csg.rotationQuaternion;
  52761. return this;
  52762. };
  52763. // Build Raw mesh from CSG
  52764. // Coordinates here are in world space
  52765. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  52766. var matrix = this.matrix.clone();
  52767. matrix.invert();
  52768. 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;
  52769. if (keepSubMeshes) {
  52770. // Sort Polygons, since subMeshes are indices range
  52771. polygons.sort(function (a, b) {
  52772. if (a.shared.meshId === b.shared.meshId) {
  52773. return a.shared.subMeshId - b.shared.subMeshId;
  52774. }
  52775. else {
  52776. return a.shared.meshId - b.shared.meshId;
  52777. }
  52778. });
  52779. }
  52780. for (var i = 0, il = polygons.length; i < il; i++) {
  52781. polygon = polygons[i];
  52782. // Building SubMeshes
  52783. if (!subMesh_dict[polygon.shared.meshId]) {
  52784. subMesh_dict[polygon.shared.meshId] = {};
  52785. }
  52786. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  52787. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  52788. indexStart: +Infinity,
  52789. indexEnd: -Infinity,
  52790. materialIndex: polygon.shared.materialIndex
  52791. };
  52792. }
  52793. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  52794. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  52795. polygonIndices[0] = 0;
  52796. polygonIndices[1] = j - 1;
  52797. polygonIndices[2] = j;
  52798. for (var k = 0; k < 3; k++) {
  52799. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  52800. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  52801. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  52802. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  52803. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  52804. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  52805. // Check if 2 points can be merged
  52806. if (!(typeof vertex_idx !== 'undefined' &&
  52807. normals[vertex_idx * 3] === localNormal.x &&
  52808. normals[vertex_idx * 3 + 1] === localNormal.y &&
  52809. normals[vertex_idx * 3 + 2] === localNormal.z &&
  52810. uvs[vertex_idx * 2] === uv.x &&
  52811. uvs[vertex_idx * 2 + 1] === uv.y)) {
  52812. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  52813. uvs.push(uv.x, uv.y);
  52814. normals.push(normal.x, normal.y, normal.z);
  52815. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  52816. }
  52817. indices.push(vertex_idx);
  52818. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  52819. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  52820. currentIndex++;
  52821. }
  52822. }
  52823. }
  52824. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  52825. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  52826. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  52827. mesh.setIndices(indices);
  52828. if (keepSubMeshes) {
  52829. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  52830. var materialIndexOffset = 0, materialMaxIndex;
  52831. mesh.subMeshes = new Array();
  52832. for (var m in subMesh_dict) {
  52833. materialMaxIndex = -1;
  52834. for (var sm in subMesh_dict[m]) {
  52835. subMesh_obj = subMesh_dict[m][sm];
  52836. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  52837. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  52838. }
  52839. materialIndexOffset += ++materialMaxIndex;
  52840. }
  52841. }
  52842. return mesh;
  52843. };
  52844. // Build Mesh from CSG taking material and transforms into account
  52845. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  52846. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  52847. mesh.material = material;
  52848. mesh.position.copyFrom(this.position);
  52849. mesh.rotation.copyFrom(this.rotation);
  52850. if (this.rotationQuaternion) {
  52851. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  52852. }
  52853. mesh.scaling.copyFrom(this.scaling);
  52854. mesh.computeWorldMatrix(true);
  52855. return mesh;
  52856. };
  52857. return CSG;
  52858. }());
  52859. BABYLON.CSG = CSG;
  52860. })(BABYLON || (BABYLON = {}));
  52861. //# sourceMappingURL=babylon.csg.js.map
  52862. var BABYLON;
  52863. (function (BABYLON) {
  52864. var LensFlare = (function () {
  52865. function LensFlare(size, position, color, imgUrl, system) {
  52866. this.size = size;
  52867. this.position = position;
  52868. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  52869. this.dispose = function () {
  52870. if (this.texture) {
  52871. this.texture.dispose();
  52872. }
  52873. // Remove from scene
  52874. var index = this._system.lensFlares.indexOf(this);
  52875. this._system.lensFlares.splice(index, 1);
  52876. };
  52877. this.color = color || new BABYLON.Color3(1, 1, 1);
  52878. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  52879. this._system = system;
  52880. system.lensFlares.push(this);
  52881. }
  52882. return LensFlare;
  52883. }());
  52884. BABYLON.LensFlare = LensFlare;
  52885. })(BABYLON || (BABYLON = {}));
  52886. //# sourceMappingURL=babylon.lensFlare.js.map
  52887. var BABYLON;
  52888. (function (BABYLON) {
  52889. var LensFlareSystem = (function () {
  52890. function LensFlareSystem(name, emitter, scene) {
  52891. this.name = name;
  52892. this.lensFlares = new Array();
  52893. this.borderLimit = 300;
  52894. this.viewportBorder = 0;
  52895. this.layerMask = 0x0FFFFFFF;
  52896. this._vertexBuffers = {};
  52897. this._isEnabled = true;
  52898. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52899. this._emitter = emitter;
  52900. this.id = name;
  52901. scene.lensFlareSystems.push(this);
  52902. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  52903. var engine = scene.getEngine();
  52904. // VBO
  52905. var vertices = [];
  52906. vertices.push(1, 1);
  52907. vertices.push(-1, 1);
  52908. vertices.push(-1, -1);
  52909. vertices.push(1, -1);
  52910. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  52911. // Indices
  52912. var indices = [];
  52913. indices.push(0);
  52914. indices.push(1);
  52915. indices.push(2);
  52916. indices.push(0);
  52917. indices.push(2);
  52918. indices.push(3);
  52919. this._indexBuffer = engine.createIndexBuffer(indices);
  52920. // Effects
  52921. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  52922. }
  52923. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  52924. get: function () {
  52925. return this._isEnabled;
  52926. },
  52927. set: function (value) {
  52928. this._isEnabled = value;
  52929. },
  52930. enumerable: true,
  52931. configurable: true
  52932. });
  52933. LensFlareSystem.prototype.getScene = function () {
  52934. return this._scene;
  52935. };
  52936. LensFlareSystem.prototype.getEmitter = function () {
  52937. return this._emitter;
  52938. };
  52939. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  52940. this._emitter = newEmitter;
  52941. };
  52942. LensFlareSystem.prototype.getEmitterPosition = function () {
  52943. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  52944. };
  52945. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  52946. var position = this.getEmitterPosition();
  52947. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  52948. this._positionX = position.x;
  52949. this._positionY = position.y;
  52950. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  52951. if (this.viewportBorder > 0) {
  52952. globalViewport.x -= this.viewportBorder;
  52953. globalViewport.y -= this.viewportBorder;
  52954. globalViewport.width += this.viewportBorder * 2;
  52955. globalViewport.height += this.viewportBorder * 2;
  52956. position.x += this.viewportBorder;
  52957. position.y += this.viewportBorder;
  52958. this._positionX += this.viewportBorder;
  52959. this._positionY += this.viewportBorder;
  52960. }
  52961. if (position.z > 0) {
  52962. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  52963. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  52964. return true;
  52965. }
  52966. return true;
  52967. }
  52968. return false;
  52969. };
  52970. LensFlareSystem.prototype._isVisible = function () {
  52971. if (!this._isEnabled) {
  52972. return false;
  52973. }
  52974. var emitterPosition = this.getEmitterPosition();
  52975. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  52976. var distance = direction.length();
  52977. direction.normalize();
  52978. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  52979. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  52980. return !pickInfo.hit || pickInfo.distance > distance;
  52981. };
  52982. LensFlareSystem.prototype.render = function () {
  52983. if (!this._effect.isReady())
  52984. return false;
  52985. var engine = this._scene.getEngine();
  52986. var viewport = this._scene.activeCamera.viewport;
  52987. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  52988. // Position
  52989. if (!this.computeEffectivePosition(globalViewport)) {
  52990. return false;
  52991. }
  52992. // Visibility
  52993. if (!this._isVisible()) {
  52994. return false;
  52995. }
  52996. // Intensity
  52997. var awayX;
  52998. var awayY;
  52999. if (this._positionX < this.borderLimit + globalViewport.x) {
  53000. awayX = this.borderLimit + globalViewport.x - this._positionX;
  53001. }
  53002. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  53003. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  53004. }
  53005. else {
  53006. awayX = 0;
  53007. }
  53008. if (this._positionY < this.borderLimit + globalViewport.y) {
  53009. awayY = this.borderLimit + globalViewport.y - this._positionY;
  53010. }
  53011. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  53012. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  53013. }
  53014. else {
  53015. awayY = 0;
  53016. }
  53017. var away = (awayX > awayY) ? awayX : awayY;
  53018. away -= this.viewportBorder;
  53019. if (away > this.borderLimit) {
  53020. away = this.borderLimit;
  53021. }
  53022. var intensity = 1.0 - (away / this.borderLimit);
  53023. if (intensity < 0) {
  53024. return false;
  53025. }
  53026. if (intensity > 1.0) {
  53027. intensity = 1.0;
  53028. }
  53029. if (this.viewportBorder > 0) {
  53030. globalViewport.x += this.viewportBorder;
  53031. globalViewport.y += this.viewportBorder;
  53032. globalViewport.width -= this.viewportBorder * 2;
  53033. globalViewport.height -= this.viewportBorder * 2;
  53034. this._positionX -= this.viewportBorder;
  53035. this._positionY -= this.viewportBorder;
  53036. }
  53037. // Position
  53038. var centerX = globalViewport.x + globalViewport.width / 2;
  53039. var centerY = globalViewport.y + globalViewport.height / 2;
  53040. var distX = centerX - this._positionX;
  53041. var distY = centerY - this._positionY;
  53042. // Effects
  53043. engine.enableEffect(this._effect);
  53044. engine.setState(false);
  53045. engine.setDepthBuffer(false);
  53046. // VBOs
  53047. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  53048. // Flares
  53049. for (var index = 0; index < this.lensFlares.length; index++) {
  53050. var flare = this.lensFlares[index];
  53051. engine.setAlphaMode(flare.alphaMode);
  53052. var x = centerX - (distX * flare.position);
  53053. var y = centerY - (distY * flare.position);
  53054. var cw = flare.size;
  53055. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  53056. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  53057. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  53058. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  53059. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  53060. // Texture
  53061. this._effect.setTexture("textureSampler", flare.texture);
  53062. // Color
  53063. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  53064. // Draw order
  53065. engine.draw(true, 0, 6);
  53066. }
  53067. engine.setDepthBuffer(true);
  53068. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53069. return true;
  53070. };
  53071. LensFlareSystem.prototype.dispose = function () {
  53072. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  53073. if (vertexBuffer) {
  53074. vertexBuffer.dispose();
  53075. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  53076. }
  53077. if (this._indexBuffer) {
  53078. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53079. this._indexBuffer = null;
  53080. }
  53081. while (this.lensFlares.length) {
  53082. this.lensFlares[0].dispose();
  53083. }
  53084. // Remove from scene
  53085. var index = this._scene.lensFlareSystems.indexOf(this);
  53086. this._scene.lensFlareSystems.splice(index, 1);
  53087. };
  53088. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  53089. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  53090. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  53091. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  53092. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  53093. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  53094. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  53095. var parsedFlare = parsedLensFlareSystem.flares[index];
  53096. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  53097. }
  53098. return lensFlareSystem;
  53099. };
  53100. LensFlareSystem.prototype.serialize = function () {
  53101. var serializationObject = {};
  53102. serializationObject.id = this.id;
  53103. serializationObject.name = this.name;
  53104. serializationObject.emitterId = this.getEmitter().id;
  53105. serializationObject.borderLimit = this.borderLimit;
  53106. serializationObject.flares = [];
  53107. for (var index = 0; index < this.lensFlares.length; index++) {
  53108. var flare = this.lensFlares[index];
  53109. serializationObject.flares.push({
  53110. size: flare.size,
  53111. position: flare.position,
  53112. color: flare.color.asArray(),
  53113. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  53114. });
  53115. }
  53116. return serializationObject;
  53117. };
  53118. return LensFlareSystem;
  53119. }());
  53120. BABYLON.LensFlareSystem = LensFlareSystem;
  53121. })(BABYLON || (BABYLON = {}));
  53122. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  53123. var BABYLON;
  53124. (function (BABYLON) {
  53125. /**
  53126. * This is a holder class for the physics joint created by the physics plugin.
  53127. * It holds a set of functions to control the underlying joint.
  53128. */
  53129. var PhysicsJoint = (function () {
  53130. function PhysicsJoint(type, jointData) {
  53131. this.type = type;
  53132. this.jointData = jointData;
  53133. jointData.nativeParams = jointData.nativeParams || {};
  53134. }
  53135. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  53136. get: function () {
  53137. return this._physicsJoint;
  53138. },
  53139. set: function (newJoint) {
  53140. if (this._physicsJoint) {
  53141. //remove from the wolrd
  53142. }
  53143. this._physicsJoint = newJoint;
  53144. },
  53145. enumerable: true,
  53146. configurable: true
  53147. });
  53148. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  53149. set: function (physicsPlugin) {
  53150. this._physicsPlugin = physicsPlugin;
  53151. },
  53152. enumerable: true,
  53153. configurable: true
  53154. });
  53155. /**
  53156. * Execute a function that is physics-plugin specific.
  53157. * @param {Function} func the function that will be executed.
  53158. * It accepts two parameters: the physics world and the physics joint.
  53159. */
  53160. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  53161. func(this._physicsPlugin.world, this._physicsJoint);
  53162. };
  53163. return PhysicsJoint;
  53164. }());
  53165. //TODO check if the native joints are the same
  53166. //Joint Types
  53167. PhysicsJoint.DistanceJoint = 0;
  53168. PhysicsJoint.HingeJoint = 1;
  53169. PhysicsJoint.BallAndSocketJoint = 2;
  53170. PhysicsJoint.WheelJoint = 3;
  53171. PhysicsJoint.SliderJoint = 4;
  53172. //OIMO
  53173. PhysicsJoint.PrismaticJoint = 5;
  53174. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  53175. PhysicsJoint.UniversalJoint = 6;
  53176. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  53177. //Cannon
  53178. //Similar to a Ball-Joint. Different in params
  53179. PhysicsJoint.PointToPointJoint = 8;
  53180. //Cannon only at the moment
  53181. PhysicsJoint.SpringJoint = 9;
  53182. PhysicsJoint.LockJoint = 10;
  53183. BABYLON.PhysicsJoint = PhysicsJoint;
  53184. /**
  53185. * A class representing a physics distance joint.
  53186. */
  53187. var DistanceJoint = (function (_super) {
  53188. __extends(DistanceJoint, _super);
  53189. function DistanceJoint(jointData) {
  53190. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  53191. }
  53192. /**
  53193. * Update the predefined distance.
  53194. */
  53195. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  53196. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  53197. };
  53198. return DistanceJoint;
  53199. }(PhysicsJoint));
  53200. BABYLON.DistanceJoint = DistanceJoint;
  53201. var MotorEnabledJoint = (function (_super) {
  53202. __extends(MotorEnabledJoint, _super);
  53203. function MotorEnabledJoint(type, jointData) {
  53204. return _super.call(this, type, jointData) || this;
  53205. }
  53206. /**
  53207. * Set the motor values.
  53208. * Attention, this function is plugin specific. Engines won't react 100% the same.
  53209. * @param {number} force the force to apply
  53210. * @param {number} maxForce max force for this motor.
  53211. */
  53212. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  53213. this._physicsPlugin.setMotor(this, force, maxForce);
  53214. };
  53215. /**
  53216. * Set the motor's limits.
  53217. * Attention, this function is plugin specific. Engines won't react 100% the same.
  53218. */
  53219. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  53220. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  53221. };
  53222. return MotorEnabledJoint;
  53223. }(PhysicsJoint));
  53224. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  53225. /**
  53226. * This class represents a single hinge physics joint
  53227. */
  53228. var HingeJoint = (function (_super) {
  53229. __extends(HingeJoint, _super);
  53230. function HingeJoint(jointData) {
  53231. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  53232. }
  53233. /**
  53234. * Set the motor values.
  53235. * Attention, this function is plugin specific. Engines won't react 100% the same.
  53236. * @param {number} force the force to apply
  53237. * @param {number} maxForce max force for this motor.
  53238. */
  53239. HingeJoint.prototype.setMotor = function (force, maxForce) {
  53240. this._physicsPlugin.setMotor(this, force, maxForce);
  53241. };
  53242. /**
  53243. * Set the motor's limits.
  53244. * Attention, this function is plugin specific. Engines won't react 100% the same.
  53245. */
  53246. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  53247. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  53248. };
  53249. return HingeJoint;
  53250. }(MotorEnabledJoint));
  53251. BABYLON.HingeJoint = HingeJoint;
  53252. /**
  53253. * This class represents a dual hinge physics joint (same as wheel joint)
  53254. */
  53255. var Hinge2Joint = (function (_super) {
  53256. __extends(Hinge2Joint, _super);
  53257. function Hinge2Joint(jointData) {
  53258. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  53259. }
  53260. /**
  53261. * Set the motor values.
  53262. * Attention, this function is plugin specific. Engines won't react 100% the same.
  53263. * @param {number} force the force to apply
  53264. * @param {number} maxForce max force for this motor.
  53265. * @param {motorIndex} the motor's index, 0 or 1.
  53266. */
  53267. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  53268. if (motorIndex === void 0) { motorIndex = 0; }
  53269. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  53270. };
  53271. /**
  53272. * Set the motor limits.
  53273. * Attention, this function is plugin specific. Engines won't react 100% the same.
  53274. * @param {number} upperLimit the upper limit
  53275. * @param {number} lowerLimit lower limit
  53276. * @param {motorIndex} the motor's index, 0 or 1.
  53277. */
  53278. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  53279. if (motorIndex === void 0) { motorIndex = 0; }
  53280. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  53281. };
  53282. return Hinge2Joint;
  53283. }(MotorEnabledJoint));
  53284. BABYLON.Hinge2Joint = Hinge2Joint;
  53285. })(BABYLON || (BABYLON = {}));
  53286. //# sourceMappingURL=babylon.physicsJoint.js.map
  53287. var BABYLON;
  53288. (function (BABYLON) {
  53289. var PhysicsImpostor = (function () {
  53290. function PhysicsImpostor(object, type, _options, _scene) {
  53291. if (_options === void 0) { _options = { mass: 0 }; }
  53292. var _this = this;
  53293. this.object = object;
  53294. this.type = type;
  53295. this._options = _options;
  53296. this._scene = _scene;
  53297. this._bodyUpdateRequired = false;
  53298. this._onBeforePhysicsStepCallbacks = new Array();
  53299. this._onAfterPhysicsStepCallbacks = new Array();
  53300. this._onPhysicsCollideCallbacks = [];
  53301. this._deltaPosition = BABYLON.Vector3.Zero();
  53302. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  53303. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  53304. /**
  53305. * this function is executed by the physics engine.
  53306. */
  53307. this.beforeStep = function () {
  53308. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  53309. //conjugate deltaRotation
  53310. if (_this._deltaRotationConjugated) {
  53311. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  53312. }
  53313. else {
  53314. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  53315. }
  53316. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  53317. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  53318. func(_this);
  53319. });
  53320. };
  53321. /**
  53322. * this function is executed by the physics engine.
  53323. */
  53324. this.afterStep = function () {
  53325. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  53326. func(_this);
  53327. });
  53328. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  53329. _this.object.position.addInPlace(_this._deltaPosition);
  53330. if (_this._deltaRotation) {
  53331. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  53332. }
  53333. };
  53334. /**
  53335. * Legacy collision detection event support
  53336. */
  53337. this.onCollideEvent = null;
  53338. //event and body object due to cannon's event-based architecture.
  53339. this.onCollide = function (e) {
  53340. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  53341. return;
  53342. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  53343. if (otherImpostor) {
  53344. // Legacy collision detection event support
  53345. if (_this.onCollideEvent) {
  53346. _this.onCollideEvent(_this, otherImpostor);
  53347. }
  53348. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  53349. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  53350. }).forEach(function (obj) {
  53351. obj.callback(_this, otherImpostor);
  53352. });
  53353. }
  53354. };
  53355. //sanity check!
  53356. if (!this.object) {
  53357. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  53358. return;
  53359. }
  53360. //legacy support for old syntax.
  53361. if (!this._scene && object.getScene) {
  53362. this._scene = object.getScene();
  53363. }
  53364. this._physicsEngine = this._scene.getPhysicsEngine();
  53365. if (!this._physicsEngine) {
  53366. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  53367. }
  53368. else {
  53369. //set the object's quaternion, if not set
  53370. if (!this.object.rotationQuaternion) {
  53371. if (this.object.rotation) {
  53372. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  53373. }
  53374. else {
  53375. this.object.rotationQuaternion = new BABYLON.Quaternion();
  53376. }
  53377. }
  53378. //default options params
  53379. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  53380. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  53381. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  53382. this._joints = [];
  53383. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  53384. if (!this.object.parent) {
  53385. this._init();
  53386. }
  53387. }
  53388. }
  53389. /**
  53390. * This function will completly initialize this impostor.
  53391. * It will create a new body - but only if this mesh has no parent.
  53392. * If it has, this impostor will not be used other than to define the impostor
  53393. * of the child mesh.
  53394. */
  53395. PhysicsImpostor.prototype._init = function () {
  53396. this._physicsEngine.removeImpostor(this);
  53397. this.physicsBody = null;
  53398. this._parent = this._parent || this._getPhysicsParent();
  53399. if (!this.parent) {
  53400. this._physicsEngine.addImpostor(this);
  53401. }
  53402. };
  53403. PhysicsImpostor.prototype._getPhysicsParent = function () {
  53404. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  53405. var parentMesh = this.object.parent;
  53406. return parentMesh.physicsImpostor;
  53407. }
  53408. return;
  53409. };
  53410. /**
  53411. * Should a new body be generated.
  53412. */
  53413. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  53414. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  53415. };
  53416. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  53417. this.forceUpdate();
  53418. };
  53419. /**
  53420. * Force a regeneration of this or the parent's impostor's body.
  53421. * Use under cautious - This will remove all joints already implemented.
  53422. */
  53423. PhysicsImpostor.prototype.forceUpdate = function () {
  53424. this._init();
  53425. if (this.parent) {
  53426. this.parent.forceUpdate();
  53427. }
  53428. };
  53429. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  53430. /*public get mesh(): AbstractMesh {
  53431. return this._mesh;
  53432. }*/
  53433. /**
  53434. * Gets the body that holds this impostor. Either its own, or its parent.
  53435. */
  53436. get: function () {
  53437. return this._parent ? this._parent.physicsBody : this._physicsBody;
  53438. },
  53439. /**
  53440. * Set the physics body. Used mainly by the physics engine/plugin
  53441. */
  53442. set: function (physicsBody) {
  53443. if (this._physicsBody) {
  53444. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  53445. }
  53446. this._physicsBody = physicsBody;
  53447. this.resetUpdateFlags();
  53448. },
  53449. enumerable: true,
  53450. configurable: true
  53451. });
  53452. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  53453. get: function () {
  53454. return this._parent;
  53455. },
  53456. set: function (value) {
  53457. this._parent = value;
  53458. },
  53459. enumerable: true,
  53460. configurable: true
  53461. });
  53462. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  53463. this._bodyUpdateRequired = false;
  53464. };
  53465. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  53466. if (this.object.getBoundingInfo) {
  53467. var q = this.object.rotationQuaternion;
  53468. //reset rotation
  53469. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  53470. //calculate the world matrix with no rotation
  53471. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  53472. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  53473. //bring back the rotation
  53474. this.object.rotationQuaternion = q;
  53475. //calculate the world matrix with the new rotation
  53476. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  53477. return size;
  53478. }
  53479. else {
  53480. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  53481. }
  53482. };
  53483. PhysicsImpostor.prototype.getObjectCenter = function () {
  53484. if (this.object.getBoundingInfo) {
  53485. return this.object.getBoundingInfo().boundingBox.centerWorld;
  53486. }
  53487. else {
  53488. return this.object.position;
  53489. }
  53490. };
  53491. /**
  53492. * Get a specific parametes from the options parameter.
  53493. */
  53494. PhysicsImpostor.prototype.getParam = function (paramName) {
  53495. return this._options[paramName];
  53496. };
  53497. /**
  53498. * Sets a specific parameter in the options given to the physics plugin
  53499. */
  53500. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  53501. this._options[paramName] = value;
  53502. this._bodyUpdateRequired = true;
  53503. };
  53504. /**
  53505. * Specifically change the body's mass option. Won't recreate the physics body object
  53506. */
  53507. PhysicsImpostor.prototype.setMass = function (mass) {
  53508. if (this.getParam("mass") !== mass) {
  53509. this.setParam("mass", mass);
  53510. }
  53511. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  53512. };
  53513. PhysicsImpostor.prototype.getLinearVelocity = function () {
  53514. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  53515. };
  53516. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  53517. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  53518. };
  53519. PhysicsImpostor.prototype.getAngularVelocity = function () {
  53520. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  53521. };
  53522. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  53523. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  53524. };
  53525. /**
  53526. * Execute a function with the physics plugin native code.
  53527. * Provide a function the will have two variables - the world object and the physics body object.
  53528. */
  53529. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  53530. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  53531. };
  53532. /**
  53533. * Register a function that will be executed before the physics world is stepping forward.
  53534. */
  53535. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  53536. this._onBeforePhysicsStepCallbacks.push(func);
  53537. };
  53538. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  53539. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  53540. if (index > -1) {
  53541. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  53542. }
  53543. else {
  53544. BABYLON.Tools.Warn("Function to remove was not found");
  53545. }
  53546. };
  53547. /**
  53548. * Register a function that will be executed after the physics step
  53549. */
  53550. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  53551. this._onAfterPhysicsStepCallbacks.push(func);
  53552. };
  53553. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  53554. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  53555. if (index > -1) {
  53556. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  53557. }
  53558. else {
  53559. BABYLON.Tools.Warn("Function to remove was not found");
  53560. }
  53561. };
  53562. /**
  53563. * register a function that will be executed when this impostor collides against a different body.
  53564. */
  53565. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  53566. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  53567. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  53568. };
  53569. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  53570. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  53571. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  53572. if (index > -1) {
  53573. this._onPhysicsCollideCallbacks.splice(index, 1);
  53574. }
  53575. else {
  53576. BABYLON.Tools.Warn("Function to remove was not found");
  53577. }
  53578. };
  53579. /**
  53580. * Apply a force
  53581. */
  53582. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  53583. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  53584. };
  53585. /**
  53586. * Apply an impulse
  53587. */
  53588. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  53589. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  53590. };
  53591. /**
  53592. * A help function to create a joint.
  53593. */
  53594. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  53595. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  53596. this.addJoint(otherImpostor, joint);
  53597. };
  53598. /**
  53599. * Add a joint to this impostor with a different impostor.
  53600. */
  53601. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  53602. this._joints.push({
  53603. otherImpostor: otherImpostor,
  53604. joint: joint
  53605. });
  53606. this._physicsEngine.addJoint(this, otherImpostor, joint);
  53607. };
  53608. /**
  53609. * Will keep this body still, in a sleep mode.
  53610. */
  53611. PhysicsImpostor.prototype.sleep = function () {
  53612. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  53613. };
  53614. /**
  53615. * Wake the body up.
  53616. */
  53617. PhysicsImpostor.prototype.wakeUp = function () {
  53618. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  53619. };
  53620. PhysicsImpostor.prototype.clone = function (newObject) {
  53621. if (!newObject)
  53622. return null;
  53623. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  53624. };
  53625. PhysicsImpostor.prototype.dispose = function () {
  53626. var _this = this;
  53627. //no dispose if no physics engine is available.
  53628. if (!this._physicsEngine) {
  53629. return;
  53630. }
  53631. this._joints.forEach(function (j) {
  53632. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  53633. });
  53634. //dispose the physics body
  53635. this._physicsEngine.removeImpostor(this);
  53636. if (this.parent) {
  53637. this.parent.forceUpdate();
  53638. }
  53639. else {
  53640. /*this._object.getChildMeshes().forEach(function(mesh) {
  53641. if (mesh.physicsImpostor) {
  53642. if (disposeChildren) {
  53643. mesh.physicsImpostor.dispose();
  53644. mesh.physicsImpostor = null;
  53645. }
  53646. }
  53647. })*/
  53648. }
  53649. };
  53650. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  53651. this._deltaPosition.copyFrom(position);
  53652. };
  53653. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  53654. if (!this._deltaRotation) {
  53655. this._deltaRotation = new BABYLON.Quaternion();
  53656. }
  53657. this._deltaRotation.copyFrom(rotation);
  53658. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  53659. };
  53660. return PhysicsImpostor;
  53661. }());
  53662. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  53663. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  53664. //Impostor types
  53665. PhysicsImpostor.NoImpostor = 0;
  53666. PhysicsImpostor.SphereImpostor = 1;
  53667. PhysicsImpostor.BoxImpostor = 2;
  53668. PhysicsImpostor.PlaneImpostor = 3;
  53669. PhysicsImpostor.MeshImpostor = 4;
  53670. PhysicsImpostor.CylinderImpostor = 7;
  53671. PhysicsImpostor.ParticleImpostor = 8;
  53672. PhysicsImpostor.HeightmapImpostor = 9;
  53673. BABYLON.PhysicsImpostor = PhysicsImpostor;
  53674. })(BABYLON || (BABYLON = {}));
  53675. //# sourceMappingURL=babylon.physicsImpostor.js.map
  53676. var BABYLON;
  53677. (function (BABYLON) {
  53678. var PhysicsEngine = (function () {
  53679. function PhysicsEngine(gravity, _physicsPlugin) {
  53680. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  53681. this._physicsPlugin = _physicsPlugin;
  53682. //new methods and parameters
  53683. this._impostors = [];
  53684. this._joints = [];
  53685. if (!this._physicsPlugin.isSupported()) {
  53686. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  53687. + "Please make sure it is included.");
  53688. }
  53689. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  53690. this.setGravity(gravity);
  53691. this.setTimeStep();
  53692. }
  53693. PhysicsEngine.prototype.setGravity = function (gravity) {
  53694. this.gravity = gravity;
  53695. this._physicsPlugin.setGravity(this.gravity);
  53696. };
  53697. /**
  53698. * Set the time step of the physics engine.
  53699. * default is 1/60.
  53700. * To slow it down, enter 1/600 for example.
  53701. * To speed it up, 1/30
  53702. * @param {number} newTimeStep the new timestep to apply to this world.
  53703. */
  53704. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  53705. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  53706. this._physicsPlugin.setTimeStep(newTimeStep);
  53707. };
  53708. PhysicsEngine.prototype.dispose = function () {
  53709. this._impostors.forEach(function (impostor) {
  53710. impostor.dispose();
  53711. });
  53712. this._physicsPlugin.dispose();
  53713. };
  53714. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  53715. return this._physicsPlugin.name;
  53716. };
  53717. /**
  53718. * Adding a new impostor for the impostor tracking.
  53719. * This will be done by the impostor itself.
  53720. * @param {PhysicsImpostor} impostor the impostor to add
  53721. */
  53722. PhysicsEngine.prototype.addImpostor = function (impostor) {
  53723. impostor.uniqueId = this._impostors.push(impostor);
  53724. //if no parent, generate the body
  53725. if (!impostor.parent) {
  53726. this._physicsPlugin.generatePhysicsBody(impostor);
  53727. }
  53728. };
  53729. /**
  53730. * Remove an impostor from the engine.
  53731. * This impostor and its mesh will not longer be updated by the physics engine.
  53732. * @param {PhysicsImpostor} impostor the impostor to remove
  53733. */
  53734. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  53735. var index = this._impostors.indexOf(impostor);
  53736. if (index > -1) {
  53737. var removed = this._impostors.splice(index, 1);
  53738. //Is it needed?
  53739. if (removed.length) {
  53740. //this will also remove it from the world.
  53741. removed[0].physicsBody = null;
  53742. }
  53743. }
  53744. };
  53745. /**
  53746. * Add a joint to the physics engine
  53747. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  53748. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  53749. * @param {PhysicsJoint} the joint that will connect both impostors.
  53750. */
  53751. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  53752. var impostorJoint = {
  53753. mainImpostor: mainImpostor,
  53754. connectedImpostor: connectedImpostor,
  53755. joint: joint
  53756. };
  53757. joint.physicsPlugin = this._physicsPlugin;
  53758. this._joints.push(impostorJoint);
  53759. this._physicsPlugin.generateJoint(impostorJoint);
  53760. };
  53761. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  53762. var matchingJoints = this._joints.filter(function (impostorJoint) {
  53763. return (impostorJoint.connectedImpostor === connectedImpostor
  53764. && impostorJoint.joint === joint
  53765. && impostorJoint.mainImpostor === mainImpostor);
  53766. });
  53767. if (matchingJoints.length) {
  53768. this._physicsPlugin.removeJoint(matchingJoints[0]);
  53769. //TODO remove it from the list as well
  53770. }
  53771. };
  53772. /**
  53773. * Called by the scene. no need to call it.
  53774. */
  53775. PhysicsEngine.prototype._step = function (delta) {
  53776. var _this = this;
  53777. //check if any mesh has no body / requires an update
  53778. this._impostors.forEach(function (impostor) {
  53779. if (impostor.isBodyInitRequired()) {
  53780. _this._physicsPlugin.generatePhysicsBody(impostor);
  53781. }
  53782. });
  53783. if (delta > 0.1) {
  53784. delta = 0.1;
  53785. }
  53786. else if (delta <= 0) {
  53787. delta = 1.0 / 60.0;
  53788. }
  53789. this._physicsPlugin.executeStep(delta, this._impostors);
  53790. };
  53791. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  53792. return this._physicsPlugin;
  53793. };
  53794. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  53795. for (var i = 0; i < this._impostors.length; ++i) {
  53796. if (this._impostors[i].object === object) {
  53797. return this._impostors[i];
  53798. }
  53799. }
  53800. };
  53801. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  53802. for (var i = 0; i < this._impostors.length; ++i) {
  53803. if (this._impostors[i].physicsBody === body) {
  53804. return this._impostors[i];
  53805. }
  53806. }
  53807. };
  53808. return PhysicsEngine;
  53809. }());
  53810. // Statics
  53811. PhysicsEngine.Epsilon = 0.001;
  53812. BABYLON.PhysicsEngine = PhysicsEngine;
  53813. })(BABYLON || (BABYLON = {}));
  53814. //# sourceMappingURL=babylon.physicsEngine.js.map
  53815. var BABYLON;
  53816. (function (BABYLON) {
  53817. var CannonJSPlugin = (function () {
  53818. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  53819. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  53820. if (iterations === void 0) { iterations = 10; }
  53821. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  53822. this.name = "CannonJSPlugin";
  53823. this._physicsMaterials = [];
  53824. this._fixedTimeStep = 1 / 60;
  53825. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  53826. this._currentCollisionGroup = 2;
  53827. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  53828. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  53829. this._tmpPosition = BABYLON.Vector3.Zero();
  53830. this._tmpQuaternion = new BABYLON.Quaternion();
  53831. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  53832. this._tmpDeltaRotation = new BABYLON.Quaternion();
  53833. this._tmpUnityRotation = new BABYLON.Quaternion();
  53834. if (!this.isSupported()) {
  53835. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  53836. return;
  53837. }
  53838. this.world = new CANNON.World();
  53839. this.world.broadphase = new CANNON.NaiveBroadphase();
  53840. this.world.solver.iterations = iterations;
  53841. }
  53842. CannonJSPlugin.prototype.setGravity = function (gravity) {
  53843. this.world.gravity.copy(gravity);
  53844. };
  53845. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  53846. this._fixedTimeStep = timeStep;
  53847. };
  53848. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  53849. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  53850. };
  53851. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  53852. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  53853. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  53854. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  53855. };
  53856. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  53857. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  53858. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  53859. impostor.physicsBody.applyForce(impulse, worldPoint);
  53860. };
  53861. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  53862. //parent-child relationship. Does this impostor has a parent impostor?
  53863. if (impostor.parent) {
  53864. if (impostor.physicsBody) {
  53865. this.removePhysicsBody(impostor);
  53866. //TODO is that needed?
  53867. impostor.forceUpdate();
  53868. }
  53869. return;
  53870. }
  53871. //should a new body be created for this impostor?
  53872. if (impostor.isBodyInitRequired()) {
  53873. var shape = this._createShape(impostor);
  53874. //unregister events, if body is being changed
  53875. var oldBody = impostor.physicsBody;
  53876. if (oldBody) {
  53877. this.removePhysicsBody(impostor);
  53878. }
  53879. //create the body and material
  53880. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  53881. var bodyCreationObject = {
  53882. mass: impostor.getParam("mass"),
  53883. material: material
  53884. };
  53885. // A simple extend, in case native options were used.
  53886. var nativeOptions = impostor.getParam("nativeOptions");
  53887. for (var key in nativeOptions) {
  53888. if (nativeOptions.hasOwnProperty(key)) {
  53889. bodyCreationObject[key] = nativeOptions[key];
  53890. }
  53891. }
  53892. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  53893. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  53894. this.world.addEventListener("preStep", impostor.beforeStep);
  53895. this.world.addEventListener("postStep", impostor.afterStep);
  53896. impostor.physicsBody.addShape(shape);
  53897. this.world.add(impostor.physicsBody);
  53898. //try to keep the body moving in the right direction by taking old properties.
  53899. //Should be tested!
  53900. if (oldBody) {
  53901. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  53902. impostor.physicsBody[param].copy(oldBody[param]);
  53903. });
  53904. }
  53905. this._processChildMeshes(impostor);
  53906. }
  53907. //now update the body's transformation
  53908. this._updatePhysicsBodyTransformation(impostor);
  53909. };
  53910. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  53911. var _this = this;
  53912. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  53913. if (meshChildren.length) {
  53914. var processMesh = function (localPosition, mesh) {
  53915. var childImpostor = mesh.getPhysicsImpostor();
  53916. if (childImpostor) {
  53917. var parent = childImpostor.parent;
  53918. if (parent !== mainImpostor) {
  53919. var localPosition = mesh.position;
  53920. if (childImpostor.physicsBody) {
  53921. _this.removePhysicsBody(childImpostor);
  53922. childImpostor.physicsBody = null;
  53923. }
  53924. childImpostor.parent = mainImpostor;
  53925. childImpostor.resetUpdateFlags();
  53926. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  53927. //Add the mass of the children.
  53928. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  53929. }
  53930. }
  53931. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  53932. };
  53933. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  53934. }
  53935. };
  53936. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  53937. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  53938. this.world.removeEventListener("preStep", impostor.beforeStep);
  53939. this.world.removeEventListener("postStep", impostor.afterStep);
  53940. this.world.remove(impostor.physicsBody);
  53941. };
  53942. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  53943. var mainBody = impostorJoint.mainImpostor.physicsBody;
  53944. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  53945. if (!mainBody || !connectedBody) {
  53946. return;
  53947. }
  53948. var constraint;
  53949. var jointData = impostorJoint.joint.jointData;
  53950. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  53951. var constraintData = {
  53952. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  53953. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  53954. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  53955. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  53956. maxForce: jointData.nativeParams.maxForce,
  53957. collideConnected: !!jointData.collision
  53958. };
  53959. switch (impostorJoint.joint.type) {
  53960. case BABYLON.PhysicsJoint.HingeJoint:
  53961. case BABYLON.PhysicsJoint.Hinge2Joint:
  53962. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  53963. break;
  53964. case BABYLON.PhysicsJoint.DistanceJoint:
  53965. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  53966. break;
  53967. case BABYLON.PhysicsJoint.SpringJoint:
  53968. var springData = jointData;
  53969. constraint = new CANNON.Spring(mainBody, connectedBody, {
  53970. restLength: springData.length,
  53971. stiffness: springData.stiffness,
  53972. damping: springData.damping,
  53973. localAnchorA: constraintData.pivotA,
  53974. localAnchorB: constraintData.pivotB
  53975. });
  53976. break;
  53977. case BABYLON.PhysicsJoint.LockJoint:
  53978. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  53979. break;
  53980. case BABYLON.PhysicsJoint.PointToPointJoint:
  53981. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  53982. default:
  53983. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  53984. break;
  53985. }
  53986. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  53987. constraint.collideConnected = !!jointData.collision;
  53988. impostorJoint.joint.physicsJoint = constraint;
  53989. //don't add spring as constraint, as it is not one.
  53990. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  53991. this.world.addConstraint(constraint);
  53992. }
  53993. else {
  53994. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  53995. constraint.applyForce();
  53996. });
  53997. }
  53998. };
  53999. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  54000. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  54001. };
  54002. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  54003. var index;
  54004. var mat;
  54005. for (index = 0; index < this._physicsMaterials.length; index++) {
  54006. mat = this._physicsMaterials[index];
  54007. if (mat.friction === friction && mat.restitution === restitution) {
  54008. return mat;
  54009. }
  54010. }
  54011. var currentMat = new CANNON.Material(name);
  54012. currentMat.friction = friction;
  54013. currentMat.restitution = restitution;
  54014. this._physicsMaterials.push(currentMat);
  54015. return currentMat;
  54016. };
  54017. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  54018. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  54019. };
  54020. CannonJSPlugin.prototype._createShape = function (impostor) {
  54021. var object = impostor.object;
  54022. var returnValue;
  54023. var extendSize = impostor.getObjectExtendSize();
  54024. switch (impostor.type) {
  54025. case BABYLON.PhysicsImpostor.SphereImpostor:
  54026. var radiusX = extendSize.x;
  54027. var radiusY = extendSize.y;
  54028. var radiusZ = extendSize.z;
  54029. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  54030. break;
  54031. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  54032. case BABYLON.PhysicsImpostor.CylinderImpostor:
  54033. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  54034. break;
  54035. case BABYLON.PhysicsImpostor.BoxImpostor:
  54036. var box = extendSize.scale(0.5);
  54037. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  54038. break;
  54039. case BABYLON.PhysicsImpostor.PlaneImpostor:
  54040. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  54041. returnValue = new CANNON.Plane();
  54042. break;
  54043. case BABYLON.PhysicsImpostor.MeshImpostor:
  54044. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  54045. var rawFaces = object.getIndices ? object.getIndices() : [];
  54046. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  54047. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  54048. break;
  54049. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  54050. returnValue = this._createHeightmap(object);
  54051. break;
  54052. case BABYLON.PhysicsImpostor.ParticleImpostor:
  54053. returnValue = new CANNON.Particle();
  54054. break;
  54055. }
  54056. return returnValue;
  54057. };
  54058. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  54059. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54060. var matrix = [];
  54061. //For now pointDepth will not be used and will be automatically calculated.
  54062. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  54063. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  54064. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  54065. var elementSize = dim * 2 / arraySize;
  54066. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  54067. for (var i = 0; i < pos.length; i = i + 3) {
  54068. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  54069. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  54070. var y = pos[i + 1] + minY;
  54071. if (!matrix[x]) {
  54072. matrix[x] = [];
  54073. }
  54074. if (!matrix[x][z]) {
  54075. matrix[x][z] = y;
  54076. }
  54077. matrix[x][z] = Math.max(y, matrix[x][z]);
  54078. }
  54079. for (var x = 0; x <= arraySize; ++x) {
  54080. if (!matrix[x]) {
  54081. var loc = 1;
  54082. while (!matrix[(x + loc) % arraySize]) {
  54083. loc++;
  54084. }
  54085. matrix[x] = matrix[(x + loc) % arraySize].slice();
  54086. //console.log("missing x", x);
  54087. }
  54088. for (var z = 0; z <= arraySize; ++z) {
  54089. if (!matrix[x][z]) {
  54090. var loc = 1;
  54091. var newValue;
  54092. while (newValue === undefined) {
  54093. newValue = matrix[x][(z + loc++) % arraySize];
  54094. }
  54095. matrix[x][z] = newValue;
  54096. }
  54097. }
  54098. }
  54099. var shape = new CANNON.Heightfield(matrix, {
  54100. elementSize: elementSize
  54101. });
  54102. //For future reference, needed for body transformation
  54103. shape.minY = minY;
  54104. return shape;
  54105. };
  54106. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  54107. var object = impostor.object;
  54108. //make sure it is updated...
  54109. object.computeWorldMatrix && object.computeWorldMatrix(true);
  54110. // The delta between the mesh position and the mesh bounding box center
  54111. var center = impostor.getObjectCenter();
  54112. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  54113. this._tmpPosition.copyFrom(center);
  54114. var quaternion = object.rotationQuaternion;
  54115. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  54116. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  54117. //-90 DEG in X, precalculated
  54118. quaternion = quaternion.multiply(this._minus90X);
  54119. //Invert! (Precalculated, 90 deg in X)
  54120. //No need to clone. this will never change.
  54121. impostor.setDeltaRotation(this._plus90X);
  54122. }
  54123. //If it is a heightfield, if should be centered.
  54124. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  54125. var mesh = object;
  54126. //calculate the correct body position:
  54127. var rotationQuaternion = mesh.rotationQuaternion;
  54128. mesh.rotationQuaternion = this._tmpUnityRotation;
  54129. mesh.computeWorldMatrix(true);
  54130. //get original center with no rotation
  54131. var c = center.clone();
  54132. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  54133. //rotation is back
  54134. mesh.rotationQuaternion = rotationQuaternion;
  54135. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  54136. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  54137. mesh.setPivotMatrix(p);
  54138. mesh.computeWorldMatrix(true);
  54139. //calculate the translation
  54140. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  54141. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  54142. //add it inverted to the delta
  54143. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  54144. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  54145. mesh.setPivotMatrix(oldPivot);
  54146. mesh.computeWorldMatrix(true);
  54147. }
  54148. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  54149. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  54150. this._tmpPosition.copyFrom(object.position);
  54151. }
  54152. impostor.setDeltaPosition(this._tmpDeltaPosition);
  54153. //Now update the impostor object
  54154. impostor.physicsBody.position.copy(this._tmpPosition);
  54155. impostor.physicsBody.quaternion.copy(quaternion);
  54156. };
  54157. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  54158. impostor.object.position.copyFrom(impostor.physicsBody.position);
  54159. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  54160. };
  54161. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  54162. impostor.physicsBody.position.copy(newPosition);
  54163. impostor.physicsBody.quaternion.copy(newRotation);
  54164. };
  54165. CannonJSPlugin.prototype.isSupported = function () {
  54166. return window.CANNON !== undefined;
  54167. };
  54168. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  54169. impostor.physicsBody.velocity.copy(velocity);
  54170. };
  54171. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  54172. impostor.physicsBody.angularVelocity.copy(velocity);
  54173. };
  54174. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  54175. var v = impostor.physicsBody.velocity;
  54176. if (!v)
  54177. return null;
  54178. return new BABYLON.Vector3(v.x, v.y, v.z);
  54179. };
  54180. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  54181. var v = impostor.physicsBody.angularVelocity;
  54182. if (!v)
  54183. return null;
  54184. return new BABYLON.Vector3(v.x, v.y, v.z);
  54185. };
  54186. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  54187. impostor.physicsBody.mass = mass;
  54188. impostor.physicsBody.updateMassProperties();
  54189. };
  54190. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  54191. impostor.physicsBody.sleep();
  54192. };
  54193. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  54194. impostor.physicsBody.wakeUp();
  54195. };
  54196. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  54197. joint.physicsJoint.distance = maxDistance;
  54198. };
  54199. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  54200. if (!motorIndex) {
  54201. joint.physicsJoint.enableMotor();
  54202. }
  54203. };
  54204. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  54205. if (!motorIndex) {
  54206. joint.physicsJoint.disableMotor();
  54207. }
  54208. };
  54209. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  54210. if (!motorIndex) {
  54211. joint.physicsJoint.enableMotor();
  54212. joint.physicsJoint.setMotorSpeed(speed);
  54213. if (maxForce) {
  54214. this.setLimit(joint, maxForce);
  54215. }
  54216. }
  54217. };
  54218. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  54219. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  54220. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  54221. };
  54222. CannonJSPlugin.prototype.dispose = function () {
  54223. //nothing to do, actually.
  54224. };
  54225. return CannonJSPlugin;
  54226. }());
  54227. BABYLON.CannonJSPlugin = CannonJSPlugin;
  54228. })(BABYLON || (BABYLON = {}));
  54229. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  54230. var BABYLON;
  54231. (function (BABYLON) {
  54232. var OimoJSPlugin = (function () {
  54233. function OimoJSPlugin(iterations) {
  54234. this.name = "OimoJSPlugin";
  54235. this._tmpImpostorsArray = [];
  54236. this._tmpPositionVector = BABYLON.Vector3.Zero();
  54237. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  54238. this.world.worldscale(1);
  54239. this.world.clear();
  54240. //making sure no stats are calculated
  54241. this.world.isNoStat = true;
  54242. }
  54243. OimoJSPlugin.prototype.setGravity = function (gravity) {
  54244. this.world.gravity.copy(gravity);
  54245. };
  54246. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  54247. this.world.timeStep = timeStep;
  54248. };
  54249. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  54250. var _this = this;
  54251. impostors.forEach(function (impostor) {
  54252. impostor.beforeStep();
  54253. });
  54254. this.world.step();
  54255. impostors.forEach(function (impostor) {
  54256. impostor.afterStep();
  54257. //update the ordered impostors array
  54258. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  54259. });
  54260. //check for collisions
  54261. var contact = this.world.contacts;
  54262. while (contact !== null) {
  54263. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  54264. contact = contact.next;
  54265. continue;
  54266. }
  54267. //is this body colliding with any other? get the impostor
  54268. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  54269. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  54270. if (!mainImpostor || !collidingImpostor) {
  54271. contact = contact.next;
  54272. continue;
  54273. }
  54274. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  54275. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  54276. contact = contact.next;
  54277. }
  54278. };
  54279. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  54280. var mass = impostor.physicsBody.massInfo.mass;
  54281. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  54282. };
  54283. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  54284. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  54285. this.applyImpulse(impostor, force, contactPoint);
  54286. };
  54287. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  54288. var _this = this;
  54289. //parent-child relationship. Does this impostor has a parent impostor?
  54290. if (impostor.parent) {
  54291. if (impostor.physicsBody) {
  54292. this.removePhysicsBody(impostor);
  54293. //TODO is that needed?
  54294. impostor.forceUpdate();
  54295. }
  54296. return;
  54297. }
  54298. if (impostor.isBodyInitRequired()) {
  54299. var bodyConfig = {
  54300. name: impostor.uniqueId,
  54301. //Oimo must have mass, also for static objects.
  54302. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  54303. size: [],
  54304. type: [],
  54305. pos: [],
  54306. rot: [],
  54307. move: impostor.getParam("mass") !== 0,
  54308. //Supporting older versions of Oimo
  54309. world: this.world
  54310. };
  54311. var impostors = [impostor];
  54312. var addToArray = function (parent) {
  54313. if (!parent.getChildMeshes)
  54314. return;
  54315. parent.getChildMeshes().forEach(function (m) {
  54316. if (m.physicsImpostor) {
  54317. impostors.push(m.physicsImpostor);
  54318. m.physicsImpostor._init();
  54319. }
  54320. });
  54321. };
  54322. addToArray(impostor.object);
  54323. var checkWithEpsilon_1 = function (value) {
  54324. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  54325. };
  54326. impostors.forEach(function (i) {
  54327. //get the correct bounding box
  54328. var oldQuaternion = i.object.rotationQuaternion;
  54329. var rot = new OIMO.Euler().setFromQuaternion({
  54330. x: impostor.object.rotationQuaternion.x,
  54331. y: impostor.object.rotationQuaternion.y,
  54332. z: impostor.object.rotationQuaternion.z,
  54333. s: impostor.object.rotationQuaternion.w
  54334. });
  54335. var extendSize = i.getObjectExtendSize();
  54336. if (i === impostor) {
  54337. var center = impostor.getObjectCenter();
  54338. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  54339. //Can also use Array.prototype.push.apply
  54340. bodyConfig.pos.push(center.x);
  54341. bodyConfig.pos.push(center.y);
  54342. bodyConfig.pos.push(center.z);
  54343. //tmp solution
  54344. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  54345. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  54346. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  54347. }
  54348. else {
  54349. bodyConfig.pos.push(i.object.position.x);
  54350. bodyConfig.pos.push(i.object.position.y);
  54351. bodyConfig.pos.push(i.object.position.z);
  54352. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  54353. bodyConfig.rot.push(0);
  54354. bodyConfig.rot.push(0);
  54355. bodyConfig.rot.push(0);
  54356. }
  54357. // register mesh
  54358. switch (i.type) {
  54359. case BABYLON.PhysicsImpostor.ParticleImpostor:
  54360. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  54361. case BABYLON.PhysicsImpostor.SphereImpostor:
  54362. var radiusX = extendSize.x;
  54363. var radiusY = extendSize.y;
  54364. var radiusZ = extendSize.z;
  54365. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  54366. bodyConfig.type.push('sphere');
  54367. //due to the way oimo works with compounds, add 3 times
  54368. bodyConfig.size.push(size);
  54369. bodyConfig.size.push(size);
  54370. bodyConfig.size.push(size);
  54371. break;
  54372. case BABYLON.PhysicsImpostor.CylinderImpostor:
  54373. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  54374. var sizeY = checkWithEpsilon_1(extendSize.y);
  54375. bodyConfig.type.push('cylinder');
  54376. bodyConfig.size.push(sizeX);
  54377. bodyConfig.size.push(sizeY);
  54378. //due to the way oimo works with compounds, add one more value.
  54379. bodyConfig.size.push(sizeY);
  54380. break;
  54381. case BABYLON.PhysicsImpostor.PlaneImpostor:
  54382. case BABYLON.PhysicsImpostor.BoxImpostor:
  54383. default:
  54384. var sizeX = checkWithEpsilon_1(extendSize.x);
  54385. var sizeY = checkWithEpsilon_1(extendSize.y);
  54386. var sizeZ = checkWithEpsilon_1(extendSize.z);
  54387. bodyConfig.type.push('box');
  54388. bodyConfig.size.push(sizeX);
  54389. bodyConfig.size.push(sizeY);
  54390. bodyConfig.size.push(sizeZ);
  54391. break;
  54392. }
  54393. //actually not needed, but hey...
  54394. i.object.rotationQuaternion = oldQuaternion;
  54395. });
  54396. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  54397. }
  54398. else {
  54399. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  54400. }
  54401. impostor.setDeltaPosition(this._tmpPositionVector);
  54402. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  54403. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  54404. };
  54405. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  54406. //impostor.physicsBody.dispose();
  54407. //Same as : (older oimo versions)
  54408. this.world.removeRigidBody(impostor.physicsBody);
  54409. };
  54410. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  54411. var mainBody = impostorJoint.mainImpostor.physicsBody;
  54412. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  54413. if (!mainBody || !connectedBody) {
  54414. return;
  54415. }
  54416. var jointData = impostorJoint.joint.jointData;
  54417. var options = jointData.nativeParams || {};
  54418. var type;
  54419. var nativeJointData = {
  54420. body1: mainBody,
  54421. body2: connectedBody,
  54422. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  54423. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  54424. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  54425. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  54426. min: options.min,
  54427. max: options.max,
  54428. collision: options.collision || jointData.collision,
  54429. spring: options.spring,
  54430. //supporting older version of Oimo
  54431. world: this.world
  54432. };
  54433. switch (impostorJoint.joint.type) {
  54434. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  54435. type = "jointBall";
  54436. break;
  54437. case BABYLON.PhysicsJoint.SpringJoint:
  54438. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  54439. var springData = jointData;
  54440. nativeJointData.min = springData.length || nativeJointData.min;
  54441. //Max should also be set, just make sure it is at least min
  54442. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  54443. case BABYLON.PhysicsJoint.DistanceJoint:
  54444. type = "jointDistance";
  54445. nativeJointData.max = jointData.maxDistance;
  54446. break;
  54447. case BABYLON.PhysicsJoint.PrismaticJoint:
  54448. type = "jointPrisme";
  54449. break;
  54450. case BABYLON.PhysicsJoint.SliderJoint:
  54451. type = "jointSlide";
  54452. break;
  54453. case BABYLON.PhysicsJoint.WheelJoint:
  54454. type = "jointWheel";
  54455. break;
  54456. case BABYLON.PhysicsJoint.HingeJoint:
  54457. default:
  54458. type = "jointHinge";
  54459. break;
  54460. }
  54461. nativeJointData.type = type;
  54462. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  54463. };
  54464. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  54465. //Bug in Oimo prevents us from disposing a joint in the playground
  54466. //joint.joint.physicsJoint.dispose();
  54467. //So we will bruteforce it!
  54468. try {
  54469. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  54470. }
  54471. catch (e) {
  54472. BABYLON.Tools.Warn(e);
  54473. }
  54474. };
  54475. OimoJSPlugin.prototype.isSupported = function () {
  54476. return OIMO !== undefined;
  54477. };
  54478. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  54479. if (!impostor.physicsBody.sleeping) {
  54480. //TODO check that
  54481. if (impostor.physicsBody.shapes.next) {
  54482. var parentShape = this._getLastShape(impostor.physicsBody);
  54483. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  54484. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  54485. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  54486. }
  54487. else {
  54488. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  54489. }
  54490. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  54491. impostor.object.rotationQuaternion.normalize();
  54492. }
  54493. };
  54494. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  54495. var body = impostor.physicsBody;
  54496. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  54497. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  54498. body.syncShapes();
  54499. body.awake();
  54500. };
  54501. OimoJSPlugin.prototype._getLastShape = function (body) {
  54502. var lastShape = body.shapes;
  54503. while (lastShape.next) {
  54504. lastShape = lastShape.next;
  54505. }
  54506. return lastShape;
  54507. };
  54508. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  54509. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  54510. };
  54511. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  54512. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  54513. };
  54514. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  54515. var v = impostor.physicsBody.linearVelocity;
  54516. if (!v)
  54517. return null;
  54518. return new BABYLON.Vector3(v.x, v.y, v.z);
  54519. };
  54520. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  54521. var v = impostor.physicsBody.angularVelocity;
  54522. if (!v)
  54523. return null;
  54524. return new BABYLON.Vector3(v.x, v.y, v.z);
  54525. };
  54526. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  54527. var staticBody = mass === 0;
  54528. //this will actually set the body's density and not its mass.
  54529. //But this is how oimo treats the mass variable.
  54530. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  54531. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  54532. };
  54533. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  54534. impostor.physicsBody.sleep();
  54535. };
  54536. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  54537. impostor.physicsBody.awake();
  54538. };
  54539. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  54540. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  54541. if (minDistance !== void 0) {
  54542. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  54543. }
  54544. };
  54545. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  54546. //TODO separate rotational and transational motors.
  54547. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  54548. if (motor) {
  54549. motor.setMotor(speed, maxForce);
  54550. }
  54551. };
  54552. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  54553. //TODO separate rotational and transational motors.
  54554. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  54555. if (motor) {
  54556. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  54557. }
  54558. };
  54559. OimoJSPlugin.prototype.dispose = function () {
  54560. this.world.clear();
  54561. };
  54562. return OimoJSPlugin;
  54563. }());
  54564. BABYLON.OimoJSPlugin = OimoJSPlugin;
  54565. })(BABYLON || (BABYLON = {}));
  54566. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  54567. var BABYLON;
  54568. (function (BABYLON) {
  54569. var Internals;
  54570. (function (Internals) {
  54571. /*
  54572. * Based on jsTGALoader - Javascript loader for TGA file
  54573. * By Vincent Thibault
  54574. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  54575. */
  54576. var TGATools = (function () {
  54577. function TGATools() {
  54578. }
  54579. TGATools.GetTGAHeader = function (data) {
  54580. var offset = 0;
  54581. var header = {
  54582. id_length: data[offset++],
  54583. colormap_type: data[offset++],
  54584. image_type: data[offset++],
  54585. colormap_index: data[offset++] | data[offset++] << 8,
  54586. colormap_length: data[offset++] | data[offset++] << 8,
  54587. colormap_size: data[offset++],
  54588. origin: [
  54589. data[offset++] | data[offset++] << 8,
  54590. data[offset++] | data[offset++] << 8
  54591. ],
  54592. width: data[offset++] | data[offset++] << 8,
  54593. height: data[offset++] | data[offset++] << 8,
  54594. pixel_size: data[offset++],
  54595. flags: data[offset++]
  54596. };
  54597. return header;
  54598. };
  54599. TGATools.UploadContent = function (gl, data) {
  54600. // Not enough data to contain header ?
  54601. if (data.length < 19) {
  54602. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  54603. return;
  54604. }
  54605. // Read Header
  54606. var offset = 18;
  54607. var header = TGATools.GetTGAHeader(data);
  54608. // Assume it's a valid Targa file.
  54609. if (header.id_length + offset > data.length) {
  54610. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  54611. return;
  54612. }
  54613. // Skip not needed data
  54614. offset += header.id_length;
  54615. var use_rle = false;
  54616. var use_pal = false;
  54617. var use_rgb = false;
  54618. var use_grey = false;
  54619. // Get some informations.
  54620. switch (header.image_type) {
  54621. case TGATools._TYPE_RLE_INDEXED:
  54622. use_rle = true;
  54623. case TGATools._TYPE_INDEXED:
  54624. use_pal = true;
  54625. break;
  54626. case TGATools._TYPE_RLE_RGB:
  54627. use_rle = true;
  54628. case TGATools._TYPE_RGB:
  54629. use_rgb = true;
  54630. break;
  54631. case TGATools._TYPE_RLE_GREY:
  54632. use_rle = true;
  54633. case TGATools._TYPE_GREY:
  54634. use_grey = true;
  54635. break;
  54636. }
  54637. var pixel_data;
  54638. var numAlphaBits = header.flags & 0xf;
  54639. var pixel_size = header.pixel_size >> 3;
  54640. var pixel_total = header.width * header.height * pixel_size;
  54641. // Read palettes
  54642. var palettes;
  54643. if (use_pal) {
  54644. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  54645. }
  54646. // Read LRE
  54647. if (use_rle) {
  54648. pixel_data = new Uint8Array(pixel_total);
  54649. var c, count, i;
  54650. var localOffset = 0;
  54651. var pixels = new Uint8Array(pixel_size);
  54652. while (offset < pixel_total && localOffset < pixel_total) {
  54653. c = data[offset++];
  54654. count = (c & 0x7f) + 1;
  54655. // RLE pixels
  54656. if (c & 0x80) {
  54657. // Bind pixel tmp array
  54658. for (i = 0; i < pixel_size; ++i) {
  54659. pixels[i] = data[offset++];
  54660. }
  54661. // Copy pixel array
  54662. for (i = 0; i < count; ++i) {
  54663. pixel_data.set(pixels, localOffset + i * pixel_size);
  54664. }
  54665. localOffset += pixel_size * count;
  54666. }
  54667. else {
  54668. count *= pixel_size;
  54669. for (i = 0; i < count; ++i) {
  54670. pixel_data[localOffset + i] = data[offset++];
  54671. }
  54672. localOffset += count;
  54673. }
  54674. }
  54675. }
  54676. else {
  54677. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  54678. }
  54679. // Load to texture
  54680. var x_start, y_start, x_step, y_step, y_end, x_end;
  54681. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  54682. default:
  54683. case TGATools._ORIGIN_UL:
  54684. x_start = 0;
  54685. x_step = 1;
  54686. x_end = header.width;
  54687. y_start = 0;
  54688. y_step = 1;
  54689. y_end = header.height;
  54690. break;
  54691. case TGATools._ORIGIN_BL:
  54692. x_start = 0;
  54693. x_step = 1;
  54694. x_end = header.width;
  54695. y_start = header.height - 1;
  54696. y_step = -1;
  54697. y_end = -1;
  54698. break;
  54699. case TGATools._ORIGIN_UR:
  54700. x_start = header.width - 1;
  54701. x_step = -1;
  54702. x_end = -1;
  54703. y_start = 0;
  54704. y_step = 1;
  54705. y_end = header.height;
  54706. break;
  54707. case TGATools._ORIGIN_BR:
  54708. x_start = header.width - 1;
  54709. x_step = -1;
  54710. x_end = -1;
  54711. y_start = header.height - 1;
  54712. y_step = -1;
  54713. y_end = -1;
  54714. break;
  54715. }
  54716. // Load the specify method
  54717. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  54718. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  54719. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  54720. };
  54721. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  54722. var image = pixel_data, colormap = palettes;
  54723. var width = header.width, height = header.height;
  54724. var color, i = 0, x, y;
  54725. var imageData = new Uint8Array(width * height * 4);
  54726. for (y = y_start; y !== y_end; y += y_step) {
  54727. for (x = x_start; x !== x_end; x += x_step, i++) {
  54728. color = image[i];
  54729. imageData[(x + width * y) * 4 + 3] = 255;
  54730. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  54731. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  54732. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  54733. }
  54734. }
  54735. return imageData;
  54736. };
  54737. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  54738. var image = pixel_data;
  54739. var width = header.width, height = header.height;
  54740. var color, i = 0, x, y;
  54741. var imageData = new Uint8Array(width * height * 4);
  54742. for (y = y_start; y !== y_end; y += y_step) {
  54743. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  54744. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  54745. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  54746. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  54747. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  54748. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  54749. }
  54750. }
  54751. return imageData;
  54752. };
  54753. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  54754. var image = pixel_data;
  54755. var width = header.width, height = header.height;
  54756. var i = 0, x, y;
  54757. var imageData = new Uint8Array(width * height * 4);
  54758. for (y = y_start; y !== y_end; y += y_step) {
  54759. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  54760. imageData[(x + width * y) * 4 + 3] = 255;
  54761. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  54762. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  54763. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  54764. }
  54765. }
  54766. return imageData;
  54767. };
  54768. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  54769. var image = pixel_data;
  54770. var width = header.width, height = header.height;
  54771. var i = 0, x, y;
  54772. var imageData = new Uint8Array(width * height * 4);
  54773. for (y = y_start; y !== y_end; y += y_step) {
  54774. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  54775. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  54776. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  54777. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  54778. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  54779. }
  54780. }
  54781. return imageData;
  54782. };
  54783. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  54784. var image = pixel_data;
  54785. var width = header.width, height = header.height;
  54786. var color, i = 0, x, y;
  54787. var imageData = new Uint8Array(width * height * 4);
  54788. for (y = y_start; y !== y_end; y += y_step) {
  54789. for (x = x_start; x !== x_end; x += x_step, i++) {
  54790. color = image[i];
  54791. imageData[(x + width * y) * 4 + 0] = color;
  54792. imageData[(x + width * y) * 4 + 1] = color;
  54793. imageData[(x + width * y) * 4 + 2] = color;
  54794. imageData[(x + width * y) * 4 + 3] = 255;
  54795. }
  54796. }
  54797. return imageData;
  54798. };
  54799. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  54800. var image = pixel_data;
  54801. var width = header.width, height = header.height;
  54802. var i = 0, x, y;
  54803. var imageData = new Uint8Array(width * height * 4);
  54804. for (y = y_start; y !== y_end; y += y_step) {
  54805. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  54806. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  54807. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  54808. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  54809. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  54810. }
  54811. }
  54812. return imageData;
  54813. };
  54814. return TGATools;
  54815. }());
  54816. TGATools._TYPE_NO_DATA = 0;
  54817. TGATools._TYPE_INDEXED = 1;
  54818. TGATools._TYPE_RGB = 2;
  54819. TGATools._TYPE_GREY = 3;
  54820. TGATools._TYPE_RLE_INDEXED = 9;
  54821. TGATools._TYPE_RLE_RGB = 10;
  54822. TGATools._TYPE_RLE_GREY = 11;
  54823. TGATools._ORIGIN_MASK = 0x30;
  54824. TGATools._ORIGIN_SHIFT = 0x04;
  54825. TGATools._ORIGIN_BL = 0x00;
  54826. TGATools._ORIGIN_BR = 0x01;
  54827. TGATools._ORIGIN_UL = 0x02;
  54828. TGATools._ORIGIN_UR = 0x03;
  54829. Internals.TGATools = TGATools;
  54830. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54831. })(BABYLON || (BABYLON = {}));
  54832. //# sourceMappingURL=babylon.tga.js.map
  54833. var BABYLON;
  54834. (function (BABYLON) {
  54835. var Internals;
  54836. (function (Internals) {
  54837. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  54838. // All values and structures referenced from:
  54839. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  54840. var DDS_MAGIC = 0x20534444;
  54841. 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;
  54842. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  54843. 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;
  54844. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  54845. function FourCCToInt32(value) {
  54846. return value.charCodeAt(0) +
  54847. (value.charCodeAt(1) << 8) +
  54848. (value.charCodeAt(2) << 16) +
  54849. (value.charCodeAt(3) << 24);
  54850. }
  54851. function Int32ToFourCC(value) {
  54852. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  54853. }
  54854. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  54855. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  54856. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  54857. var headerLengthInt = 31; // The header length in 32 bit ints
  54858. // Offsets into the header array
  54859. var off_magic = 0;
  54860. var off_size = 1;
  54861. var off_flags = 2;
  54862. var off_height = 3;
  54863. var off_width = 4;
  54864. var off_mipmapCount = 7;
  54865. var off_pfFlags = 20;
  54866. var off_pfFourCC = 21;
  54867. var off_RGBbpp = 22;
  54868. var off_RMask = 23;
  54869. var off_GMask = 24;
  54870. var off_BMask = 25;
  54871. var off_AMask = 26;
  54872. var off_caps1 = 27;
  54873. var off_caps2 = 28;
  54874. ;
  54875. var DDSTools = (function () {
  54876. function DDSTools() {
  54877. }
  54878. DDSTools.GetDDSInfo = function (arrayBuffer) {
  54879. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  54880. var mipmapCount = 1;
  54881. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  54882. mipmapCount = Math.max(1, header[off_mipmapCount]);
  54883. }
  54884. return {
  54885. width: header[off_width],
  54886. height: header[off_height],
  54887. mipmapCount: mipmapCount,
  54888. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  54889. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  54890. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  54891. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  54892. };
  54893. };
  54894. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  54895. var byteArray = new Uint8Array(dataLength);
  54896. var srcData = new Uint8Array(arrayBuffer);
  54897. var index = 0;
  54898. for (var y = height - 1; y >= 0; y--) {
  54899. for (var x = 0; x < width; x++) {
  54900. var srcPos = dataOffset + (x + y * width) * 4;
  54901. byteArray[index + 2] = srcData[srcPos];
  54902. byteArray[index + 1] = srcData[srcPos + 1];
  54903. byteArray[index] = srcData[srcPos + 2];
  54904. byteArray[index + 3] = srcData[srcPos + 3];
  54905. index += 4;
  54906. }
  54907. }
  54908. return byteArray;
  54909. };
  54910. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  54911. var byteArray = new Uint8Array(dataLength);
  54912. var srcData = new Uint8Array(arrayBuffer);
  54913. var index = 0;
  54914. for (var y = height - 1; y >= 0; y--) {
  54915. for (var x = 0; x < width; x++) {
  54916. var srcPos = dataOffset + (x + y * width) * 3;
  54917. byteArray[index + 2] = srcData[srcPos];
  54918. byteArray[index + 1] = srcData[srcPos + 1];
  54919. byteArray[index] = srcData[srcPos + 2];
  54920. index += 3;
  54921. }
  54922. }
  54923. return byteArray;
  54924. };
  54925. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  54926. var byteArray = new Uint8Array(dataLength);
  54927. var srcData = new Uint8Array(arrayBuffer);
  54928. var index = 0;
  54929. for (var y = height - 1; y >= 0; y--) {
  54930. for (var x = 0; x < width; x++) {
  54931. var srcPos = dataOffset + (x + y * width);
  54932. byteArray[index] = srcData[srcPos];
  54933. index++;
  54934. }
  54935. }
  54936. return byteArray;
  54937. };
  54938. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  54939. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  54940. if (header[off_magic] != DDS_MAGIC) {
  54941. BABYLON.Tools.Error("Invalid magic number in DDS header");
  54942. return;
  54943. }
  54944. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  54945. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  54946. return;
  54947. }
  54948. if (info.isFourCC) {
  54949. fourCC = header[off_pfFourCC];
  54950. switch (fourCC) {
  54951. case FOURCC_DXT1:
  54952. blockBytes = 8;
  54953. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  54954. break;
  54955. case FOURCC_DXT3:
  54956. blockBytes = 16;
  54957. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  54958. break;
  54959. case FOURCC_DXT5:
  54960. blockBytes = 16;
  54961. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  54962. break;
  54963. default:
  54964. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  54965. return;
  54966. }
  54967. }
  54968. mipmapCount = 1;
  54969. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  54970. mipmapCount = Math.max(1, header[off_mipmapCount]);
  54971. }
  54972. var bpp = header[off_RGBbpp];
  54973. for (var face = 0; face < faces; face++) {
  54974. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  54975. width = header[off_width];
  54976. height = header[off_height];
  54977. dataOffset = header[off_size] + 4;
  54978. for (i = 0; i < mipmapCount; ++i) {
  54979. if (info.isRGB) {
  54980. if (bpp === 24) {
  54981. dataLength = width * height * 3;
  54982. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  54983. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  54984. }
  54985. else {
  54986. dataLength = width * height * 4;
  54987. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  54988. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  54989. }
  54990. }
  54991. else if (info.isLuminance) {
  54992. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  54993. var unpaddedRowSize = width;
  54994. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  54995. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  54996. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  54997. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  54998. }
  54999. else {
  55000. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  55001. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  55002. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  55003. }
  55004. dataOffset += dataLength;
  55005. width *= 0.5;
  55006. height *= 0.5;
  55007. width = Math.max(1.0, width);
  55008. height = Math.max(1.0, height);
  55009. }
  55010. }
  55011. };
  55012. return DDSTools;
  55013. }());
  55014. Internals.DDSTools = DDSTools;
  55015. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55016. })(BABYLON || (BABYLON = {}));
  55017. //# sourceMappingURL=babylon.dds.js.map
  55018. var BABYLON;
  55019. (function (BABYLON) {
  55020. var Internals;
  55021. (function (Internals) {
  55022. /**
  55023. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  55024. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  55025. */
  55026. var KhronosTextureContainer = (function () {
  55027. /**
  55028. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  55029. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  55030. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  55031. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  55032. */
  55033. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  55034. this.arrayBuffer = arrayBuffer;
  55035. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  55036. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  55037. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  55038. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  55039. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  55040. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  55041. BABYLON.Tools.Error("texture missing KTX identifier");
  55042. return;
  55043. }
  55044. // load the reset of the header in native 32 bit int
  55045. var header = new Int32Array(this.arrayBuffer, 12, 13);
  55046. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  55047. var oppositeEndianess = header[0] === 0x01020304;
  55048. // read all the header elements in order they exist in the file, without modification (sans endainness)
  55049. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  55050. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  55051. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  55052. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  55053. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  55054. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  55055. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  55056. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  55057. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  55058. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  55059. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  55060. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  55061. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  55062. if (this.glType !== 0) {
  55063. BABYLON.Tools.Error("only compressed formats currently supported");
  55064. return;
  55065. }
  55066. else {
  55067. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  55068. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  55069. }
  55070. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  55071. BABYLON.Tools.Error("only 2D textures currently supported");
  55072. return;
  55073. }
  55074. if (this.numberOfArrayElements !== 0) {
  55075. BABYLON.Tools.Error("texture arrays not currently supported");
  55076. return;
  55077. }
  55078. if (this.numberOfFaces !== facesExpected) {
  55079. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  55080. return;
  55081. }
  55082. // we now have a completely validated file, so could use existence of loadType as success
  55083. // would need to make this more elaborate & adjust checks above to support more than one load type
  55084. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  55085. }
  55086. // not as fast hardware based, but will probably never need to use
  55087. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  55088. return ((val & 0xFF) << 24)
  55089. | ((val & 0xFF00) << 8)
  55090. | ((val >> 8) & 0xFF00)
  55091. | ((val >> 24) & 0xFF);
  55092. };
  55093. /**
  55094. * It is assumed that the texture has already been created & is currently bound
  55095. */
  55096. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  55097. switch (this.loadType) {
  55098. case KhronosTextureContainer.COMPRESSED_2D:
  55099. this._upload2DCompressedLevels(gl, loadMipmaps);
  55100. break;
  55101. case KhronosTextureContainer.TEX_2D:
  55102. case KhronosTextureContainer.COMPRESSED_3D:
  55103. case KhronosTextureContainer.TEX_3D:
  55104. }
  55105. };
  55106. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  55107. // initialize width & height for level 1
  55108. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  55109. var width = this.pixelWidth;
  55110. var height = this.pixelHeight;
  55111. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  55112. for (var level = 0; level < mipmapCount; level++) {
  55113. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  55114. for (var face = 0; face < this.numberOfFaces; face++) {
  55115. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  55116. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  55117. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  55118. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  55119. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  55120. }
  55121. width = Math.max(1.0, width * 0.5);
  55122. height = Math.max(1.0, height * 0.5);
  55123. }
  55124. };
  55125. return KhronosTextureContainer;
  55126. }());
  55127. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  55128. // load types
  55129. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  55130. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  55131. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  55132. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  55133. Internals.KhronosTextureContainer = KhronosTextureContainer;
  55134. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55135. })(BABYLON || (BABYLON = {}));
  55136. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  55137. var BABYLON;
  55138. (function (BABYLON) {
  55139. var Debug;
  55140. (function (Debug) {
  55141. /**
  55142. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  55143. */
  55144. var SkeletonViewer = (function () {
  55145. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  55146. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  55147. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  55148. this.skeleton = skeleton;
  55149. this.mesh = mesh;
  55150. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  55151. this.renderingGroupId = renderingGroupId;
  55152. this.color = BABYLON.Color3.White();
  55153. this._debugLines = [];
  55154. this._isEnabled = false;
  55155. this._scene = scene;
  55156. this.update();
  55157. this._renderFunction = this.update.bind(this);
  55158. }
  55159. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  55160. get: function () {
  55161. return this._isEnabled;
  55162. },
  55163. set: function (value) {
  55164. if (this._isEnabled === value) {
  55165. return;
  55166. }
  55167. this._isEnabled = value;
  55168. if (value) {
  55169. this._scene.registerBeforeRender(this._renderFunction);
  55170. }
  55171. else {
  55172. this._scene.unregisterBeforeRender(this._renderFunction);
  55173. }
  55174. },
  55175. enumerable: true,
  55176. configurable: true
  55177. });
  55178. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  55179. if (x === void 0) { x = 0; }
  55180. if (y === void 0) { y = 0; }
  55181. if (z === void 0) { z = 0; }
  55182. var tmat = BABYLON.Tmp.Matrix[0];
  55183. var parentBone = bone.getParent();
  55184. tmat.copyFrom(bone.getLocalMatrix());
  55185. if (x !== 0 || y !== 0 || z !== 0) {
  55186. var tmat2 = BABYLON.Tmp.Matrix[1];
  55187. BABYLON.Matrix.IdentityToRef(tmat2);
  55188. tmat2.m[12] = x;
  55189. tmat2.m[13] = y;
  55190. tmat2.m[14] = z;
  55191. tmat2.multiplyToRef(tmat, tmat);
  55192. }
  55193. if (parentBone) {
  55194. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  55195. }
  55196. tmat.multiplyToRef(meshMat, tmat);
  55197. position.x = tmat.m[12];
  55198. position.y = tmat.m[13];
  55199. position.z = tmat.m[14];
  55200. };
  55201. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  55202. var len = bones.length;
  55203. for (var i = 0; i < len; i++) {
  55204. var bone = bones[i];
  55205. var points = this._debugLines[i];
  55206. if (!points) {
  55207. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55208. this._debugLines[i] = points;
  55209. }
  55210. this._getBonePosition(points[0], bone, meshMat);
  55211. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  55212. }
  55213. };
  55214. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  55215. var len = bones.length;
  55216. var boneNum = 0;
  55217. for (var i = len - 1; i >= 0; i--) {
  55218. var childBone = bones[i];
  55219. var parentBone = childBone.getParent();
  55220. if (!parentBone) {
  55221. continue;
  55222. }
  55223. var points = this._debugLines[boneNum];
  55224. if (!points) {
  55225. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55226. this._debugLines[boneNum] = points;
  55227. }
  55228. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  55229. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  55230. boneNum++;
  55231. }
  55232. };
  55233. SkeletonViewer.prototype.update = function () {
  55234. if (this.autoUpdateBonesMatrices) {
  55235. this.skeleton.computeAbsoluteTransforms();
  55236. }
  55237. if (this.skeleton.bones[0].length === undefined) {
  55238. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  55239. }
  55240. else {
  55241. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  55242. }
  55243. if (!this._debugMesh) {
  55244. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  55245. this._debugMesh.renderingGroupId = this.renderingGroupId;
  55246. }
  55247. else {
  55248. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  55249. }
  55250. this._debugMesh.color = this.color;
  55251. };
  55252. SkeletonViewer.prototype.dispose = function () {
  55253. if (this._debugMesh) {
  55254. this.isEnabled = false;
  55255. this._debugMesh.dispose();
  55256. this._debugMesh = null;
  55257. }
  55258. };
  55259. return SkeletonViewer;
  55260. }());
  55261. Debug.SkeletonViewer = SkeletonViewer;
  55262. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55263. })(BABYLON || (BABYLON = {}));
  55264. //# sourceMappingURL=babylon.skeletonViewer.js.map
  55265. var BABYLON;
  55266. (function (BABYLON) {
  55267. var Debug;
  55268. (function (Debug) {
  55269. var AxesViewer = (function () {
  55270. function AxesViewer(scene, scaleLines) {
  55271. if (scaleLines === void 0) { scaleLines = 1; }
  55272. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55273. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55274. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55275. this.scaleLines = 1;
  55276. this.scaleLines = scaleLines;
  55277. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  55278. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  55279. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  55280. this._xmesh.renderingGroupId = 2;
  55281. this._ymesh.renderingGroupId = 2;
  55282. this._zmesh.renderingGroupId = 2;
  55283. this._xmesh.material.checkReadyOnlyOnce = true;
  55284. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  55285. this._ymesh.material.checkReadyOnlyOnce = true;
  55286. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  55287. this._zmesh.material.checkReadyOnlyOnce = true;
  55288. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  55289. this.scene = scene;
  55290. }
  55291. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  55292. var scaleLines = this.scaleLines;
  55293. var point1 = this._xline[0];
  55294. var point2 = this._xline[1];
  55295. point1.x = position.x;
  55296. point1.y = position.y;
  55297. point1.z = position.z;
  55298. point2.x = point1.x + xaxis.x * scaleLines;
  55299. point2.y = point1.y + xaxis.y * scaleLines;
  55300. point2.z = point1.z + xaxis.z * scaleLines;
  55301. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  55302. point1 = this._yline[0];
  55303. point2 = this._yline[1];
  55304. point1.x = position.x;
  55305. point1.y = position.y;
  55306. point1.z = position.z;
  55307. point2.x = point1.x + yaxis.x * scaleLines;
  55308. point2.y = point1.y + yaxis.y * scaleLines;
  55309. point2.z = point1.z + yaxis.z * scaleLines;
  55310. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  55311. point1 = this._zline[0];
  55312. point2 = this._zline[1];
  55313. point1.x = position.x;
  55314. point1.y = position.y;
  55315. point1.z = position.z;
  55316. point2.x = point1.x + zaxis.x * scaleLines;
  55317. point2.y = point1.y + zaxis.y * scaleLines;
  55318. point2.z = point1.z + zaxis.z * scaleLines;
  55319. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  55320. };
  55321. AxesViewer.prototype.dispose = function () {
  55322. if (this._xmesh) {
  55323. this._xmesh.dispose();
  55324. this._ymesh.dispose();
  55325. this._zmesh.dispose();
  55326. this._xmesh = null;
  55327. this._ymesh = null;
  55328. this._zmesh = null;
  55329. this._xline = null;
  55330. this._yline = null;
  55331. this._zline = null;
  55332. this.scene = null;
  55333. }
  55334. };
  55335. return AxesViewer;
  55336. }());
  55337. Debug.AxesViewer = AxesViewer;
  55338. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55339. })(BABYLON || (BABYLON = {}));
  55340. //# sourceMappingURL=babylon.axesViewer.js.map
  55341. var BABYLON;
  55342. (function (BABYLON) {
  55343. var Debug;
  55344. (function (Debug) {
  55345. var BoneAxesViewer = (function (_super) {
  55346. __extends(BoneAxesViewer, _super);
  55347. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  55348. if (scaleLines === void 0) { scaleLines = 1; }
  55349. var _this = _super.call(this, scene, scaleLines) || this;
  55350. _this.pos = BABYLON.Vector3.Zero();
  55351. _this.xaxis = BABYLON.Vector3.Zero();
  55352. _this.yaxis = BABYLON.Vector3.Zero();
  55353. _this.zaxis = BABYLON.Vector3.Zero();
  55354. _this.mesh = mesh;
  55355. _this.bone = bone;
  55356. return _this;
  55357. }
  55358. BoneAxesViewer.prototype.update = function () {
  55359. var bone = this.bone;
  55360. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  55361. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  55362. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  55363. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  55364. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  55365. };
  55366. BoneAxesViewer.prototype.dispose = function () {
  55367. if (this.pos) {
  55368. this.pos = null;
  55369. this.xaxis = null;
  55370. this.yaxis = null;
  55371. this.zaxis = null;
  55372. this.mesh = null;
  55373. this.bone = null;
  55374. _super.prototype.dispose.call(this);
  55375. }
  55376. };
  55377. return BoneAxesViewer;
  55378. }(Debug.AxesViewer));
  55379. Debug.BoneAxesViewer = BoneAxesViewer;
  55380. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55381. })(BABYLON || (BABYLON = {}));
  55382. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  55383. var BABYLON;
  55384. (function (BABYLON) {
  55385. var RayHelper = (function () {
  55386. function RayHelper(ray) {
  55387. this.ray = ray;
  55388. }
  55389. RayHelper.CreateAndShow = function (ray, scene, color) {
  55390. var helper = new RayHelper(ray);
  55391. helper.show(scene, color);
  55392. return helper;
  55393. };
  55394. RayHelper.prototype.show = function (scene, color) {
  55395. if (!this._renderFunction) {
  55396. var ray = this.ray;
  55397. this._renderFunction = this._render.bind(this);
  55398. this._scene = scene;
  55399. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  55400. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  55401. this._scene.registerBeforeRender(this._renderFunction);
  55402. }
  55403. if (color) {
  55404. this._renderLine.color.copyFrom(color);
  55405. }
  55406. };
  55407. RayHelper.prototype.hide = function () {
  55408. if (this._renderFunction) {
  55409. this._scene.unregisterBeforeRender(this._renderFunction);
  55410. this._scene = null;
  55411. this._renderFunction = null;
  55412. this._renderLine.dispose();
  55413. this._renderLine = null;
  55414. this._renderPoints = null;
  55415. }
  55416. };
  55417. RayHelper.prototype._render = function () {
  55418. var ray = this.ray;
  55419. var point = this._renderPoints[1];
  55420. var len = Math.min(ray.length, 1000000);
  55421. point.copyFrom(ray.direction);
  55422. point.scaleInPlace(len);
  55423. point.addInPlace(ray.origin);
  55424. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  55425. };
  55426. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  55427. this._attachedToMesh = mesh;
  55428. var ray = this.ray;
  55429. if (!ray.direction) {
  55430. ray.direction = BABYLON.Vector3.Zero();
  55431. }
  55432. if (!ray.origin) {
  55433. ray.origin = BABYLON.Vector3.Zero();
  55434. }
  55435. if (length) {
  55436. ray.length = length;
  55437. }
  55438. if (!meshSpaceOrigin) {
  55439. meshSpaceOrigin = BABYLON.Vector3.Zero();
  55440. }
  55441. if (!meshSpaceDirection) {
  55442. // -1 so that this will work with Mesh.lookAt
  55443. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  55444. }
  55445. if (!this._meshSpaceDirection) {
  55446. this._meshSpaceDirection = meshSpaceDirection.clone();
  55447. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  55448. }
  55449. else {
  55450. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  55451. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  55452. }
  55453. if (!this._updateToMeshFunction) {
  55454. this._updateToMeshFunction = this._updateToMesh.bind(this);
  55455. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  55456. }
  55457. this._updateToMesh();
  55458. };
  55459. RayHelper.prototype.detachFromMesh = function () {
  55460. if (this._attachedToMesh) {
  55461. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  55462. this._attachedToMesh = null;
  55463. this._updateToMeshFunction = null;
  55464. }
  55465. };
  55466. RayHelper.prototype._updateToMesh = function () {
  55467. var ray = this.ray;
  55468. if (this._attachedToMesh._isDisposed) {
  55469. this.detachFromMesh();
  55470. return;
  55471. }
  55472. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  55473. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  55474. };
  55475. RayHelper.prototype.dispose = function () {
  55476. this.hide();
  55477. this.detachFromMesh();
  55478. this.ray = null;
  55479. };
  55480. return RayHelper;
  55481. }());
  55482. BABYLON.RayHelper = RayHelper;
  55483. })(BABYLON || (BABYLON = {}));
  55484. //# sourceMappingURL=babylon.rayHelper.js.map
  55485. var BABYLON;
  55486. (function (BABYLON) {
  55487. var DebugLayer = (function () {
  55488. function DebugLayer(scene) {
  55489. this._scene = scene;
  55490. }
  55491. /** Creates the inspector window. */
  55492. DebugLayer.prototype._createInspector = function (config) {
  55493. if (config === void 0) { config = {}; }
  55494. var popup = config.popup || false;
  55495. var initialTab = config.initialTab || 0;
  55496. var parentElement = config.parentElement || null;
  55497. if (!this._inspector) {
  55498. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  55499. } // else nothing to do,; instance is already existing
  55500. };
  55501. DebugLayer.prototype.isVisible = function () {
  55502. if (!this._inspector) {
  55503. return false;
  55504. }
  55505. return true;
  55506. };
  55507. DebugLayer.prototype.hide = function () {
  55508. if (this._inspector) {
  55509. try {
  55510. this._inspector.dispose();
  55511. }
  55512. catch (e) {
  55513. // If the inspector has been removed directly from the inspector tool
  55514. }
  55515. this._inspector = null;
  55516. }
  55517. };
  55518. DebugLayer.prototype.show = function (config) {
  55519. if (config === void 0) { config = {}; }
  55520. if (typeof INSPECTOR == 'undefined') {
  55521. // Load inspector and add it to the DOM
  55522. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  55523. }
  55524. else {
  55525. // Otherwise creates the inspector
  55526. this._createInspector(config);
  55527. }
  55528. };
  55529. return DebugLayer;
  55530. }());
  55531. // Get protocol used - http or https
  55532. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  55533. BABYLON.DebugLayer = DebugLayer;
  55534. })(BABYLON || (BABYLON = {}));
  55535. //# sourceMappingURL=babylon.debugLayer.js.map
  55536. var BABYLON;
  55537. (function (BABYLON) {
  55538. var BoundingBoxRenderer = (function () {
  55539. function BoundingBoxRenderer(scene) {
  55540. this.frontColor = new BABYLON.Color3(1, 1, 1);
  55541. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  55542. this.showBackLines = true;
  55543. this.renderList = new BABYLON.SmartArray(32);
  55544. this._vertexBuffers = {};
  55545. this._scene = scene;
  55546. }
  55547. BoundingBoxRenderer.prototype._prepareRessources = function () {
  55548. if (this._colorShader) {
  55549. return;
  55550. }
  55551. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  55552. attributes: [BABYLON.VertexBuffer.PositionKind],
  55553. uniforms: ["worldViewProjection", "color"]
  55554. });
  55555. var engine = this._scene.getEngine();
  55556. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  55557. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  55558. 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]);
  55559. };
  55560. BoundingBoxRenderer.prototype.reset = function () {
  55561. this.renderList.reset();
  55562. };
  55563. BoundingBoxRenderer.prototype.render = function () {
  55564. if (this.renderList.length === 0) {
  55565. return;
  55566. }
  55567. this._prepareRessources();
  55568. if (!this._colorShader.isReady()) {
  55569. return;
  55570. }
  55571. var engine = this._scene.getEngine();
  55572. engine.setDepthWrite(false);
  55573. this._colorShader._preBind();
  55574. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  55575. var boundingBox = this.renderList.data[boundingBoxIndex];
  55576. var min = boundingBox.minimum;
  55577. var max = boundingBox.maximum;
  55578. var diff = max.subtract(min);
  55579. var median = min.add(diff.scale(0.5));
  55580. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  55581. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  55582. .multiply(boundingBox.getWorldMatrix());
  55583. // VBOs
  55584. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  55585. if (this.showBackLines) {
  55586. // Back
  55587. engine.setDepthFunctionToGreaterOrEqual();
  55588. this._scene.resetCachedMaterial();
  55589. this._colorShader.setColor4("color", this.backColor.toColor4());
  55590. this._colorShader.bind(worldMatrix);
  55591. // Draw order
  55592. engine.draw(false, 0, 24);
  55593. }
  55594. // Front
  55595. engine.setDepthFunctionToLess();
  55596. this._scene.resetCachedMaterial();
  55597. this._colorShader.setColor4("color", this.frontColor.toColor4());
  55598. this._colorShader.bind(worldMatrix);
  55599. // Draw order
  55600. engine.draw(false, 0, 24);
  55601. }
  55602. this._colorShader.unbind();
  55603. engine.setDepthFunctionToLessOrEqual();
  55604. engine.setDepthWrite(true);
  55605. };
  55606. BoundingBoxRenderer.prototype.dispose = function () {
  55607. if (!this._colorShader) {
  55608. return;
  55609. }
  55610. this.renderList.dispose();
  55611. this._colorShader.dispose();
  55612. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55613. if (buffer) {
  55614. buffer.dispose();
  55615. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  55616. }
  55617. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55618. };
  55619. return BoundingBoxRenderer;
  55620. }());
  55621. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  55622. })(BABYLON || (BABYLON = {}));
  55623. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  55624. var BABYLON;
  55625. (function (BABYLON) {
  55626. var MorphTarget = (function () {
  55627. function MorphTarget(name, influence) {
  55628. if (influence === void 0) { influence = 0; }
  55629. this.name = name;
  55630. this.onInfluenceChanged = new BABYLON.Observable();
  55631. this.influence = influence;
  55632. }
  55633. Object.defineProperty(MorphTarget.prototype, "influence", {
  55634. get: function () {
  55635. return this._influence;
  55636. },
  55637. set: function (influence) {
  55638. if (this._influence === influence) {
  55639. return;
  55640. }
  55641. var previous = this._influence;
  55642. this._influence = influence;
  55643. if (this.onInfluenceChanged.hasObservers) {
  55644. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  55645. }
  55646. },
  55647. enumerable: true,
  55648. configurable: true
  55649. });
  55650. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  55651. get: function () {
  55652. return this._normals !== undefined;
  55653. },
  55654. enumerable: true,
  55655. configurable: true
  55656. });
  55657. MorphTarget.prototype.setPositions = function (data) {
  55658. this._positions = new Float32Array(data);
  55659. };
  55660. MorphTarget.prototype.getPositions = function () {
  55661. return this._positions;
  55662. };
  55663. MorphTarget.prototype.setNormals = function (data) {
  55664. this._normals = new Float32Array(data);
  55665. };
  55666. MorphTarget.prototype.getNormals = function () {
  55667. return this._normals;
  55668. };
  55669. /**
  55670. * Serializes the current target into a Serialization object.
  55671. * Returns the serialized object.
  55672. */
  55673. MorphTarget.prototype.serialize = function () {
  55674. var serializationObject = {};
  55675. serializationObject.name = this.name;
  55676. serializationObject.influence = this.influence;
  55677. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  55678. if (this.hasNormals) {
  55679. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  55680. }
  55681. return serializationObject;
  55682. };
  55683. // Statics
  55684. MorphTarget.Parse = function (serializationObject) {
  55685. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  55686. result.setPositions(serializationObject.positions);
  55687. if (serializationObject.normals) {
  55688. result.setNormals(serializationObject.normals);
  55689. }
  55690. return result;
  55691. };
  55692. MorphTarget.FromMesh = function (mesh, name, influence) {
  55693. if (!name) {
  55694. name = mesh.name;
  55695. }
  55696. var result = new MorphTarget(name, influence);
  55697. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  55698. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55699. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  55700. }
  55701. return result;
  55702. };
  55703. return MorphTarget;
  55704. }());
  55705. BABYLON.MorphTarget = MorphTarget;
  55706. })(BABYLON || (BABYLON = {}));
  55707. //# sourceMappingURL=babylon.morphTarget.js.map
  55708. var BABYLON;
  55709. (function (BABYLON) {
  55710. var MorphTargetManager = (function () {
  55711. function MorphTargetManager(scene) {
  55712. this._targets = new Array();
  55713. this._targetObservable = new Array();
  55714. this._activeTargets = new BABYLON.SmartArray(16);
  55715. this._supportsNormals = false;
  55716. this._vertexCount = 0;
  55717. this._uniqueId = 0;
  55718. if (!scene) {
  55719. scene = BABYLON.Engine.LastCreatedScene;
  55720. }
  55721. this._scene = scene;
  55722. this._scene.morphTargetManagers.push(this);
  55723. this._uniqueId = scene.getUniqueId();
  55724. }
  55725. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  55726. get: function () {
  55727. return this._uniqueId;
  55728. },
  55729. enumerable: true,
  55730. configurable: true
  55731. });
  55732. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  55733. get: function () {
  55734. return this._vertexCount;
  55735. },
  55736. enumerable: true,
  55737. configurable: true
  55738. });
  55739. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  55740. get: function () {
  55741. return this._supportsNormals;
  55742. },
  55743. enumerable: true,
  55744. configurable: true
  55745. });
  55746. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  55747. get: function () {
  55748. return this._activeTargets.length;
  55749. },
  55750. enumerable: true,
  55751. configurable: true
  55752. });
  55753. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  55754. get: function () {
  55755. return this._influences;
  55756. },
  55757. enumerable: true,
  55758. configurable: true
  55759. });
  55760. MorphTargetManager.prototype.getActiveTarget = function (index) {
  55761. return this._activeTargets.data[index];
  55762. };
  55763. MorphTargetManager.prototype.addTarget = function (target) {
  55764. var _this = this;
  55765. if (this._vertexCount) {
  55766. if (this._vertexCount !== target.getPositions().length / 3) {
  55767. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  55768. return;
  55769. }
  55770. }
  55771. this._targets.push(target);
  55772. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  55773. _this._syncActiveTargets(needUpdate);
  55774. }));
  55775. this._syncActiveTargets(true);
  55776. };
  55777. MorphTargetManager.prototype.removeTarget = function (target) {
  55778. var index = this._targets.indexOf(target);
  55779. if (index >= 0) {
  55780. this._targets.splice(index, 1);
  55781. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  55782. this._vertexCount = 0;
  55783. this._syncActiveTargets(true);
  55784. }
  55785. };
  55786. /**
  55787. * Serializes the current manager into a Serialization object.
  55788. * Returns the serialized object.
  55789. */
  55790. MorphTargetManager.prototype.serialize = function () {
  55791. var serializationObject = {};
  55792. serializationObject.id = this.uniqueId;
  55793. serializationObject.targets = [];
  55794. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  55795. var target = _a[_i];
  55796. serializationObject.targets.push(target.serialize());
  55797. }
  55798. return serializationObject;
  55799. };
  55800. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  55801. this._syncActiveTargets(needUpdate);
  55802. };
  55803. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  55804. this._activeTargets.reset();
  55805. var tempInfluences = [];
  55806. this._supportsNormals = true;
  55807. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  55808. var target = _a[_i];
  55809. if (target.influence > 0) {
  55810. this._activeTargets.push(target);
  55811. tempInfluences.push(target.influence);
  55812. this._supportsNormals = this._supportsNormals && target.hasNormals;
  55813. if (this._vertexCount === 0) {
  55814. this._vertexCount = target.getPositions().length / 3;
  55815. }
  55816. }
  55817. }
  55818. this._influences = new Float32Array(tempInfluences);
  55819. if (needUpdate) {
  55820. // Flag meshes as dirty to resync with the active targets
  55821. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  55822. var mesh = _c[_b];
  55823. if (mesh.morphTargetManager === this) {
  55824. mesh._syncGeometryWithMorphTargetManager();
  55825. }
  55826. }
  55827. }
  55828. };
  55829. // Statics
  55830. MorphTargetManager.Parse = function (serializationObject, scene) {
  55831. var result = new MorphTargetManager(scene);
  55832. result._uniqueId = serializationObject.id;
  55833. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  55834. var targetData = _a[_i];
  55835. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  55836. }
  55837. return result;
  55838. };
  55839. return MorphTargetManager;
  55840. }());
  55841. BABYLON.MorphTargetManager = MorphTargetManager;
  55842. })(BABYLON || (BABYLON = {}));
  55843. //# sourceMappingURL=babylon.morphTargetManager.js.map
  55844. var BABYLON;
  55845. (function (BABYLON) {
  55846. /**
  55847. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  55848. * It can help converting any input color in a desired output one. This can then be used to create effects
  55849. * from sepia, black and white to sixties or futuristic rendering...
  55850. *
  55851. * The only supported format is currently 3dl.
  55852. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  55853. */
  55854. var ColorGradingTexture = (function (_super) {
  55855. __extends(ColorGradingTexture, _super);
  55856. /**
  55857. * Instantiates a ColorGradingTexture from the following parameters.
  55858. *
  55859. * @param url The location of the color gradind data (currently only supporting 3dl)
  55860. * @param scene The scene the texture will be used in
  55861. */
  55862. function ColorGradingTexture(url, scene) {
  55863. var _this = _super.call(this, scene) || this;
  55864. if (!url) {
  55865. return _this;
  55866. }
  55867. _this._textureMatrix = BABYLON.Matrix.Identity();
  55868. _this.name = url;
  55869. _this.url = url;
  55870. _this.hasAlpha = false;
  55871. _this.isCube = false;
  55872. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55873. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55874. _this.anisotropicFilteringLevel = 1;
  55875. _this._texture = _this._getFromCache(url, true);
  55876. if (!_this._texture) {
  55877. if (!scene.useDelayedTextureLoading) {
  55878. _this.loadTexture();
  55879. }
  55880. else {
  55881. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55882. }
  55883. }
  55884. return _this;
  55885. }
  55886. /**
  55887. * Returns the texture matrix used in most of the material.
  55888. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  55889. */
  55890. ColorGradingTexture.prototype.getTextureMatrix = function () {
  55891. return this._textureMatrix;
  55892. };
  55893. /**
  55894. * Occurs when the file being loaded is a .3dl LUT file.
  55895. */
  55896. ColorGradingTexture.prototype.load3dlTexture = function () {
  55897. var _this = this;
  55898. var mipLevels = 0;
  55899. var floatArrayView = null;
  55900. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55901. this._texture = texture;
  55902. var callback = function (text) {
  55903. var data;
  55904. var tempData;
  55905. var line;
  55906. var lines = text.split('\n');
  55907. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  55908. var maxColor = 0;
  55909. for (var i = 0; i < lines.length; i++) {
  55910. line = lines[i];
  55911. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  55912. continue;
  55913. if (line.indexOf('#') === 0)
  55914. continue;
  55915. var words = line.split(" ");
  55916. if (size === 0) {
  55917. // Number of space + one
  55918. size = words.length;
  55919. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  55920. tempData = new Float32Array(size * size * size * 4);
  55921. continue;
  55922. }
  55923. if (size != 0) {
  55924. var r = Math.max(parseInt(words[0]), 0);
  55925. var g = Math.max(parseInt(words[1]), 0);
  55926. var b = Math.max(parseInt(words[2]), 0);
  55927. maxColor = Math.max(r, maxColor);
  55928. maxColor = Math.max(g, maxColor);
  55929. maxColor = Math.max(b, maxColor);
  55930. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  55931. tempData[pixelStorageIndex + 0] = r;
  55932. tempData[pixelStorageIndex + 1] = g;
  55933. tempData[pixelStorageIndex + 2] = b;
  55934. tempData[pixelStorageIndex + 3] = 0;
  55935. pixelIndexSlice++;
  55936. if (pixelIndexSlice % size == 0) {
  55937. pixelIndexH++;
  55938. pixelIndexSlice = 0;
  55939. if (pixelIndexH % size == 0) {
  55940. pixelIndexW++;
  55941. pixelIndexH = 0;
  55942. }
  55943. }
  55944. }
  55945. }
  55946. for (var i = 0; i < tempData.length; i++) {
  55947. var value = tempData[i];
  55948. data[i] = (value / maxColor * 255);
  55949. }
  55950. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  55951. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  55952. };
  55953. BABYLON.Tools.LoadFile(this.url, callback);
  55954. return this._texture;
  55955. };
  55956. /**
  55957. * Starts the loading process of the texture.
  55958. */
  55959. ColorGradingTexture.prototype.loadTexture = function () {
  55960. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  55961. this.load3dlTexture();
  55962. }
  55963. };
  55964. /**
  55965. * Clones the color gradind texture.
  55966. */
  55967. ColorGradingTexture.prototype.clone = function () {
  55968. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  55969. // Base texture
  55970. newTexture.level = this.level;
  55971. return newTexture;
  55972. };
  55973. /**
  55974. * Called during delayed load for textures.
  55975. */
  55976. ColorGradingTexture.prototype.delayLoad = function () {
  55977. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55978. return;
  55979. }
  55980. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55981. this._texture = this._getFromCache(this.url, true);
  55982. if (!this._texture) {
  55983. this.loadTexture();
  55984. }
  55985. };
  55986. /**
  55987. * Binds the color grading to the shader.
  55988. * @param colorGrading The texture to bind
  55989. * @param effect The effect to bind to
  55990. */
  55991. ColorGradingTexture.Bind = function (colorGrading, effect) {
  55992. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  55993. var x = colorGrading.level; // Texture Level
  55994. var y = colorGrading.getSize().height; // Texture Size example with 8
  55995. var z = y - 1.0; // SizeMinusOne 8 - 1
  55996. var w = 1 / y; // Space of 1 slice 1 / 8
  55997. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  55998. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  55999. 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
  56000. 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
  56001. 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
  56002. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  56003. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  56004. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  56005. };
  56006. /**
  56007. * Prepare the list of uniforms associated with the ColorGrading effects.
  56008. * @param uniformsList The list of uniforms used in the effect
  56009. * @param samplersList The list of samplers used in the effect
  56010. */
  56011. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  56012. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  56013. samplersList.push("cameraColorGrading2DSampler");
  56014. };
  56015. /**
  56016. * Parses a color grading texture serialized by Babylon.
  56017. * @param parsedTexture The texture information being parsedTexture
  56018. * @param scene The scene to load the texture in
  56019. * @param rootUrl The root url of the data assets to load
  56020. * @return A color gradind texture
  56021. */
  56022. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56023. var texture = null;
  56024. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56025. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  56026. texture.name = parsedTexture.name;
  56027. texture.level = parsedTexture.level;
  56028. }
  56029. return texture;
  56030. };
  56031. /**
  56032. * Serializes the LUT texture to json format.
  56033. */
  56034. ColorGradingTexture.prototype.serialize = function () {
  56035. if (!this.name) {
  56036. return null;
  56037. }
  56038. var serializationObject = {};
  56039. serializationObject.name = this.name;
  56040. serializationObject.level = this.level;
  56041. serializationObject.customType = "BABYLON.ColorGradingTexture";
  56042. return serializationObject;
  56043. };
  56044. return ColorGradingTexture;
  56045. }(BABYLON.BaseTexture));
  56046. /**
  56047. * Empty line regex stored for GC.
  56048. */
  56049. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  56050. BABYLON.ColorGradingTexture = ColorGradingTexture;
  56051. })(BABYLON || (BABYLON = {}));
  56052. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  56053. var BABYLON;
  56054. (function (BABYLON) {
  56055. /**
  56056. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  56057. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  56058. * 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;
  56059. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  56060. */
  56061. var ColorCurves = (function () {
  56062. function ColorCurves() {
  56063. this._dirty = true;
  56064. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  56065. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  56066. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  56067. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  56068. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  56069. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  56070. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  56071. this._globalHue = 30;
  56072. this._globalDensity = 0;
  56073. this._globalSaturation = 0;
  56074. this._globalExposure = 0;
  56075. this._highlightsHue = 30;
  56076. this._highlightsDensity = 0;
  56077. this._highlightsSaturation = 0;
  56078. this._highlightsExposure = 0;
  56079. this._midtonesHue = 30;
  56080. this._midtonesDensity = 0;
  56081. this._midtonesSaturation = 0;
  56082. this._midtonesExposure = 0;
  56083. this._shadowsHue = 30;
  56084. this._shadowsDensity = 0;
  56085. this._shadowsSaturation = 0;
  56086. this._shadowsExposure = 0;
  56087. }
  56088. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  56089. /**
  56090. * Gets the global Hue value.
  56091. * 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).
  56092. */
  56093. get: function () {
  56094. return this._globalHue;
  56095. },
  56096. /**
  56097. * Sets the global Hue value.
  56098. * 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).
  56099. */
  56100. set: function (value) {
  56101. this._globalHue = value;
  56102. this._dirty = true;
  56103. },
  56104. enumerable: true,
  56105. configurable: true
  56106. });
  56107. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  56108. /**
  56109. * Gets the global Density value.
  56110. * 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.
  56111. * Values less than zero provide a filter of opposite hue.
  56112. */
  56113. get: function () {
  56114. return this._globalDensity;
  56115. },
  56116. /**
  56117. * Sets the global Density value.
  56118. * 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.
  56119. * Values less than zero provide a filter of opposite hue.
  56120. */
  56121. set: function (value) {
  56122. this._globalDensity = value;
  56123. this._dirty = true;
  56124. },
  56125. enumerable: true,
  56126. configurable: true
  56127. });
  56128. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  56129. /**
  56130. * Gets the global Saturation value.
  56131. * 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.
  56132. */
  56133. get: function () {
  56134. return this._globalSaturation;
  56135. },
  56136. /**
  56137. * Sets the global Saturation value.
  56138. * 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.
  56139. */
  56140. set: function (value) {
  56141. this._globalSaturation = value;
  56142. this._dirty = true;
  56143. },
  56144. enumerable: true,
  56145. configurable: true
  56146. });
  56147. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  56148. /**
  56149. * Gets the highlights Hue value.
  56150. * 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).
  56151. */
  56152. get: function () {
  56153. return this._highlightsHue;
  56154. },
  56155. /**
  56156. * Sets the highlights Hue value.
  56157. * 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).
  56158. */
  56159. set: function (value) {
  56160. this._highlightsHue = value;
  56161. this._dirty = true;
  56162. },
  56163. enumerable: true,
  56164. configurable: true
  56165. });
  56166. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  56167. /**
  56168. * Gets the highlights Density value.
  56169. * 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.
  56170. * Values less than zero provide a filter of opposite hue.
  56171. */
  56172. get: function () {
  56173. return this._highlightsDensity;
  56174. },
  56175. /**
  56176. * Sets the highlights Density value.
  56177. * 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.
  56178. * Values less than zero provide a filter of opposite hue.
  56179. */
  56180. set: function (value) {
  56181. this._highlightsDensity = value;
  56182. this._dirty = true;
  56183. },
  56184. enumerable: true,
  56185. configurable: true
  56186. });
  56187. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  56188. /**
  56189. * Gets the highlights Saturation value.
  56190. * 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.
  56191. */
  56192. get: function () {
  56193. return this._highlightsSaturation;
  56194. },
  56195. /**
  56196. * Sets the highlights Saturation value.
  56197. * 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.
  56198. */
  56199. set: function (value) {
  56200. this._highlightsSaturation = value;
  56201. this._dirty = true;
  56202. },
  56203. enumerable: true,
  56204. configurable: true
  56205. });
  56206. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  56207. /**
  56208. * Gets the highlights Exposure value.
  56209. * 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.
  56210. */
  56211. get: function () {
  56212. return this._highlightsExposure;
  56213. },
  56214. /**
  56215. * Sets the highlights Exposure value.
  56216. * 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.
  56217. */
  56218. set: function (value) {
  56219. this._highlightsExposure = value;
  56220. this._dirty = true;
  56221. },
  56222. enumerable: true,
  56223. configurable: true
  56224. });
  56225. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  56226. /**
  56227. * Gets the midtones Hue value.
  56228. * 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).
  56229. */
  56230. get: function () {
  56231. return this._midtonesHue;
  56232. },
  56233. /**
  56234. * Sets the midtones Hue value.
  56235. * 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).
  56236. */
  56237. set: function (value) {
  56238. this._midtonesHue = value;
  56239. this._dirty = true;
  56240. },
  56241. enumerable: true,
  56242. configurable: true
  56243. });
  56244. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  56245. /**
  56246. * Gets the midtones Density value.
  56247. * 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.
  56248. * Values less than zero provide a filter of opposite hue.
  56249. */
  56250. get: function () {
  56251. return this._midtonesDensity;
  56252. },
  56253. /**
  56254. * Sets the midtones Density value.
  56255. * 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.
  56256. * Values less than zero provide a filter of opposite hue.
  56257. */
  56258. set: function (value) {
  56259. this._midtonesDensity = value;
  56260. this._dirty = true;
  56261. },
  56262. enumerable: true,
  56263. configurable: true
  56264. });
  56265. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  56266. /**
  56267. * Gets the midtones Saturation value.
  56268. * 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.
  56269. */
  56270. get: function () {
  56271. return this._midtonesSaturation;
  56272. },
  56273. /**
  56274. * Sets the midtones Saturation value.
  56275. * 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.
  56276. */
  56277. set: function (value) {
  56278. this._midtonesSaturation = value;
  56279. this._dirty = true;
  56280. },
  56281. enumerable: true,
  56282. configurable: true
  56283. });
  56284. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  56285. /**
  56286. * Gets the midtones Exposure value.
  56287. * 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.
  56288. */
  56289. get: function () {
  56290. return this._midtonesExposure;
  56291. },
  56292. /**
  56293. * Sets the midtones Exposure value.
  56294. * 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.
  56295. */
  56296. set: function (value) {
  56297. this._midtonesExposure = value;
  56298. this._dirty = true;
  56299. },
  56300. enumerable: true,
  56301. configurable: true
  56302. });
  56303. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  56304. /**
  56305. * Gets the shadows Hue value.
  56306. * 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).
  56307. */
  56308. get: function () {
  56309. return this._shadowsHue;
  56310. },
  56311. /**
  56312. * Sets the shadows Hue value.
  56313. * 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).
  56314. */
  56315. set: function (value) {
  56316. this._shadowsHue = value;
  56317. this._dirty = true;
  56318. },
  56319. enumerable: true,
  56320. configurable: true
  56321. });
  56322. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  56323. /**
  56324. * Gets the shadows Density value.
  56325. * 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.
  56326. * Values less than zero provide a filter of opposite hue.
  56327. */
  56328. get: function () {
  56329. return this._shadowsDensity;
  56330. },
  56331. /**
  56332. * Sets the shadows Density value.
  56333. * 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.
  56334. * Values less than zero provide a filter of opposite hue.
  56335. */
  56336. set: function (value) {
  56337. this._shadowsDensity = value;
  56338. this._dirty = true;
  56339. },
  56340. enumerable: true,
  56341. configurable: true
  56342. });
  56343. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  56344. /**
  56345. * Gets the shadows Saturation value.
  56346. * 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.
  56347. */
  56348. get: function () {
  56349. return this._shadowsSaturation;
  56350. },
  56351. /**
  56352. * Sets the shadows Saturation value.
  56353. * 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.
  56354. */
  56355. set: function (value) {
  56356. this._shadowsSaturation = value;
  56357. this._dirty = true;
  56358. },
  56359. enumerable: true,
  56360. configurable: true
  56361. });
  56362. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  56363. /**
  56364. * Gets the shadows Exposure value.
  56365. * 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.
  56366. */
  56367. get: function () {
  56368. return this._shadowsExposure;
  56369. },
  56370. /**
  56371. * Sets the shadows Exposure value.
  56372. * 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.
  56373. */
  56374. set: function (value) {
  56375. this._shadowsExposure = value;
  56376. this._dirty = true;
  56377. },
  56378. enumerable: true,
  56379. configurable: true
  56380. });
  56381. /**
  56382. * Binds the color curves to the shader.
  56383. * @param colorCurves The color curve to bind
  56384. * @param effect The effect to bind to
  56385. */
  56386. ColorCurves.Bind = function (colorCurves, effect) {
  56387. if (colorCurves._dirty) {
  56388. colorCurves._dirty = false;
  56389. // Fill in global info.
  56390. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  56391. // Compute highlights info.
  56392. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  56393. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  56394. // Compute midtones info.
  56395. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  56396. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  56397. // Compute shadows info.
  56398. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  56399. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  56400. // Compute deltas (neutral is midtones).
  56401. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  56402. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  56403. }
  56404. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  56405. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  56406. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  56407. };
  56408. /**
  56409. * Prepare the list of uniforms associated with the ColorCurves effects.
  56410. * @param uniformsList The list of uniforms used in the effect
  56411. */
  56412. ColorCurves.PrepareUniforms = function (uniformsList) {
  56413. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  56414. };
  56415. /**
  56416. * Returns color grading data based on a hue, density, saturation and exposure value.
  56417. * @param filterHue The hue of the color filter.
  56418. * @param filterDensity The density of the color filter.
  56419. * @param saturation The saturation.
  56420. * @param exposure The exposure.
  56421. * @param result The result data container.
  56422. */
  56423. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  56424. if (hue == null) {
  56425. return;
  56426. }
  56427. hue = ColorCurves.clamp(hue, 0, 360);
  56428. density = ColorCurves.clamp(density, -100, 100);
  56429. saturation = ColorCurves.clamp(saturation, -100, 100);
  56430. exposure = ColorCurves.clamp(exposure, -100, 100);
  56431. // Remap the slider/config filter density with non-linear mapping and also scale by half
  56432. // so that the maximum filter density is only 50% control. This provides fine control
  56433. // for small values and reasonable range.
  56434. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  56435. density *= 0.5;
  56436. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  56437. if (density < 0) {
  56438. density *= -1;
  56439. hue = (hue + 180) % 360;
  56440. }
  56441. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  56442. result.scaleToRef(2, result);
  56443. result.a = 1 + 0.01 * saturation;
  56444. };
  56445. /**
  56446. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  56447. * @param value The input slider value in range [-100,100].
  56448. * @returns Adjusted value.
  56449. */
  56450. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  56451. value /= 100;
  56452. var x = Math.abs(value);
  56453. x = Math.pow(x, 2);
  56454. if (value < 0) {
  56455. x *= -1;
  56456. }
  56457. x *= 100;
  56458. return x;
  56459. };
  56460. /**
  56461. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  56462. * @param hue The hue (H) input.
  56463. * @param saturation The saturation (S) input.
  56464. * @param brightness The brightness (B) input.
  56465. * @result An RGBA color represented as Vector4.
  56466. */
  56467. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  56468. var h = ColorCurves.clamp(hue, 0, 360);
  56469. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  56470. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  56471. if (s === 0) {
  56472. result.r = v;
  56473. result.g = v;
  56474. result.b = v;
  56475. }
  56476. else {
  56477. // sector 0 to 5
  56478. h /= 60;
  56479. var i = Math.floor(h);
  56480. // fractional part of h
  56481. var f = h - i;
  56482. var p = v * (1 - s);
  56483. var q = v * (1 - s * f);
  56484. var t = v * (1 - s * (1 - f));
  56485. switch (i) {
  56486. case 0:
  56487. result.r = v;
  56488. result.g = t;
  56489. result.b = p;
  56490. break;
  56491. case 1:
  56492. result.r = q;
  56493. result.g = v;
  56494. result.b = p;
  56495. break;
  56496. case 2:
  56497. result.r = p;
  56498. result.g = v;
  56499. result.b = t;
  56500. break;
  56501. case 3:
  56502. result.r = p;
  56503. result.g = q;
  56504. result.b = v;
  56505. break;
  56506. case 4:
  56507. result.r = t;
  56508. result.g = p;
  56509. result.b = v;
  56510. break;
  56511. default:
  56512. result.r = v;
  56513. result.g = p;
  56514. result.b = q;
  56515. break;
  56516. }
  56517. }
  56518. result.a = 1;
  56519. };
  56520. /**
  56521. * Returns a value clamped between min and max
  56522. * @param value The value to clamp
  56523. * @param min The minimum of value
  56524. * @param max The maximum of value
  56525. * @returns The clamped value.
  56526. */
  56527. ColorCurves.clamp = function (value, min, max) {
  56528. return Math.min(Math.max(value, min), max);
  56529. };
  56530. /**
  56531. * Clones the current color curve instance.
  56532. * @return The cloned curves
  56533. */
  56534. ColorCurves.prototype.clone = function () {
  56535. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  56536. };
  56537. /**
  56538. * Serializes the current color curve instance to a json representation.
  56539. * @return a JSON representation
  56540. */
  56541. ColorCurves.prototype.serialize = function () {
  56542. return BABYLON.SerializationHelper.Serialize(this);
  56543. };
  56544. /**
  56545. * Parses the color curve from a json representation.
  56546. * @param source the JSON source to parse
  56547. * @return The parsed curves
  56548. */
  56549. ColorCurves.Parse = function (source) {
  56550. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  56551. };
  56552. return ColorCurves;
  56553. }());
  56554. __decorate([
  56555. BABYLON.serialize()
  56556. ], ColorCurves.prototype, "_globalHue", void 0);
  56557. __decorate([
  56558. BABYLON.serialize()
  56559. ], ColorCurves.prototype, "_globalDensity", void 0);
  56560. __decorate([
  56561. BABYLON.serialize()
  56562. ], ColorCurves.prototype, "_globalSaturation", void 0);
  56563. __decorate([
  56564. BABYLON.serialize()
  56565. ], ColorCurves.prototype, "_globalExposure", void 0);
  56566. __decorate([
  56567. BABYLON.serialize()
  56568. ], ColorCurves.prototype, "_highlightsHue", void 0);
  56569. __decorate([
  56570. BABYLON.serialize()
  56571. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  56572. __decorate([
  56573. BABYLON.serialize()
  56574. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  56575. __decorate([
  56576. BABYLON.serialize()
  56577. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  56578. __decorate([
  56579. BABYLON.serialize()
  56580. ], ColorCurves.prototype, "_midtonesHue", void 0);
  56581. __decorate([
  56582. BABYLON.serialize()
  56583. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  56584. __decorate([
  56585. BABYLON.serialize()
  56586. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  56587. __decorate([
  56588. BABYLON.serialize()
  56589. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  56590. BABYLON.ColorCurves = ColorCurves;
  56591. })(BABYLON || (BABYLON = {}));
  56592. //# sourceMappingURL=babylon.colorCurves.js.map
  56593. var BABYLON;
  56594. (function (BABYLON) {
  56595. var Octree = (function () {
  56596. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  56597. if (maxDepth === void 0) { maxDepth = 2; }
  56598. this.maxDepth = maxDepth;
  56599. this.dynamicContent = new Array();
  56600. this._maxBlockCapacity = maxBlockCapacity || 64;
  56601. this._selectionContent = new BABYLON.SmartArray(1024);
  56602. this._creationFunc = creationFunc;
  56603. }
  56604. // Methods
  56605. Octree.prototype.update = function (worldMin, worldMax, entries) {
  56606. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  56607. };
  56608. Octree.prototype.addMesh = function (entry) {
  56609. for (var index = 0; index < this.blocks.length; index++) {
  56610. var block = this.blocks[index];
  56611. block.addEntry(entry);
  56612. }
  56613. };
  56614. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  56615. this._selectionContent.reset();
  56616. for (var index = 0; index < this.blocks.length; index++) {
  56617. var block = this.blocks[index];
  56618. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  56619. }
  56620. if (allowDuplicate) {
  56621. this._selectionContent.concat(this.dynamicContent);
  56622. }
  56623. else {
  56624. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  56625. }
  56626. return this._selectionContent;
  56627. };
  56628. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  56629. this._selectionContent.reset();
  56630. for (var index = 0; index < this.blocks.length; index++) {
  56631. var block = this.blocks[index];
  56632. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  56633. }
  56634. if (allowDuplicate) {
  56635. this._selectionContent.concat(this.dynamicContent);
  56636. }
  56637. else {
  56638. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  56639. }
  56640. return this._selectionContent;
  56641. };
  56642. Octree.prototype.intersectsRay = function (ray) {
  56643. this._selectionContent.reset();
  56644. for (var index = 0; index < this.blocks.length; index++) {
  56645. var block = this.blocks[index];
  56646. block.intersectsRay(ray, this._selectionContent);
  56647. }
  56648. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  56649. return this._selectionContent;
  56650. };
  56651. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  56652. target.blocks = new Array();
  56653. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  56654. // Segmenting space
  56655. for (var x = 0; x < 2; x++) {
  56656. for (var y = 0; y < 2; y++) {
  56657. for (var z = 0; z < 2; z++) {
  56658. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  56659. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  56660. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  56661. block.addEntries(entries);
  56662. target.blocks.push(block);
  56663. }
  56664. }
  56665. }
  56666. };
  56667. return Octree;
  56668. }());
  56669. Octree.CreationFuncForMeshes = function (entry, block) {
  56670. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  56671. block.entries.push(entry);
  56672. }
  56673. };
  56674. Octree.CreationFuncForSubMeshes = function (entry, block) {
  56675. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  56676. block.entries.push(entry);
  56677. }
  56678. };
  56679. BABYLON.Octree = Octree;
  56680. })(BABYLON || (BABYLON = {}));
  56681. //# sourceMappingURL=babylon.octree.js.map
  56682. var BABYLON;
  56683. (function (BABYLON) {
  56684. var OctreeBlock = (function () {
  56685. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  56686. this.entries = new Array();
  56687. this._boundingVectors = new Array();
  56688. this._capacity = capacity;
  56689. this._depth = depth;
  56690. this._maxDepth = maxDepth;
  56691. this._creationFunc = creationFunc;
  56692. this._minPoint = minPoint;
  56693. this._maxPoint = maxPoint;
  56694. this._boundingVectors.push(minPoint.clone());
  56695. this._boundingVectors.push(maxPoint.clone());
  56696. this._boundingVectors.push(minPoint.clone());
  56697. this._boundingVectors[2].x = maxPoint.x;
  56698. this._boundingVectors.push(minPoint.clone());
  56699. this._boundingVectors[3].y = maxPoint.y;
  56700. this._boundingVectors.push(minPoint.clone());
  56701. this._boundingVectors[4].z = maxPoint.z;
  56702. this._boundingVectors.push(maxPoint.clone());
  56703. this._boundingVectors[5].z = minPoint.z;
  56704. this._boundingVectors.push(maxPoint.clone());
  56705. this._boundingVectors[6].x = minPoint.x;
  56706. this._boundingVectors.push(maxPoint.clone());
  56707. this._boundingVectors[7].y = minPoint.y;
  56708. }
  56709. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  56710. // Property
  56711. get: function () {
  56712. return this._capacity;
  56713. },
  56714. enumerable: true,
  56715. configurable: true
  56716. });
  56717. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  56718. get: function () {
  56719. return this._minPoint;
  56720. },
  56721. enumerable: true,
  56722. configurable: true
  56723. });
  56724. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  56725. get: function () {
  56726. return this._maxPoint;
  56727. },
  56728. enumerable: true,
  56729. configurable: true
  56730. });
  56731. // Methods
  56732. OctreeBlock.prototype.addEntry = function (entry) {
  56733. if (this.blocks) {
  56734. for (var index = 0; index < this.blocks.length; index++) {
  56735. var block = this.blocks[index];
  56736. block.addEntry(entry);
  56737. }
  56738. return;
  56739. }
  56740. this._creationFunc(entry, this);
  56741. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  56742. this.createInnerBlocks();
  56743. }
  56744. };
  56745. OctreeBlock.prototype.addEntries = function (entries) {
  56746. for (var index = 0; index < entries.length; index++) {
  56747. var mesh = entries[index];
  56748. this.addEntry(mesh);
  56749. }
  56750. };
  56751. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  56752. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  56753. if (this.blocks) {
  56754. for (var index = 0; index < this.blocks.length; index++) {
  56755. var block = this.blocks[index];
  56756. block.select(frustumPlanes, selection, allowDuplicate);
  56757. }
  56758. return;
  56759. }
  56760. if (allowDuplicate) {
  56761. selection.concat(this.entries);
  56762. }
  56763. else {
  56764. selection.concatWithNoDuplicate(this.entries);
  56765. }
  56766. }
  56767. };
  56768. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  56769. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  56770. if (this.blocks) {
  56771. for (var index = 0; index < this.blocks.length; index++) {
  56772. var block = this.blocks[index];
  56773. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  56774. }
  56775. return;
  56776. }
  56777. if (allowDuplicate) {
  56778. selection.concat(this.entries);
  56779. }
  56780. else {
  56781. selection.concatWithNoDuplicate(this.entries);
  56782. }
  56783. }
  56784. };
  56785. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  56786. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  56787. if (this.blocks) {
  56788. for (var index = 0; index < this.blocks.length; index++) {
  56789. var block = this.blocks[index];
  56790. block.intersectsRay(ray, selection);
  56791. }
  56792. return;
  56793. }
  56794. selection.concatWithNoDuplicate(this.entries);
  56795. }
  56796. };
  56797. OctreeBlock.prototype.createInnerBlocks = function () {
  56798. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  56799. };
  56800. return OctreeBlock;
  56801. }());
  56802. BABYLON.OctreeBlock = OctreeBlock;
  56803. })(BABYLON || (BABYLON = {}));
  56804. //# sourceMappingURL=babylon.octreeBlock.js.map
  56805. var BABYLON;
  56806. (function (BABYLON) {
  56807. var SIMDVector3 = (function () {
  56808. function SIMDVector3() {
  56809. }
  56810. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  56811. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  56812. };
  56813. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  56814. var m = transformation.m;
  56815. var m0 = SIMD.Float32x4.load(m, 0);
  56816. var m1 = SIMD.Float32x4.load(m, 4);
  56817. var m2 = SIMD.Float32x4.load(m, 8);
  56818. var m3 = SIMD.Float32x4.load(m, 12);
  56819. 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));
  56820. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  56821. result.x = SIMD.Float32x4.extractLane(r, 0);
  56822. result.y = SIMD.Float32x4.extractLane(r, 1);
  56823. result.z = SIMD.Float32x4.extractLane(r, 2);
  56824. };
  56825. return SIMDVector3;
  56826. }());
  56827. var SIMDMatrix = (function () {
  56828. function SIMDMatrix() {
  56829. }
  56830. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  56831. var tm = this.m;
  56832. var om = other.m;
  56833. var m0 = SIMD.Float32x4.load(om, 0);
  56834. var m1 = SIMD.Float32x4.load(om, 4);
  56835. var m2 = SIMD.Float32x4.load(om, 8);
  56836. var m3 = SIMD.Float32x4.load(om, 12);
  56837. for (var i = 0; i < 16; i += 4) {
  56838. 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)))));
  56839. }
  56840. return this;
  56841. };
  56842. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  56843. var src = this.m;
  56844. var dest = other.m;
  56845. // Load the 4 rows
  56846. var src0 = SIMD.Float32x4.load(src, 0);
  56847. var src1 = SIMD.Float32x4.load(src, 4);
  56848. var src2 = SIMD.Float32x4.load(src, 8);
  56849. var src3 = SIMD.Float32x4.load(src, 12);
  56850. // Transpose the source matrix. Sort of. Not a true transpose operation
  56851. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  56852. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  56853. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  56854. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  56855. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  56856. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  56857. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  56858. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  56859. // This is a true transposition, but it will lead to an incorrect result
  56860. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  56861. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  56862. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  56863. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  56864. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  56865. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  56866. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  56867. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  56868. // ----
  56869. tmp1 = SIMD.Float32x4.mul(row2, row3);
  56870. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  56871. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  56872. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  56873. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  56874. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  56875. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  56876. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  56877. // ----
  56878. tmp1 = SIMD.Float32x4.mul(row1, row2);
  56879. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  56880. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  56881. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  56882. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  56883. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  56884. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  56885. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  56886. // ----
  56887. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  56888. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  56889. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  56890. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  56891. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  56892. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  56893. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  56894. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  56895. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  56896. // ----
  56897. tmp1 = SIMD.Float32x4.mul(row0, row1);
  56898. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  56899. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  56900. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  56901. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  56902. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  56903. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  56904. // ----
  56905. tmp1 = SIMD.Float32x4.mul(row0, row3);
  56906. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  56907. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  56908. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  56909. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  56910. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  56911. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  56912. // ----
  56913. tmp1 = SIMD.Float32x4.mul(row0, row2);
  56914. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  56915. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  56916. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  56917. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  56918. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  56919. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  56920. // Compute determinant
  56921. var det = SIMD.Float32x4.mul(row0, minor0);
  56922. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  56923. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  56924. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  56925. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  56926. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  56927. // These shuffles aren't necessary if the faulty transposition is done
  56928. // up at the top of this function.
  56929. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  56930. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  56931. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  56932. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  56933. // Compute final values by multiplying with 1/det
  56934. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  56935. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  56936. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  56937. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  56938. return this;
  56939. };
  56940. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  56941. var out = result.m;
  56942. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  56943. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  56944. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  56945. // cc.kmVec3Subtract(f, pCenter, pEye);
  56946. var f = SIMD.Float32x4.sub(center, eye);
  56947. // cc.kmVec3Normalize(f, f);
  56948. var tmp = SIMD.Float32x4.mul(f, f);
  56949. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  56950. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  56951. // cc.kmVec3Assign(up, pUp);
  56952. // cc.kmVec3Normalize(up, up);
  56953. tmp = SIMD.Float32x4.mul(up, up);
  56954. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  56955. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  56956. // cc.kmVec3Cross(s, f, up);
  56957. 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)));
  56958. // cc.kmVec3Normalize(s, s);
  56959. tmp = SIMD.Float32x4.mul(s, s);
  56960. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  56961. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  56962. // cc.kmVec3Cross(u, s, f);
  56963. 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)));
  56964. // cc.kmVec3Normalize(s, s);
  56965. tmp = SIMD.Float32x4.mul(s, s);
  56966. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  56967. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  56968. var zero = SIMD.Float32x4.splat(0.0);
  56969. s = SIMD.Float32x4.neg(s);
  56970. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  56971. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  56972. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  56973. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  56974. 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);
  56975. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  56976. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  56977. 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)))));
  56978. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  56979. 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)))));
  56980. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  56981. 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)))));
  56982. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  56983. 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)))));
  56984. };
  56985. return SIMDMatrix;
  56986. }());
  56987. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  56988. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  56989. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  56990. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  56991. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  56992. var SIMDHelper = (function () {
  56993. function SIMDHelper() {
  56994. }
  56995. Object.defineProperty(SIMDHelper, "IsEnabled", {
  56996. get: function () {
  56997. return SIMDHelper._isEnabled;
  56998. },
  56999. enumerable: true,
  57000. configurable: true
  57001. });
  57002. SIMDHelper.DisableSIMD = function () {
  57003. // Replace functions
  57004. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  57005. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  57006. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  57007. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  57008. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  57009. SIMDHelper._isEnabled = false;
  57010. };
  57011. SIMDHelper.EnableSIMD = function () {
  57012. if (self.SIMD === undefined) {
  57013. return;
  57014. }
  57015. // check if polyfills needed
  57016. if (!self.Math.fround) {
  57017. self.Math.fround = (function (array) { return function (x) {
  57018. return array[0] = x, array[0];
  57019. }; })(new Float32Array(1));
  57020. }
  57021. if (!self.Math.imul) {
  57022. self.Math.imul = function (a, b) {
  57023. var ah = (a >>> 16) & 0xffff;
  57024. var al = a & 0xffff;
  57025. var bh = (b >>> 16) & 0xffff;
  57026. var bl = b & 0xffff;
  57027. // the shift by 0 fixes the sign on the high part
  57028. // the final |0 converts the unsigned value into a signed value
  57029. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  57030. };
  57031. }
  57032. // Replace functions
  57033. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  57034. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  57035. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  57036. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  57037. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  57038. SIMDHelper._isEnabled = true;
  57039. };
  57040. return SIMDHelper;
  57041. }());
  57042. SIMDHelper._isEnabled = false;
  57043. BABYLON.SIMDHelper = SIMDHelper;
  57044. })(BABYLON || (BABYLON = {}));
  57045. //# sourceMappingURL=babylon.math.SIMD.js.map
  57046. var BABYLON;
  57047. (function (BABYLON) {
  57048. var VRDistortionCorrectionPostProcess = (function (_super) {
  57049. __extends(VRDistortionCorrectionPostProcess, _super);
  57050. //ANY
  57051. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  57052. var _this = _super.call(this, name, "vrDistortionCorrection", [
  57053. 'LensCenter',
  57054. 'Scale',
  57055. 'ScaleIn',
  57056. 'HmdWarpParam'
  57057. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  57058. _this._isRightEye = isRightEye;
  57059. _this._distortionFactors = vrMetrics.distortionK;
  57060. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  57061. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  57062. _this.onSizeChangedObservable.add(function () {
  57063. _this.aspectRatio = _this.width * .5 / _this.height;
  57064. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  57065. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  57066. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  57067. });
  57068. _this.onApplyObservable.add(function (effect) {
  57069. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  57070. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  57071. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  57072. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  57073. });
  57074. return _this;
  57075. }
  57076. return VRDistortionCorrectionPostProcess;
  57077. }(BABYLON.PostProcess));
  57078. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  57079. })(BABYLON || (BABYLON = {}));
  57080. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  57081. var BABYLON;
  57082. (function (BABYLON) {
  57083. var FreeCameraDeviceOrientationInput = (function () {
  57084. function FreeCameraDeviceOrientationInput() {
  57085. var _this = this;
  57086. this._screenOrientationAngle = 0;
  57087. this._screenQuaternion = new BABYLON.Quaternion();
  57088. this._alpha = 0;
  57089. this._beta = 0;
  57090. this._gamma = 0;
  57091. this._orientationChanged = function () {
  57092. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  57093. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  57094. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  57095. };
  57096. this._deviceOrientation = function (evt) {
  57097. _this._alpha = evt.alpha;
  57098. _this._beta = evt.beta;
  57099. _this._gamma = evt.gamma;
  57100. };
  57101. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  57102. this._orientationChanged();
  57103. }
  57104. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  57105. get: function () {
  57106. return this._camera;
  57107. },
  57108. set: function (camera) {
  57109. this._camera = camera;
  57110. if (!this._camera.rotationQuaternion)
  57111. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  57112. },
  57113. enumerable: true,
  57114. configurable: true
  57115. });
  57116. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  57117. window.addEventListener("orientationchange", this._orientationChanged);
  57118. window.addEventListener("deviceorientation", this._deviceOrientation);
  57119. //In certain cases, the attach control is called AFTER orientation was changed,
  57120. //So this is needed.
  57121. this._orientationChanged();
  57122. };
  57123. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  57124. window.removeEventListener("orientationchange", this._orientationChanged);
  57125. window.removeEventListener("deviceorientation", this._deviceOrientation);
  57126. };
  57127. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  57128. //if no device orientation provided, don't update the rotation.
  57129. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  57130. if (!this._alpha)
  57131. return;
  57132. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  57133. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  57134. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  57135. //Mirror on XY Plane
  57136. this._camera.rotationQuaternion.z *= -1;
  57137. this._camera.rotationQuaternion.w *= -1;
  57138. };
  57139. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  57140. return "FreeCameraDeviceOrientationInput";
  57141. };
  57142. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  57143. return "deviceOrientation";
  57144. };
  57145. return FreeCameraDeviceOrientationInput;
  57146. }());
  57147. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  57148. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  57149. })(BABYLON || (BABYLON = {}));
  57150. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  57151. var BABYLON;
  57152. (function (BABYLON) {
  57153. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  57154. function ArcRotateCameraVRDeviceOrientationInput() {
  57155. this.alphaCorrection = 1;
  57156. this.betaCorrection = 1;
  57157. this.gammaCorrection = 1;
  57158. this._alpha = 0;
  57159. this._beta = 0;
  57160. this._gamma = 0;
  57161. this._dirty = false;
  57162. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  57163. }
  57164. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  57165. this.camera.attachControl(element, noPreventDefault);
  57166. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  57167. };
  57168. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  57169. var camera = this.camera;
  57170. this._alpha = +evt.alpha | 0;
  57171. this._beta = +evt.beta | 0;
  57172. this._gamma = +evt.gamma | 0;
  57173. this._dirty = true;
  57174. };
  57175. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  57176. if (this._dirty) {
  57177. this._dirty = false;
  57178. if (this._gamma < 0) {
  57179. this._gamma = 180 + this._gamma;
  57180. }
  57181. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  57182. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  57183. }
  57184. };
  57185. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  57186. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  57187. };
  57188. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  57189. return "ArcRotateCameraVRDeviceOrientationInput";
  57190. };
  57191. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  57192. return "VRDeviceOrientation";
  57193. };
  57194. return ArcRotateCameraVRDeviceOrientationInput;
  57195. }());
  57196. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  57197. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  57198. })(BABYLON || (BABYLON = {}));
  57199. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  57200. var BABYLON;
  57201. (function (BABYLON) {
  57202. var VRCameraMetrics = (function () {
  57203. function VRCameraMetrics() {
  57204. this.compensateDistortion = true;
  57205. }
  57206. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  57207. get: function () {
  57208. return this.hResolution / (2 * this.vResolution);
  57209. },
  57210. enumerable: true,
  57211. configurable: true
  57212. });
  57213. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  57214. get: function () {
  57215. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  57216. },
  57217. enumerable: true,
  57218. configurable: true
  57219. });
  57220. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  57221. get: function () {
  57222. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  57223. var h = (4 * meters) / this.hScreenSize;
  57224. return BABYLON.Matrix.Translation(h, 0, 0);
  57225. },
  57226. enumerable: true,
  57227. configurable: true
  57228. });
  57229. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  57230. get: function () {
  57231. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  57232. var h = (4 * meters) / this.hScreenSize;
  57233. return BABYLON.Matrix.Translation(-h, 0, 0);
  57234. },
  57235. enumerable: true,
  57236. configurable: true
  57237. });
  57238. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  57239. get: function () {
  57240. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  57241. },
  57242. enumerable: true,
  57243. configurable: true
  57244. });
  57245. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  57246. get: function () {
  57247. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  57248. },
  57249. enumerable: true,
  57250. configurable: true
  57251. });
  57252. VRCameraMetrics.GetDefault = function () {
  57253. var result = new VRCameraMetrics();
  57254. result.hResolution = 1280;
  57255. result.vResolution = 800;
  57256. result.hScreenSize = 0.149759993;
  57257. result.vScreenSize = 0.0935999975;
  57258. result.vScreenCenter = 0.0467999987;
  57259. result.eyeToScreenDistance = 0.0410000011;
  57260. result.lensSeparationDistance = 0.0635000020;
  57261. result.interpupillaryDistance = 0.0640000030;
  57262. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  57263. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  57264. result.postProcessScaleFactor = 1.714605507808412;
  57265. result.lensCenterOffset = 0.151976421;
  57266. return result;
  57267. };
  57268. return VRCameraMetrics;
  57269. }());
  57270. BABYLON.VRCameraMetrics = VRCameraMetrics;
  57271. })(BABYLON || (BABYLON = {}));
  57272. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  57273. var BABYLON;
  57274. (function (BABYLON) {
  57275. var WebVRFreeCamera = (function (_super) {
  57276. __extends(WebVRFreeCamera, _super);
  57277. function WebVRFreeCamera(name, position, scene, webVROptions) {
  57278. if (webVROptions === void 0) { webVROptions = {}; }
  57279. var _this = _super.call(this, name, position, scene) || this;
  57280. _this.webVROptions = webVROptions;
  57281. _this._vrDevice = null;
  57282. _this.rawPose = null;
  57283. _this._vrEnabled = false;
  57284. _this._specsVersion = 1.1;
  57285. _this._attached = false;
  57286. _this._positionOffset = BABYLON.Vector3.Zero();
  57287. _this._descendants = [];
  57288. _this.devicePosition = BABYLON.Vector3.Zero();
  57289. _this.deviceScaleFactor = 1;
  57290. _this.controllers = [];
  57291. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  57292. //legacy support - the compensation boolean was removed.
  57293. if (arguments.length === 5) {
  57294. _this.webVROptions = arguments[4];
  57295. }
  57296. // default webVR options
  57297. if (_this.webVROptions.trackPosition == undefined) {
  57298. _this.webVROptions.trackPosition = true;
  57299. }
  57300. if (_this.webVROptions.controllerMeshes == undefined) {
  57301. _this.webVROptions.controllerMeshes = true;
  57302. }
  57303. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  57304. _this.webVROptions.defaultLightningOnControllers = true;
  57305. }
  57306. _this.rotationQuaternion = new BABYLON.Quaternion();
  57307. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  57308. if (_this.webVROptions && _this.webVROptions.positionScale) {
  57309. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  57310. }
  57311. //enable VR
  57312. _this.getEngine().initWebVR();
  57313. if (!_this.getEngine().vrDisplaysPromise) {
  57314. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  57315. }
  57316. else {
  57317. //check specs version
  57318. if (!window.VRFrameData) {
  57319. _this._specsVersion = 1.0;
  57320. _this._frameData = {};
  57321. }
  57322. else {
  57323. _this._frameData = new VRFrameData();
  57324. }
  57325. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  57326. if (devices.length > 0) {
  57327. _this._vrEnabled = true;
  57328. if (_this.webVROptions.displayName) {
  57329. var found = devices.some(function (device) {
  57330. if (device.displayName === _this.webVROptions.displayName) {
  57331. _this._vrDevice = device;
  57332. return true;
  57333. }
  57334. else {
  57335. return false;
  57336. }
  57337. });
  57338. if (!found) {
  57339. _this._vrDevice = devices[0];
  57340. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  57341. }
  57342. }
  57343. else {
  57344. //choose the first one
  57345. _this._vrDevice = devices[0];
  57346. }
  57347. //reset the rig parameters.
  57348. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  57349. if (_this._attached) {
  57350. _this.getEngine().enableVR(_this._vrDevice);
  57351. }
  57352. }
  57353. else {
  57354. BABYLON.Tools.Error("No WebVR devices found!");
  57355. }
  57356. });
  57357. }
  57358. // try to attach the controllers, if found.
  57359. _this.initControllers();
  57360. /**
  57361. * The idea behind the following lines:
  57362. * objects that have the camera as parent should actually have the rig cameras as a parent.
  57363. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  57364. * the second will not show it correctly.
  57365. *
  57366. * To solve this - each object that has the camera as parent will be added to a protected array.
  57367. * When the rig camera renders, it will take this array and set all of those to be its children.
  57368. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  57369. * Amazing!
  57370. */
  57371. scene.onBeforeCameraRenderObservable.add(function (camera) {
  57372. if (camera.parent === _this && _this.rigParenting) {
  57373. _this._descendants = _this.getDescendants(true, function (n) {
  57374. // don't take the cameras or the controllers!
  57375. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  57376. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  57377. return !isController && !isRigCamera;
  57378. });
  57379. _this._descendants.forEach(function (node) {
  57380. node.parent = camera;
  57381. });
  57382. }
  57383. });
  57384. scene.onAfterCameraRenderObservable.add(function (camera) {
  57385. if (camera.parent === _this && _this.rigParenting) {
  57386. _this._descendants.forEach(function (node) {
  57387. node.parent = _this;
  57388. });
  57389. }
  57390. });
  57391. return _this;
  57392. }
  57393. WebVRFreeCamera.prototype._checkInputs = function () {
  57394. if (this._vrEnabled) {
  57395. if (this._specsVersion === 1.1) {
  57396. this._vrDevice.getFrameData(this._frameData);
  57397. }
  57398. else {
  57399. //backwards comp
  57400. var pose = this._vrDevice.getPose();
  57401. this._frameData.pose = pose;
  57402. // calculate view and projection matrix
  57403. }
  57404. this.updateFromDevice(this._frameData.pose);
  57405. }
  57406. _super.prototype._checkInputs.call(this);
  57407. };
  57408. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  57409. if (poseData && poseData.orientation) {
  57410. this.rawPose = poseData;
  57411. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  57412. if (this.getScene().useRightHandedSystem) {
  57413. this.deviceRotationQuaternion.z *= -1;
  57414. this.deviceRotationQuaternion.w *= -1;
  57415. }
  57416. if (this.webVROptions.trackPosition && this.rawPose.position) {
  57417. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  57418. if (this.getScene().useRightHandedSystem) {
  57419. this.devicePosition.z *= -1;
  57420. }
  57421. }
  57422. }
  57423. };
  57424. /**
  57425. * WebVR's attach control will start broadcasting frames to the device.
  57426. * Note that in certain browsers (chrome for example) this function must be called
  57427. * within a user-interaction callback. Example:
  57428. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  57429. *
  57430. * @param {HTMLElement} element
  57431. * @param {boolean} [noPreventDefault]
  57432. *
  57433. * @memberOf WebVRFreeCamera
  57434. */
  57435. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  57436. _super.prototype.attachControl.call(this, element, noPreventDefault);
  57437. this._attached = true;
  57438. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  57439. if (this._vrEnabled) {
  57440. this.getEngine().enableVR(this._vrDevice);
  57441. }
  57442. };
  57443. WebVRFreeCamera.prototype.detachControl = function (element) {
  57444. _super.prototype.detachControl.call(this, element);
  57445. this._vrEnabled = false;
  57446. this._attached = false;
  57447. this.getEngine().disableVR();
  57448. };
  57449. WebVRFreeCamera.prototype.getClassName = function () {
  57450. return "WebVRFreeCamera";
  57451. };
  57452. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  57453. //uses the vrDisplay's "resetPose()".
  57454. //pitch and roll won't be affected.
  57455. this._vrDevice.resetPose();
  57456. };
  57457. WebVRFreeCamera.prototype._updateRigCameras = function () {
  57458. var camLeft = this._rigCameras[0];
  57459. var camRight = this._rigCameras[1];
  57460. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  57461. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  57462. camLeft.position.copyFrom(this.devicePosition);
  57463. camRight.position.copyFrom(this.devicePosition);
  57464. };
  57465. /**
  57466. * This function is called by the two RIG cameras.
  57467. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  57468. */
  57469. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  57470. var _this = this;
  57471. //WebVR 1.0
  57472. if (this._cameraRigParams["specs"] === 1.0) {
  57473. this._updateCameraRotationMatrix();
  57474. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  57475. // Computing target and final matrix
  57476. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  57477. if (this.getScene().useRightHandedSystem) {
  57478. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  57479. }
  57480. else {
  57481. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  57482. }
  57483. //now move the eye in the right direction
  57484. var eyeParams = this._cameraRigParams["eyeParameters"];
  57485. var offset = eyeParams.offset;
  57486. // it will actually always be 0, but just in case
  57487. if (this.getScene().useRightHandedSystem) {
  57488. offset[2] *= -1;
  57489. }
  57490. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  57491. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  57492. }
  57493. else {
  57494. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  57495. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  57496. if (!this.getScene().useRightHandedSystem) {
  57497. [2, 6, 8, 9, 14].forEach(function (num) {
  57498. _this._webvrViewMatrix.m[num] *= -1;
  57499. });
  57500. }
  57501. // update the camera rotation matrix
  57502. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  57503. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  57504. // Computing target and final matrix
  57505. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  57506. }
  57507. var parentCamera = this._cameraRigParams["parentCamera"];
  57508. // should the view matrix be updated with scale and position offset?
  57509. if (parentCamera.deviceScaleFactor !== 1) {
  57510. this._webvrViewMatrix.invert();
  57511. // scale the position, if set
  57512. if (parentCamera.deviceScaleFactor) {
  57513. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  57514. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  57515. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  57516. }
  57517. this._webvrViewMatrix.invert();
  57518. }
  57519. return this._webvrViewMatrix;
  57520. };
  57521. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  57522. var _this = this;
  57523. if (this._cameraRigParams["specs"] === 1.0) {
  57524. var eyeParams = this._cameraRigParams["eyeParameters"];
  57525. // deprecated!!
  57526. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  57527. }
  57528. else {
  57529. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  57530. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  57531. //babylon compatible matrix
  57532. if (!this.getScene().useRightHandedSystem) {
  57533. [8, 9, 10, 11].forEach(function (num) {
  57534. _this._projectionMatrix.m[num] *= -1;
  57535. });
  57536. }
  57537. }
  57538. return this._projectionMatrix;
  57539. };
  57540. WebVRFreeCamera.prototype.initControllers = function () {
  57541. var _this = this;
  57542. this.controllers = [];
  57543. new BABYLON.Gamepads(function (gp) {
  57544. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  57545. var webVrController = gp;
  57546. if (_this.webVROptions.controllerMeshes) {
  57547. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  57548. if (_this.webVROptions.defaultLightningOnControllers) {
  57549. if (!_this._lightOnControllers) {
  57550. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  57551. }
  57552. loadedMesh.getChildren().forEach(function (mesh) {
  57553. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  57554. });
  57555. }
  57556. });
  57557. }
  57558. webVrController.attachToPoseControlledCamera(_this);
  57559. // since this is async - sanity check. Is the controller already stored?
  57560. if (_this.controllers.indexOf(webVrController) === -1) {
  57561. //add to the controllers array
  57562. _this.controllers.push(webVrController);
  57563. //did we find enough controllers? Great! let the developer know.
  57564. if (_this.onControllersAttached && _this.controllers.length === 2) {
  57565. _this.onControllersAttached(_this.controllers);
  57566. }
  57567. }
  57568. }
  57569. });
  57570. };
  57571. return WebVRFreeCamera;
  57572. }(BABYLON.FreeCamera));
  57573. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  57574. })(BABYLON || (BABYLON = {}));
  57575. //# sourceMappingURL=babylon.webVRCamera.js.map
  57576. /// <reference path="babylon.freeCamera.ts" />
  57577. var BABYLON;
  57578. (function (BABYLON) {
  57579. // We're mainly based on the logic defined into the FreeCamera code
  57580. var DeviceOrientationCamera = (function (_super) {
  57581. __extends(DeviceOrientationCamera, _super);
  57582. function DeviceOrientationCamera(name, position, scene) {
  57583. var _this = _super.call(this, name, position, scene) || this;
  57584. _this._quaternionCache = new BABYLON.Quaternion();
  57585. _this.inputs.addDeviceOrientation();
  57586. return _this;
  57587. }
  57588. DeviceOrientationCamera.prototype.getClassName = function () {
  57589. return "DeviceOrientationCamera";
  57590. };
  57591. DeviceOrientationCamera.prototype._checkInputs = function () {
  57592. _super.prototype._checkInputs.call(this);
  57593. this._quaternionCache.copyFrom(this.rotationQuaternion);
  57594. if (this._initialQuaternion) {
  57595. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  57596. }
  57597. };
  57598. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  57599. var _this = this;
  57600. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  57601. //can only work if this camera has a rotation quaternion already.
  57602. if (!this.rotationQuaternion)
  57603. return;
  57604. if (!this._initialQuaternion) {
  57605. this._initialQuaternion = new BABYLON.Quaternion();
  57606. }
  57607. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  57608. ['x', 'y', 'z'].forEach(function (axisName) {
  57609. if (!axis[axisName]) {
  57610. _this._initialQuaternion[axisName] = 0;
  57611. }
  57612. else {
  57613. _this._initialQuaternion[axisName] *= -1;
  57614. }
  57615. });
  57616. this._initialQuaternion.normalize();
  57617. //force rotation update
  57618. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  57619. };
  57620. return DeviceOrientationCamera;
  57621. }(BABYLON.FreeCamera));
  57622. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  57623. })(BABYLON || (BABYLON = {}));
  57624. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  57625. var BABYLON;
  57626. (function (BABYLON) {
  57627. var VRDeviceOrientationFreeCamera = (function (_super) {
  57628. __extends(VRDeviceOrientationFreeCamera, _super);
  57629. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  57630. if (compensateDistortion === void 0) { compensateDistortion = true; }
  57631. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  57632. var _this = _super.call(this, name, position, scene) || this;
  57633. vrCameraMetrics.compensateDistortion = compensateDistortion;
  57634. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  57635. return _this;
  57636. }
  57637. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  57638. return "VRDeviceOrientationFreeCamera";
  57639. };
  57640. return VRDeviceOrientationFreeCamera;
  57641. }(BABYLON.DeviceOrientationCamera));
  57642. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  57643. var VRDeviceOrientationGamepadCamera = (function (_super) {
  57644. __extends(VRDeviceOrientationGamepadCamera, _super);
  57645. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  57646. if (compensateDistortion === void 0) { compensateDistortion = true; }
  57647. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  57648. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  57649. _this.inputs.addGamepad();
  57650. return _this;
  57651. }
  57652. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  57653. return "VRDeviceOrientationGamepadCamera";
  57654. };
  57655. return VRDeviceOrientationGamepadCamera;
  57656. }(VRDeviceOrientationFreeCamera));
  57657. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  57658. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  57659. __extends(VRDeviceOrientationArcRotateCamera, _super);
  57660. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  57661. if (compensateDistortion === void 0) { compensateDistortion = true; }
  57662. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  57663. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  57664. vrCameraMetrics.compensateDistortion = compensateDistortion;
  57665. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  57666. _this.inputs.addVRDeviceOrientation();
  57667. return _this;
  57668. }
  57669. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  57670. return "VRDeviceOrientationArcRotateCamera";
  57671. };
  57672. return VRDeviceOrientationArcRotateCamera;
  57673. }(BABYLON.ArcRotateCamera));
  57674. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  57675. })(BABYLON || (BABYLON = {}));
  57676. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  57677. /// <reference path="babylon.freeCamera.ts" />
  57678. /// <reference path="babylon.arcRotateCamera.ts" />
  57679. /// <reference path="babylon.gamepadCamera.ts" />
  57680. /// <reference path="babylon.universalCamera.ts" />
  57681. var BABYLON;
  57682. (function (BABYLON) {
  57683. var AnaglyphFreeCamera = (function (_super) {
  57684. __extends(AnaglyphFreeCamera, _super);
  57685. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  57686. var _this = _super.call(this, name, position, scene) || this;
  57687. _this.interaxialDistance = interaxialDistance;
  57688. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  57689. return _this;
  57690. }
  57691. AnaglyphFreeCamera.prototype.getClassName = function () {
  57692. return "AnaglyphFreeCamera";
  57693. };
  57694. return AnaglyphFreeCamera;
  57695. }(BABYLON.FreeCamera));
  57696. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  57697. var AnaglyphArcRotateCamera = (function (_super) {
  57698. __extends(AnaglyphArcRotateCamera, _super);
  57699. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  57700. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  57701. _this.interaxialDistance = interaxialDistance;
  57702. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  57703. return _this;
  57704. }
  57705. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  57706. return "AnaglyphArcRotateCamera";
  57707. };
  57708. return AnaglyphArcRotateCamera;
  57709. }(BABYLON.ArcRotateCamera));
  57710. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  57711. var AnaglyphGamepadCamera = (function (_super) {
  57712. __extends(AnaglyphGamepadCamera, _super);
  57713. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  57714. var _this = _super.call(this, name, position, scene) || this;
  57715. _this.interaxialDistance = interaxialDistance;
  57716. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  57717. return _this;
  57718. }
  57719. AnaglyphGamepadCamera.prototype.getClassName = function () {
  57720. return "AnaglyphGamepadCamera";
  57721. };
  57722. return AnaglyphGamepadCamera;
  57723. }(BABYLON.GamepadCamera));
  57724. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  57725. var AnaglyphUniversalCamera = (function (_super) {
  57726. __extends(AnaglyphUniversalCamera, _super);
  57727. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  57728. var _this = _super.call(this, name, position, scene) || this;
  57729. _this.interaxialDistance = interaxialDistance;
  57730. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  57731. return _this;
  57732. }
  57733. AnaglyphUniversalCamera.prototype.getClassName = function () {
  57734. return "AnaglyphUniversalCamera";
  57735. };
  57736. return AnaglyphUniversalCamera;
  57737. }(BABYLON.UniversalCamera));
  57738. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  57739. var StereoscopicFreeCamera = (function (_super) {
  57740. __extends(StereoscopicFreeCamera, _super);
  57741. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  57742. var _this = _super.call(this, name, position, scene) || this;
  57743. _this.interaxialDistance = interaxialDistance;
  57744. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  57745. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  57746. return _this;
  57747. }
  57748. StereoscopicFreeCamera.prototype.getClassName = function () {
  57749. return "StereoscopicFreeCamera";
  57750. };
  57751. return StereoscopicFreeCamera;
  57752. }(BABYLON.FreeCamera));
  57753. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  57754. var StereoscopicArcRotateCamera = (function (_super) {
  57755. __extends(StereoscopicArcRotateCamera, _super);
  57756. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  57757. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  57758. _this.interaxialDistance = interaxialDistance;
  57759. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  57760. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  57761. return _this;
  57762. }
  57763. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  57764. return "StereoscopicArcRotateCamera";
  57765. };
  57766. return StereoscopicArcRotateCamera;
  57767. }(BABYLON.ArcRotateCamera));
  57768. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  57769. var StereoscopicGamepadCamera = (function (_super) {
  57770. __extends(StereoscopicGamepadCamera, _super);
  57771. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  57772. var _this = _super.call(this, name, position, scene) || this;
  57773. _this.interaxialDistance = interaxialDistance;
  57774. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  57775. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  57776. return _this;
  57777. }
  57778. StereoscopicGamepadCamera.prototype.getClassName = function () {
  57779. return "StereoscopicGamepadCamera";
  57780. };
  57781. return StereoscopicGamepadCamera;
  57782. }(BABYLON.GamepadCamera));
  57783. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  57784. var StereoscopicUniversalCamera = (function (_super) {
  57785. __extends(StereoscopicUniversalCamera, _super);
  57786. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  57787. var _this = _super.call(this, name, position, scene) || this;
  57788. _this.interaxialDistance = interaxialDistance;
  57789. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  57790. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  57791. return _this;
  57792. }
  57793. StereoscopicUniversalCamera.prototype.getClassName = function () {
  57794. return "StereoscopicUniversalCamera";
  57795. };
  57796. return StereoscopicUniversalCamera;
  57797. }(BABYLON.UniversalCamera));
  57798. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  57799. })(BABYLON || (BABYLON = {}));
  57800. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  57801. // Mainly based on these 2 articles :
  57802. // 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
  57803. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  57804. var BABYLON;
  57805. (function (BABYLON) {
  57806. var JoystickAxis;
  57807. (function (JoystickAxis) {
  57808. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  57809. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  57810. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  57811. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  57812. var VirtualJoystick = (function () {
  57813. function VirtualJoystick(leftJoystick) {
  57814. var _this = this;
  57815. if (leftJoystick) {
  57816. this._leftJoystick = true;
  57817. }
  57818. else {
  57819. this._leftJoystick = false;
  57820. }
  57821. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  57822. VirtualJoystick._globalJoystickIndex++;
  57823. // By default left & right arrow keys are moving the X
  57824. // and up & down keys are moving the Y
  57825. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  57826. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  57827. this.reverseLeftRight = false;
  57828. this.reverseUpDown = false;
  57829. // collections of pointers
  57830. this._touches = new BABYLON.StringDictionary();
  57831. this.deltaPosition = BABYLON.Vector3.Zero();
  57832. this._joystickSensibility = 25;
  57833. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  57834. this._rotationSpeed = 25;
  57835. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  57836. this._rotateOnAxisRelativeToMesh = false;
  57837. this._onResize = function (evt) {
  57838. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  57839. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  57840. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  57841. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  57842. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  57843. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  57844. };
  57845. // injecting a canvas element on top of the canvas 3D game
  57846. if (!VirtualJoystick.vjCanvas) {
  57847. window.addEventListener("resize", this._onResize, false);
  57848. VirtualJoystick.vjCanvas = document.createElement("canvas");
  57849. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  57850. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  57851. VirtualJoystick.vjCanvas.width = window.innerWidth;
  57852. VirtualJoystick.vjCanvas.height = window.innerHeight;
  57853. VirtualJoystick.vjCanvas.style.width = "100%";
  57854. VirtualJoystick.vjCanvas.style.height = "100%";
  57855. VirtualJoystick.vjCanvas.style.position = "absolute";
  57856. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  57857. VirtualJoystick.vjCanvas.style.top = "0px";
  57858. VirtualJoystick.vjCanvas.style.left = "0px";
  57859. VirtualJoystick.vjCanvas.style.zIndex = "5";
  57860. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  57861. // Support for jQuery PEP polyfill
  57862. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  57863. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  57864. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  57865. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  57866. document.body.appendChild(VirtualJoystick.vjCanvas);
  57867. }
  57868. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  57869. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  57870. this.pressed = false;
  57871. // default joystick color
  57872. this._joystickColor = "cyan";
  57873. this._joystickPointerID = -1;
  57874. // current joystick position
  57875. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  57876. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  57877. // origin joystick position
  57878. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  57879. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  57880. this._onPointerDownHandlerRef = function (evt) {
  57881. _this._onPointerDown(evt);
  57882. };
  57883. this._onPointerMoveHandlerRef = function (evt) {
  57884. _this._onPointerMove(evt);
  57885. };
  57886. this._onPointerOutHandlerRef = function (evt) {
  57887. _this._onPointerUp(evt);
  57888. };
  57889. this._onPointerUpHandlerRef = function (evt) {
  57890. _this._onPointerUp(evt);
  57891. };
  57892. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  57893. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  57894. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  57895. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  57896. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  57897. evt.preventDefault(); // Disables system menu
  57898. }, false);
  57899. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  57900. }
  57901. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  57902. this._joystickSensibility = newJoystickSensibility;
  57903. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  57904. };
  57905. VirtualJoystick.prototype._onPointerDown = function (e) {
  57906. var positionOnScreenCondition;
  57907. e.preventDefault();
  57908. if (this._leftJoystick === true) {
  57909. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  57910. }
  57911. else {
  57912. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  57913. }
  57914. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  57915. // First contact will be dedicated to the virtual joystick
  57916. this._joystickPointerID = e.pointerId;
  57917. this._joystickPointerStartPos.x = e.clientX;
  57918. this._joystickPointerStartPos.y = e.clientY;
  57919. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  57920. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  57921. this._deltaJoystickVector.x = 0;
  57922. this._deltaJoystickVector.y = 0;
  57923. this.pressed = true;
  57924. this._touches.add(e.pointerId.toString(), e);
  57925. }
  57926. else {
  57927. // You can only trigger the action buttons with a joystick declared
  57928. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  57929. this._action();
  57930. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  57931. }
  57932. }
  57933. };
  57934. VirtualJoystick.prototype._onPointerMove = function (e) {
  57935. // If the current pointer is the one associated to the joystick (first touch contact)
  57936. if (this._joystickPointerID == e.pointerId) {
  57937. this._joystickPointerPos.x = e.clientX;
  57938. this._joystickPointerPos.y = e.clientY;
  57939. this._deltaJoystickVector = this._joystickPointerPos.clone();
  57940. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  57941. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  57942. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  57943. switch (this._axisTargetedByLeftAndRight) {
  57944. case JoystickAxis.X:
  57945. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  57946. break;
  57947. case JoystickAxis.Y:
  57948. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  57949. break;
  57950. case JoystickAxis.Z:
  57951. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  57952. break;
  57953. }
  57954. var directionUpDown = this.reverseUpDown ? 1 : -1;
  57955. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  57956. switch (this._axisTargetedByUpAndDown) {
  57957. case JoystickAxis.X:
  57958. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  57959. break;
  57960. case JoystickAxis.Y:
  57961. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  57962. break;
  57963. case JoystickAxis.Z:
  57964. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  57965. break;
  57966. }
  57967. }
  57968. else {
  57969. var data = this._touches.get(e.pointerId.toString());
  57970. if (data) {
  57971. data.x = e.clientX;
  57972. data.y = e.clientY;
  57973. }
  57974. }
  57975. };
  57976. VirtualJoystick.prototype._onPointerUp = function (e) {
  57977. if (this._joystickPointerID == e.pointerId) {
  57978. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  57979. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  57980. this._joystickPointerID = -1;
  57981. this.pressed = false;
  57982. }
  57983. else {
  57984. var touch = this._touches.get(e.pointerId.toString());
  57985. if (touch) {
  57986. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  57987. }
  57988. }
  57989. this._deltaJoystickVector.x = 0;
  57990. this._deltaJoystickVector.y = 0;
  57991. this._touches.remove(e.pointerId.toString());
  57992. };
  57993. /**
  57994. * Change the color of the virtual joystick
  57995. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  57996. */
  57997. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  57998. this._joystickColor = newColor;
  57999. };
  58000. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  58001. this._action = action;
  58002. };
  58003. // Define which axis you'd like to control for left & right
  58004. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  58005. switch (axis) {
  58006. case JoystickAxis.X:
  58007. case JoystickAxis.Y:
  58008. case JoystickAxis.Z:
  58009. this._axisTargetedByLeftAndRight = axis;
  58010. break;
  58011. default:
  58012. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  58013. break;
  58014. }
  58015. };
  58016. // Define which axis you'd like to control for up & down
  58017. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  58018. switch (axis) {
  58019. case JoystickAxis.X:
  58020. case JoystickAxis.Y:
  58021. case JoystickAxis.Z:
  58022. this._axisTargetedByUpAndDown = axis;
  58023. break;
  58024. default:
  58025. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  58026. break;
  58027. }
  58028. };
  58029. VirtualJoystick.prototype._clearCanvas = function () {
  58030. if (this._leftJoystick) {
  58031. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  58032. }
  58033. else {
  58034. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  58035. }
  58036. };
  58037. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  58038. var _this = this;
  58039. if (this.pressed) {
  58040. this._touches.forEach(function (key, touch) {
  58041. if (touch.pointerId === _this._joystickPointerID) {
  58042. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  58043. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  58044. VirtualJoystick.vjCanvasContext.beginPath();
  58045. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  58046. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  58047. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  58048. VirtualJoystick.vjCanvasContext.stroke();
  58049. VirtualJoystick.vjCanvasContext.closePath();
  58050. VirtualJoystick.vjCanvasContext.beginPath();
  58051. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  58052. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  58053. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  58054. VirtualJoystick.vjCanvasContext.stroke();
  58055. VirtualJoystick.vjCanvasContext.closePath();
  58056. VirtualJoystick.vjCanvasContext.beginPath();
  58057. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  58058. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  58059. VirtualJoystick.vjCanvasContext.stroke();
  58060. VirtualJoystick.vjCanvasContext.closePath();
  58061. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  58062. }
  58063. else {
  58064. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  58065. VirtualJoystick.vjCanvasContext.beginPath();
  58066. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  58067. VirtualJoystick.vjCanvasContext.beginPath();
  58068. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  58069. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  58070. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  58071. VirtualJoystick.vjCanvasContext.stroke();
  58072. VirtualJoystick.vjCanvasContext.closePath();
  58073. touch.prevX = touch.x;
  58074. touch.prevY = touch.y;
  58075. }
  58076. ;
  58077. });
  58078. }
  58079. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  58080. };
  58081. VirtualJoystick.prototype.releaseCanvas = function () {
  58082. if (VirtualJoystick.vjCanvas) {
  58083. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  58084. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  58085. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  58086. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  58087. window.removeEventListener("resize", this._onResize);
  58088. document.body.removeChild(VirtualJoystick.vjCanvas);
  58089. VirtualJoystick.vjCanvas = null;
  58090. }
  58091. };
  58092. return VirtualJoystick;
  58093. }());
  58094. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  58095. VirtualJoystick._globalJoystickIndex = 0;
  58096. BABYLON.VirtualJoystick = VirtualJoystick;
  58097. })(BABYLON || (BABYLON = {}));
  58098. //# sourceMappingURL=babylon.virtualJoystick.js.map
  58099. var BABYLON;
  58100. (function (BABYLON) {
  58101. // We're mainly based on the logic defined into the FreeCamera code
  58102. var VirtualJoysticksCamera = (function (_super) {
  58103. __extends(VirtualJoysticksCamera, _super);
  58104. function VirtualJoysticksCamera(name, position, scene) {
  58105. var _this = _super.call(this, name, position, scene) || this;
  58106. _this.inputs.addVirtualJoystick();
  58107. return _this;
  58108. }
  58109. VirtualJoysticksCamera.prototype.getClassName = function () {
  58110. return "VirtualJoysticksCamera";
  58111. };
  58112. return VirtualJoysticksCamera;
  58113. }(BABYLON.FreeCamera));
  58114. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  58115. })(BABYLON || (BABYLON = {}));
  58116. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  58117. var BABYLON;
  58118. (function (BABYLON) {
  58119. var FreeCameraVirtualJoystickInput = (function () {
  58120. function FreeCameraVirtualJoystickInput() {
  58121. }
  58122. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  58123. return this._leftjoystick;
  58124. };
  58125. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  58126. return this._rightjoystick;
  58127. };
  58128. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  58129. if (this._leftjoystick) {
  58130. var camera = this.camera;
  58131. var speed = camera._computeLocalCameraSpeed() * 50;
  58132. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  58133. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  58134. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  58135. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  58136. if (!this._leftjoystick.pressed) {
  58137. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  58138. }
  58139. if (!this._rightjoystick.pressed) {
  58140. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  58141. }
  58142. }
  58143. };
  58144. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  58145. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  58146. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  58147. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  58148. this._leftjoystick.setJoystickSensibility(0.15);
  58149. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  58150. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  58151. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  58152. this._rightjoystick.reverseUpDown = true;
  58153. this._rightjoystick.setJoystickSensibility(0.05);
  58154. this._rightjoystick.setJoystickColor("yellow");
  58155. };
  58156. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  58157. this._leftjoystick.releaseCanvas();
  58158. this._rightjoystick.releaseCanvas();
  58159. };
  58160. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  58161. return "FreeCameraVirtualJoystickInput";
  58162. };
  58163. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  58164. return "virtualJoystick";
  58165. };
  58166. return FreeCameraVirtualJoystickInput;
  58167. }());
  58168. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  58169. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  58170. })(BABYLON || (BABYLON = {}));
  58171. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  58172. var BABYLON;
  58173. (function (BABYLON) {
  58174. var SimplificationSettings = (function () {
  58175. function SimplificationSettings(quality, distance, optimizeMesh) {
  58176. this.quality = quality;
  58177. this.distance = distance;
  58178. this.optimizeMesh = optimizeMesh;
  58179. }
  58180. return SimplificationSettings;
  58181. }());
  58182. BABYLON.SimplificationSettings = SimplificationSettings;
  58183. var SimplificationQueue = (function () {
  58184. function SimplificationQueue() {
  58185. this.running = false;
  58186. this._simplificationArray = [];
  58187. }
  58188. SimplificationQueue.prototype.addTask = function (task) {
  58189. this._simplificationArray.push(task);
  58190. };
  58191. SimplificationQueue.prototype.executeNext = function () {
  58192. var task = this._simplificationArray.pop();
  58193. if (task) {
  58194. this.running = true;
  58195. this.runSimplification(task);
  58196. }
  58197. else {
  58198. this.running = false;
  58199. }
  58200. };
  58201. SimplificationQueue.prototype.runSimplification = function (task) {
  58202. var _this = this;
  58203. if (task.parallelProcessing) {
  58204. //parallel simplifier
  58205. task.settings.forEach(function (setting) {
  58206. var simplifier = _this.getSimplifier(task);
  58207. simplifier.simplify(setting, function (newMesh) {
  58208. task.mesh.addLODLevel(setting.distance, newMesh);
  58209. newMesh.isVisible = true;
  58210. //check if it is the last
  58211. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  58212. //all done, run the success callback.
  58213. task.successCallback();
  58214. }
  58215. _this.executeNext();
  58216. });
  58217. });
  58218. }
  58219. else {
  58220. //single simplifier.
  58221. var simplifier = this.getSimplifier(task);
  58222. var runDecimation = function (setting, callback) {
  58223. simplifier.simplify(setting, function (newMesh) {
  58224. task.mesh.addLODLevel(setting.distance, newMesh);
  58225. newMesh.isVisible = true;
  58226. //run the next quality level
  58227. callback();
  58228. });
  58229. };
  58230. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  58231. runDecimation(task.settings[loop.index], function () {
  58232. loop.executeNext();
  58233. });
  58234. }, function () {
  58235. //execution ended, run the success callback.
  58236. if (task.successCallback) {
  58237. task.successCallback();
  58238. }
  58239. _this.executeNext();
  58240. });
  58241. }
  58242. };
  58243. SimplificationQueue.prototype.getSimplifier = function (task) {
  58244. switch (task.simplificationType) {
  58245. case SimplificationType.QUADRATIC:
  58246. default:
  58247. return new QuadraticErrorSimplification(task.mesh);
  58248. }
  58249. };
  58250. return SimplificationQueue;
  58251. }());
  58252. BABYLON.SimplificationQueue = SimplificationQueue;
  58253. /**
  58254. * The implemented types of simplification.
  58255. * At the moment only Quadratic Error Decimation is implemented.
  58256. */
  58257. var SimplificationType;
  58258. (function (SimplificationType) {
  58259. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  58260. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  58261. var DecimationTriangle = (function () {
  58262. function DecimationTriangle(vertices) {
  58263. this.vertices = vertices;
  58264. this.error = new Array(4);
  58265. this.deleted = false;
  58266. this.isDirty = false;
  58267. this.deletePending = false;
  58268. this.borderFactor = 0;
  58269. }
  58270. return DecimationTriangle;
  58271. }());
  58272. BABYLON.DecimationTriangle = DecimationTriangle;
  58273. var DecimationVertex = (function () {
  58274. function DecimationVertex(position, id) {
  58275. this.position = position;
  58276. this.id = id;
  58277. this.isBorder = true;
  58278. this.q = new QuadraticMatrix();
  58279. this.triangleCount = 0;
  58280. this.triangleStart = 0;
  58281. this.originalOffsets = [];
  58282. }
  58283. DecimationVertex.prototype.updatePosition = function (newPosition) {
  58284. this.position.copyFrom(newPosition);
  58285. };
  58286. return DecimationVertex;
  58287. }());
  58288. BABYLON.DecimationVertex = DecimationVertex;
  58289. var QuadraticMatrix = (function () {
  58290. function QuadraticMatrix(data) {
  58291. this.data = new Array(10);
  58292. for (var i = 0; i < 10; ++i) {
  58293. if (data && data[i]) {
  58294. this.data[i] = data[i];
  58295. }
  58296. else {
  58297. this.data[i] = 0;
  58298. }
  58299. }
  58300. }
  58301. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  58302. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  58303. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  58304. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  58305. return det;
  58306. };
  58307. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  58308. for (var i = 0; i < 10; ++i) {
  58309. this.data[i] += matrix.data[i];
  58310. }
  58311. };
  58312. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  58313. for (var i = 0; i < 10; ++i) {
  58314. this.data[i] += data[i];
  58315. }
  58316. };
  58317. QuadraticMatrix.prototype.add = function (matrix) {
  58318. var m = new QuadraticMatrix();
  58319. for (var i = 0; i < 10; ++i) {
  58320. m.data[i] = this.data[i] + matrix.data[i];
  58321. }
  58322. return m;
  58323. };
  58324. QuadraticMatrix.FromData = function (a, b, c, d) {
  58325. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  58326. };
  58327. //returning an array to avoid garbage collection
  58328. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  58329. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  58330. };
  58331. return QuadraticMatrix;
  58332. }());
  58333. BABYLON.QuadraticMatrix = QuadraticMatrix;
  58334. var Reference = (function () {
  58335. function Reference(vertexId, triangleId) {
  58336. this.vertexId = vertexId;
  58337. this.triangleId = triangleId;
  58338. }
  58339. return Reference;
  58340. }());
  58341. BABYLON.Reference = Reference;
  58342. /**
  58343. * An implementation of the Quadratic Error simplification algorithm.
  58344. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  58345. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  58346. * @author RaananW
  58347. */
  58348. var QuadraticErrorSimplification = (function () {
  58349. function QuadraticErrorSimplification(_mesh) {
  58350. this._mesh = _mesh;
  58351. this.initialized = false;
  58352. this.syncIterations = 5000;
  58353. this.aggressiveness = 7;
  58354. this.decimationIterations = 100;
  58355. this.boundingBoxEpsilon = BABYLON.Epsilon;
  58356. }
  58357. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  58358. var _this = this;
  58359. this.initDecimatedMesh();
  58360. //iterating through the submeshes array, one after the other.
  58361. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  58362. _this.initWithMesh(loop.index, function () {
  58363. _this.runDecimation(settings, loop.index, function () {
  58364. loop.executeNext();
  58365. });
  58366. }, settings.optimizeMesh);
  58367. }, function () {
  58368. setTimeout(function () {
  58369. successCallback(_this._reconstructedMesh);
  58370. }, 0);
  58371. });
  58372. };
  58373. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  58374. var _this = this;
  58375. var gCount = 0;
  58376. triangle.vertices.forEach(function (vertex) {
  58377. var count = 0;
  58378. var vPos = vertex.position;
  58379. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  58380. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  58381. ++count;
  58382. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  58383. ++count;
  58384. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  58385. ++count;
  58386. if (count > 1) {
  58387. ++gCount;
  58388. }
  58389. ;
  58390. });
  58391. if (gCount > 1) {
  58392. console.log(triangle, gCount);
  58393. }
  58394. return gCount > 1;
  58395. };
  58396. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  58397. var _this = this;
  58398. var targetCount = ~~(this.triangles.length * settings.quality);
  58399. var deletedTriangles = 0;
  58400. var triangleCount = this.triangles.length;
  58401. var iterationFunction = function (iteration, callback) {
  58402. setTimeout(function () {
  58403. if (iteration % 5 === 0) {
  58404. _this.updateMesh(iteration === 0);
  58405. }
  58406. for (var i = 0; i < _this.triangles.length; ++i) {
  58407. _this.triangles[i].isDirty = false;
  58408. }
  58409. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  58410. var trianglesIterator = function (i) {
  58411. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  58412. var t = _this.triangles[tIdx];
  58413. if (!t)
  58414. return;
  58415. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  58416. return;
  58417. }
  58418. for (var j = 0; j < 3; ++j) {
  58419. if (t.error[j] < threshold) {
  58420. var deleted0 = [];
  58421. var deleted1 = [];
  58422. var v0 = t.vertices[j];
  58423. var v1 = t.vertices[(j + 1) % 3];
  58424. if (v0.isBorder || v1.isBorder)
  58425. continue;
  58426. var p = BABYLON.Vector3.Zero();
  58427. var n = BABYLON.Vector3.Zero();
  58428. var uv = BABYLON.Vector2.Zero();
  58429. var color = new BABYLON.Color4(0, 0, 0, 1);
  58430. _this.calculateError(v0, v1, p, n, uv, color);
  58431. var delTr = [];
  58432. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  58433. continue;
  58434. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  58435. continue;
  58436. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  58437. continue;
  58438. var uniqueArray = [];
  58439. delTr.forEach(function (deletedT) {
  58440. if (uniqueArray.indexOf(deletedT) === -1) {
  58441. deletedT.deletePending = true;
  58442. uniqueArray.push(deletedT);
  58443. }
  58444. });
  58445. if (uniqueArray.length % 2 !== 0) {
  58446. continue;
  58447. }
  58448. v0.q = v1.q.add(v0.q);
  58449. v0.updatePosition(p);
  58450. var tStart = _this.references.length;
  58451. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  58452. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  58453. var tCount = _this.references.length - tStart;
  58454. if (tCount <= v0.triangleCount) {
  58455. if (tCount) {
  58456. for (var c = 0; c < tCount; c++) {
  58457. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  58458. }
  58459. }
  58460. }
  58461. else {
  58462. v0.triangleStart = tStart;
  58463. }
  58464. v0.triangleCount = tCount;
  58465. break;
  58466. }
  58467. }
  58468. };
  58469. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  58470. }, 0);
  58471. };
  58472. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  58473. if (triangleCount - deletedTriangles <= targetCount)
  58474. loop.breakLoop();
  58475. else {
  58476. iterationFunction(loop.index, function () {
  58477. loop.executeNext();
  58478. });
  58479. }
  58480. }, function () {
  58481. setTimeout(function () {
  58482. //reconstruct this part of the mesh
  58483. _this.reconstructMesh(submeshIndex);
  58484. successCallback();
  58485. }, 0);
  58486. });
  58487. };
  58488. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  58489. var _this = this;
  58490. this.vertices = [];
  58491. this.triangles = [];
  58492. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58493. var indices = this._mesh.getIndices();
  58494. var submesh = this._mesh.subMeshes[submeshIndex];
  58495. var findInVertices = function (positionToSearch) {
  58496. if (optimizeMesh) {
  58497. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  58498. if (_this.vertices[ii].position.equals(positionToSearch)) {
  58499. return _this.vertices[ii];
  58500. }
  58501. }
  58502. }
  58503. return null;
  58504. };
  58505. var vertexReferences = [];
  58506. var vertexInit = function (i) {
  58507. var offset = i + submesh.verticesStart;
  58508. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  58509. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  58510. vertex.originalOffsets.push(offset);
  58511. if (vertex.id === _this.vertices.length) {
  58512. _this.vertices.push(vertex);
  58513. }
  58514. vertexReferences.push(vertex.id);
  58515. };
  58516. //var totalVertices = mesh.getTotalVertices();
  58517. var totalVertices = submesh.verticesCount;
  58518. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  58519. var indicesInit = function (i) {
  58520. var offset = (submesh.indexStart / 3) + i;
  58521. var pos = (offset * 3);
  58522. var i0 = indices[pos + 0];
  58523. var i1 = indices[pos + 1];
  58524. var i2 = indices[pos + 2];
  58525. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  58526. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  58527. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  58528. var triangle = new DecimationTriangle([v0, v1, v2]);
  58529. triangle.originalOffset = pos;
  58530. _this.triangles.push(triangle);
  58531. };
  58532. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  58533. _this.init(callback);
  58534. });
  58535. });
  58536. };
  58537. QuadraticErrorSimplification.prototype.init = function (callback) {
  58538. var _this = this;
  58539. var triangleInit1 = function (i) {
  58540. var t = _this.triangles[i];
  58541. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  58542. for (var j = 0; j < 3; j++) {
  58543. 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))));
  58544. }
  58545. };
  58546. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  58547. var triangleInit2 = function (i) {
  58548. var t = _this.triangles[i];
  58549. for (var j = 0; j < 3; ++j) {
  58550. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  58551. }
  58552. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  58553. };
  58554. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  58555. _this.initialized = true;
  58556. callback();
  58557. });
  58558. });
  58559. };
  58560. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  58561. var newTriangles = [];
  58562. var i;
  58563. for (i = 0; i < this.vertices.length; ++i) {
  58564. this.vertices[i].triangleCount = 0;
  58565. }
  58566. var t;
  58567. var j;
  58568. for (i = 0; i < this.triangles.length; ++i) {
  58569. if (!this.triangles[i].deleted) {
  58570. t = this.triangles[i];
  58571. for (j = 0; j < 3; ++j) {
  58572. t.vertices[j].triangleCount = 1;
  58573. }
  58574. newTriangles.push(t);
  58575. }
  58576. }
  58577. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  58578. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  58579. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  58580. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  58581. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58582. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58583. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58584. var vertexCount = 0;
  58585. for (i = 0; i < this.vertices.length; ++i) {
  58586. var vertex = this.vertices[i];
  58587. vertex.id = vertexCount;
  58588. if (vertex.triangleCount) {
  58589. vertex.originalOffsets.forEach(function (originalOffset) {
  58590. newPositionData.push(vertex.position.x);
  58591. newPositionData.push(vertex.position.y);
  58592. newPositionData.push(vertex.position.z);
  58593. newNormalData.push(normalData[originalOffset * 3]);
  58594. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  58595. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  58596. if (uvs && uvs.length) {
  58597. newUVsData.push(uvs[(originalOffset * 2)]);
  58598. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  58599. }
  58600. else if (colorsData && colorsData.length) {
  58601. newColorsData.push(colorsData[(originalOffset * 4)]);
  58602. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  58603. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  58604. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  58605. }
  58606. ++vertexCount;
  58607. });
  58608. }
  58609. }
  58610. var startingIndex = this._reconstructedMesh.getTotalIndices();
  58611. var startingVertex = this._reconstructedMesh.getTotalVertices();
  58612. var submeshesArray = this._reconstructedMesh.subMeshes;
  58613. this._reconstructedMesh.subMeshes = [];
  58614. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  58615. var originalIndices = this._mesh.getIndices();
  58616. for (i = 0; i < newTriangles.length; ++i) {
  58617. t = newTriangles[i]; //now get the new referencing point for each vertex
  58618. [0, 1, 2].forEach(function (idx) {
  58619. var id = originalIndices[t.originalOffset + idx];
  58620. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  58621. if (offset < 0)
  58622. offset = 0;
  58623. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  58624. });
  58625. }
  58626. //overwriting the old vertex buffers and indices.
  58627. this._reconstructedMesh.setIndices(newIndicesArray);
  58628. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  58629. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  58630. if (newUVsData.length > 0)
  58631. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  58632. if (newColorsData.length > 0)
  58633. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  58634. //create submesh
  58635. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  58636. if (submeshIndex > 0) {
  58637. this._reconstructedMesh.subMeshes = [];
  58638. submeshesArray.forEach(function (submesh) {
  58639. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  58640. });
  58641. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  58642. }
  58643. };
  58644. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  58645. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  58646. this._reconstructedMesh.material = this._mesh.material;
  58647. this._reconstructedMesh.parent = this._mesh.parent;
  58648. this._reconstructedMesh.isVisible = false;
  58649. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  58650. };
  58651. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  58652. for (var i = 0; i < vertex1.triangleCount; ++i) {
  58653. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  58654. if (t.deleted)
  58655. continue;
  58656. var s = this.references[vertex1.triangleStart + i].vertexId;
  58657. var v1 = t.vertices[(s + 1) % 3];
  58658. var v2 = t.vertices[(s + 2) % 3];
  58659. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  58660. deletedArray[i] = true;
  58661. delTr.push(t);
  58662. continue;
  58663. }
  58664. var d1 = v1.position.subtract(point);
  58665. d1 = d1.normalize();
  58666. var d2 = v2.position.subtract(point);
  58667. d2 = d2.normalize();
  58668. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  58669. return true;
  58670. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  58671. deletedArray[i] = false;
  58672. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  58673. return true;
  58674. }
  58675. return false;
  58676. };
  58677. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  58678. var newDeleted = deletedTriangles;
  58679. for (var i = 0; i < vertex.triangleCount; ++i) {
  58680. var ref = this.references[vertex.triangleStart + i];
  58681. var t = this.triangles[ref.triangleId];
  58682. if (t.deleted)
  58683. continue;
  58684. if (deletedArray[i] && t.deletePending) {
  58685. t.deleted = true;
  58686. newDeleted++;
  58687. continue;
  58688. }
  58689. t.vertices[ref.vertexId] = origVertex;
  58690. t.isDirty = true;
  58691. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  58692. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  58693. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  58694. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  58695. this.references.push(ref);
  58696. }
  58697. return newDeleted;
  58698. };
  58699. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  58700. for (var i = 0; i < this.vertices.length; ++i) {
  58701. var vCount = [];
  58702. var vId = [];
  58703. var v = this.vertices[i];
  58704. var j;
  58705. for (j = 0; j < v.triangleCount; ++j) {
  58706. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  58707. for (var ii = 0; ii < 3; ii++) {
  58708. var ofs = 0;
  58709. var vv = triangle.vertices[ii];
  58710. while (ofs < vCount.length) {
  58711. if (vId[ofs] === vv.id)
  58712. break;
  58713. ++ofs;
  58714. }
  58715. if (ofs === vCount.length) {
  58716. vCount.push(1);
  58717. vId.push(vv.id);
  58718. }
  58719. else {
  58720. vCount[ofs]++;
  58721. }
  58722. }
  58723. }
  58724. for (j = 0; j < vCount.length; ++j) {
  58725. if (vCount[j] === 1) {
  58726. this.vertices[vId[j]].isBorder = true;
  58727. }
  58728. else {
  58729. this.vertices[vId[j]].isBorder = false;
  58730. }
  58731. }
  58732. }
  58733. };
  58734. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  58735. if (identifyBorders === void 0) { identifyBorders = false; }
  58736. var i;
  58737. if (!identifyBorders) {
  58738. var newTrianglesVector = [];
  58739. for (i = 0; i < this.triangles.length; ++i) {
  58740. if (!this.triangles[i].deleted) {
  58741. newTrianglesVector.push(this.triangles[i]);
  58742. }
  58743. }
  58744. this.triangles = newTrianglesVector;
  58745. }
  58746. for (i = 0; i < this.vertices.length; ++i) {
  58747. this.vertices[i].triangleCount = 0;
  58748. this.vertices[i].triangleStart = 0;
  58749. }
  58750. var t;
  58751. var j;
  58752. var v;
  58753. for (i = 0; i < this.triangles.length; ++i) {
  58754. t = this.triangles[i];
  58755. for (j = 0; j < 3; ++j) {
  58756. v = t.vertices[j];
  58757. v.triangleCount++;
  58758. }
  58759. }
  58760. var tStart = 0;
  58761. for (i = 0; i < this.vertices.length; ++i) {
  58762. this.vertices[i].triangleStart = tStart;
  58763. tStart += this.vertices[i].triangleCount;
  58764. this.vertices[i].triangleCount = 0;
  58765. }
  58766. var newReferences = new Array(this.triangles.length * 3);
  58767. for (i = 0; i < this.triangles.length; ++i) {
  58768. t = this.triangles[i];
  58769. for (j = 0; j < 3; ++j) {
  58770. v = t.vertices[j];
  58771. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  58772. v.triangleCount++;
  58773. }
  58774. }
  58775. this.references = newReferences;
  58776. if (identifyBorders) {
  58777. this.identifyBorder();
  58778. }
  58779. };
  58780. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  58781. var x = point.x;
  58782. var y = point.y;
  58783. var z = point.z;
  58784. 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
  58785. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  58786. };
  58787. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  58788. var q = vertex1.q.add(vertex2.q);
  58789. var border = vertex1.isBorder && vertex2.isBorder;
  58790. var error = 0;
  58791. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  58792. if (qDet !== 0 && !border) {
  58793. if (!pointResult) {
  58794. pointResult = BABYLON.Vector3.Zero();
  58795. }
  58796. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  58797. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  58798. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  58799. error = this.vertexError(q, pointResult);
  58800. }
  58801. else {
  58802. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  58803. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  58804. var error1 = this.vertexError(q, vertex1.position);
  58805. var error2 = this.vertexError(q, vertex2.position);
  58806. var error3 = this.vertexError(q, p3);
  58807. error = Math.min(error1, error2, error3);
  58808. if (error === error1) {
  58809. if (pointResult) {
  58810. pointResult.copyFrom(vertex1.position);
  58811. }
  58812. }
  58813. else if (error === error2) {
  58814. if (pointResult) {
  58815. pointResult.copyFrom(vertex2.position);
  58816. }
  58817. }
  58818. else {
  58819. if (pointResult) {
  58820. pointResult.copyFrom(p3);
  58821. }
  58822. }
  58823. }
  58824. return error;
  58825. };
  58826. return QuadraticErrorSimplification;
  58827. }());
  58828. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  58829. })(BABYLON || (BABYLON = {}));
  58830. //# sourceMappingURL=babylon.meshSimplification.js.map
  58831. var BABYLON;
  58832. (function (BABYLON) {
  58833. var Internals;
  58834. (function (Internals) {
  58835. var MeshLODLevel = (function () {
  58836. function MeshLODLevel(distance, mesh) {
  58837. this.distance = distance;
  58838. this.mesh = mesh;
  58839. }
  58840. return MeshLODLevel;
  58841. }());
  58842. Internals.MeshLODLevel = MeshLODLevel;
  58843. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58844. })(BABYLON || (BABYLON = {}));
  58845. //# sourceMappingURL=babylon.meshLODLevel.js.map
  58846. var BABYLON;
  58847. (function (BABYLON) {
  58848. // Standard optimizations
  58849. var SceneOptimization = (function () {
  58850. function SceneOptimization(priority) {
  58851. if (priority === void 0) { priority = 0; }
  58852. this.priority = priority;
  58853. this.apply = function (scene) {
  58854. return true; // Return true if everything that can be done was applied
  58855. };
  58856. }
  58857. return SceneOptimization;
  58858. }());
  58859. BABYLON.SceneOptimization = SceneOptimization;
  58860. var TextureOptimization = (function (_super) {
  58861. __extends(TextureOptimization, _super);
  58862. function TextureOptimization(priority, maximumSize) {
  58863. if (priority === void 0) { priority = 0; }
  58864. if (maximumSize === void 0) { maximumSize = 1024; }
  58865. var _this = _super.call(this, priority) || this;
  58866. _this.priority = priority;
  58867. _this.maximumSize = maximumSize;
  58868. _this.apply = function (scene) {
  58869. var allDone = true;
  58870. for (var index = 0; index < scene.textures.length; index++) {
  58871. var texture = scene.textures[index];
  58872. if (!texture.canRescale) {
  58873. continue;
  58874. }
  58875. var currentSize = texture.getSize();
  58876. var maxDimension = Math.max(currentSize.width, currentSize.height);
  58877. if (maxDimension > _this.maximumSize) {
  58878. texture.scale(0.5);
  58879. allDone = false;
  58880. }
  58881. }
  58882. return allDone;
  58883. };
  58884. return _this;
  58885. }
  58886. return TextureOptimization;
  58887. }(SceneOptimization));
  58888. BABYLON.TextureOptimization = TextureOptimization;
  58889. var HardwareScalingOptimization = (function (_super) {
  58890. __extends(HardwareScalingOptimization, _super);
  58891. function HardwareScalingOptimization(priority, maximumScale) {
  58892. if (priority === void 0) { priority = 0; }
  58893. if (maximumScale === void 0) { maximumScale = 2; }
  58894. var _this = _super.call(this, priority) || this;
  58895. _this.priority = priority;
  58896. _this.maximumScale = maximumScale;
  58897. _this._currentScale = 1;
  58898. _this.apply = function (scene) {
  58899. _this._currentScale++;
  58900. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  58901. return _this._currentScale >= _this.maximumScale;
  58902. };
  58903. return _this;
  58904. }
  58905. return HardwareScalingOptimization;
  58906. }(SceneOptimization));
  58907. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  58908. var ShadowsOptimization = (function (_super) {
  58909. __extends(ShadowsOptimization, _super);
  58910. function ShadowsOptimization() {
  58911. var _this = _super !== null && _super.apply(this, arguments) || this;
  58912. _this.apply = function (scene) {
  58913. scene.shadowsEnabled = false;
  58914. return true;
  58915. };
  58916. return _this;
  58917. }
  58918. return ShadowsOptimization;
  58919. }(SceneOptimization));
  58920. BABYLON.ShadowsOptimization = ShadowsOptimization;
  58921. var PostProcessesOptimization = (function (_super) {
  58922. __extends(PostProcessesOptimization, _super);
  58923. function PostProcessesOptimization() {
  58924. var _this = _super !== null && _super.apply(this, arguments) || this;
  58925. _this.apply = function (scene) {
  58926. scene.postProcessesEnabled = false;
  58927. return true;
  58928. };
  58929. return _this;
  58930. }
  58931. return PostProcessesOptimization;
  58932. }(SceneOptimization));
  58933. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  58934. var LensFlaresOptimization = (function (_super) {
  58935. __extends(LensFlaresOptimization, _super);
  58936. function LensFlaresOptimization() {
  58937. var _this = _super !== null && _super.apply(this, arguments) || this;
  58938. _this.apply = function (scene) {
  58939. scene.lensFlaresEnabled = false;
  58940. return true;
  58941. };
  58942. return _this;
  58943. }
  58944. return LensFlaresOptimization;
  58945. }(SceneOptimization));
  58946. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  58947. var ParticlesOptimization = (function (_super) {
  58948. __extends(ParticlesOptimization, _super);
  58949. function ParticlesOptimization() {
  58950. var _this = _super !== null && _super.apply(this, arguments) || this;
  58951. _this.apply = function (scene) {
  58952. scene.particlesEnabled = false;
  58953. return true;
  58954. };
  58955. return _this;
  58956. }
  58957. return ParticlesOptimization;
  58958. }(SceneOptimization));
  58959. BABYLON.ParticlesOptimization = ParticlesOptimization;
  58960. var RenderTargetsOptimization = (function (_super) {
  58961. __extends(RenderTargetsOptimization, _super);
  58962. function RenderTargetsOptimization() {
  58963. var _this = _super !== null && _super.apply(this, arguments) || this;
  58964. _this.apply = function (scene) {
  58965. scene.renderTargetsEnabled = false;
  58966. return true;
  58967. };
  58968. return _this;
  58969. }
  58970. return RenderTargetsOptimization;
  58971. }(SceneOptimization));
  58972. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  58973. var MergeMeshesOptimization = (function (_super) {
  58974. __extends(MergeMeshesOptimization, _super);
  58975. function MergeMeshesOptimization() {
  58976. var _this = _super !== null && _super.apply(this, arguments) || this;
  58977. _this._canBeMerged = function (abstractMesh) {
  58978. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  58979. return false;
  58980. }
  58981. var mesh = abstractMesh;
  58982. if (!mesh.isVisible || !mesh.isEnabled()) {
  58983. return false;
  58984. }
  58985. if (mesh.instances.length > 0) {
  58986. return false;
  58987. }
  58988. if (mesh.skeleton || mesh.hasLODLevels) {
  58989. return false;
  58990. }
  58991. if (mesh.parent) {
  58992. return false;
  58993. }
  58994. return true;
  58995. };
  58996. _this.apply = function (scene, updateSelectionTree) {
  58997. var globalPool = scene.meshes.slice(0);
  58998. var globalLength = globalPool.length;
  58999. for (var index = 0; index < globalLength; index++) {
  59000. var currentPool = new Array();
  59001. var current = globalPool[index];
  59002. // Checks
  59003. if (!_this._canBeMerged(current)) {
  59004. continue;
  59005. }
  59006. currentPool.push(current);
  59007. // Find compatible meshes
  59008. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  59009. var otherMesh = globalPool[subIndex];
  59010. if (!_this._canBeMerged(otherMesh)) {
  59011. continue;
  59012. }
  59013. if (otherMesh.material !== current.material) {
  59014. continue;
  59015. }
  59016. if (otherMesh.checkCollisions !== current.checkCollisions) {
  59017. continue;
  59018. }
  59019. currentPool.push(otherMesh);
  59020. globalLength--;
  59021. globalPool.splice(subIndex, 1);
  59022. subIndex--;
  59023. }
  59024. if (currentPool.length < 2) {
  59025. continue;
  59026. }
  59027. // Merge meshes
  59028. BABYLON.Mesh.MergeMeshes(currentPool);
  59029. }
  59030. if (updateSelectionTree != undefined) {
  59031. if (updateSelectionTree) {
  59032. scene.createOrUpdateSelectionOctree();
  59033. }
  59034. }
  59035. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  59036. scene.createOrUpdateSelectionOctree();
  59037. }
  59038. return true;
  59039. };
  59040. return _this;
  59041. }
  59042. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  59043. get: function () {
  59044. return MergeMeshesOptimization._UpdateSelectionTree;
  59045. },
  59046. set: function (value) {
  59047. MergeMeshesOptimization._UpdateSelectionTree = value;
  59048. },
  59049. enumerable: true,
  59050. configurable: true
  59051. });
  59052. return MergeMeshesOptimization;
  59053. }(SceneOptimization));
  59054. MergeMeshesOptimization._UpdateSelectionTree = false;
  59055. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  59056. // Options
  59057. var SceneOptimizerOptions = (function () {
  59058. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  59059. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  59060. if (trackerDuration === void 0) { trackerDuration = 2000; }
  59061. this.targetFrameRate = targetFrameRate;
  59062. this.trackerDuration = trackerDuration;
  59063. this.optimizations = new Array();
  59064. }
  59065. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  59066. var result = new SceneOptimizerOptions(targetFrameRate);
  59067. var priority = 0;
  59068. result.optimizations.push(new MergeMeshesOptimization(priority));
  59069. result.optimizations.push(new ShadowsOptimization(priority));
  59070. result.optimizations.push(new LensFlaresOptimization(priority));
  59071. // Next priority
  59072. priority++;
  59073. result.optimizations.push(new PostProcessesOptimization(priority));
  59074. result.optimizations.push(new ParticlesOptimization(priority));
  59075. // Next priority
  59076. priority++;
  59077. result.optimizations.push(new TextureOptimization(priority, 1024));
  59078. return result;
  59079. };
  59080. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  59081. var result = new SceneOptimizerOptions(targetFrameRate);
  59082. var priority = 0;
  59083. result.optimizations.push(new MergeMeshesOptimization(priority));
  59084. result.optimizations.push(new ShadowsOptimization(priority));
  59085. result.optimizations.push(new LensFlaresOptimization(priority));
  59086. // Next priority
  59087. priority++;
  59088. result.optimizations.push(new PostProcessesOptimization(priority));
  59089. result.optimizations.push(new ParticlesOptimization(priority));
  59090. // Next priority
  59091. priority++;
  59092. result.optimizations.push(new TextureOptimization(priority, 512));
  59093. // Next priority
  59094. priority++;
  59095. result.optimizations.push(new RenderTargetsOptimization(priority));
  59096. // Next priority
  59097. priority++;
  59098. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  59099. return result;
  59100. };
  59101. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  59102. var result = new SceneOptimizerOptions(targetFrameRate);
  59103. var priority = 0;
  59104. result.optimizations.push(new MergeMeshesOptimization(priority));
  59105. result.optimizations.push(new ShadowsOptimization(priority));
  59106. result.optimizations.push(new LensFlaresOptimization(priority));
  59107. // Next priority
  59108. priority++;
  59109. result.optimizations.push(new PostProcessesOptimization(priority));
  59110. result.optimizations.push(new ParticlesOptimization(priority));
  59111. // Next priority
  59112. priority++;
  59113. result.optimizations.push(new TextureOptimization(priority, 256));
  59114. // Next priority
  59115. priority++;
  59116. result.optimizations.push(new RenderTargetsOptimization(priority));
  59117. // Next priority
  59118. priority++;
  59119. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  59120. return result;
  59121. };
  59122. return SceneOptimizerOptions;
  59123. }());
  59124. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  59125. // Scene optimizer tool
  59126. var SceneOptimizer = (function () {
  59127. function SceneOptimizer() {
  59128. }
  59129. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  59130. // TODO: add an epsilon
  59131. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  59132. if (onSuccess) {
  59133. onSuccess();
  59134. }
  59135. return;
  59136. }
  59137. // Apply current level of optimizations
  59138. var allDone = true;
  59139. var noOptimizationApplied = true;
  59140. for (var index = 0; index < options.optimizations.length; index++) {
  59141. var optimization = options.optimizations[index];
  59142. if (optimization.priority === currentPriorityLevel) {
  59143. noOptimizationApplied = false;
  59144. allDone = allDone && optimization.apply(scene);
  59145. }
  59146. }
  59147. // If no optimization was applied, this is a failure :(
  59148. if (noOptimizationApplied) {
  59149. if (onFailure) {
  59150. onFailure();
  59151. }
  59152. return;
  59153. }
  59154. // If all optimizations were done, move to next level
  59155. if (allDone) {
  59156. currentPriorityLevel++;
  59157. }
  59158. // Let's the system running for a specific amount of time before checking FPS
  59159. scene.executeWhenReady(function () {
  59160. setTimeout(function () {
  59161. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  59162. }, options.trackerDuration);
  59163. });
  59164. };
  59165. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  59166. if (!options) {
  59167. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  59168. }
  59169. // Let's the system running for a specific amount of time before checking FPS
  59170. scene.executeWhenReady(function () {
  59171. setTimeout(function () {
  59172. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  59173. }, options.trackerDuration);
  59174. });
  59175. };
  59176. return SceneOptimizer;
  59177. }());
  59178. BABYLON.SceneOptimizer = SceneOptimizer;
  59179. })(BABYLON || (BABYLON = {}));
  59180. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  59181. var BABYLON;
  59182. (function (BABYLON) {
  59183. var OutlineRenderer = (function () {
  59184. function OutlineRenderer(scene) {
  59185. this._scene = scene;
  59186. }
  59187. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  59188. var _this = this;
  59189. if (useOverlay === void 0) { useOverlay = false; }
  59190. var scene = this._scene;
  59191. var engine = this._scene.getEngine();
  59192. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59193. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  59194. return;
  59195. }
  59196. var mesh = subMesh.getRenderingMesh();
  59197. var material = subMesh.getMaterial();
  59198. engine.enableEffect(this._effect);
  59199. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  59200. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  59201. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59202. // Bones
  59203. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59204. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59205. }
  59206. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  59207. // Alpha test
  59208. if (material && material.needAlphaTesting()) {
  59209. var alphaTexture = material.getAlphaTestTexture();
  59210. this._effect.setTexture("diffuseSampler", alphaTexture);
  59211. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59212. }
  59213. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  59214. };
  59215. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  59216. var defines = [];
  59217. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  59218. var mesh = subMesh.getMesh();
  59219. var material = subMesh.getMaterial();
  59220. // Alpha test
  59221. if (material && material.needAlphaTesting()) {
  59222. defines.push("#define ALPHATEST");
  59223. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59224. attribs.push(BABYLON.VertexBuffer.UVKind);
  59225. defines.push("#define UV1");
  59226. }
  59227. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59228. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59229. defines.push("#define UV2");
  59230. }
  59231. }
  59232. // Bones
  59233. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59234. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59235. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59236. if (mesh.numBoneInfluencers > 4) {
  59237. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59238. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59239. }
  59240. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59241. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59242. }
  59243. else {
  59244. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59245. }
  59246. // Instances
  59247. if (useInstances) {
  59248. defines.push("#define INSTANCES");
  59249. attribs.push("world0");
  59250. attribs.push("world1");
  59251. attribs.push("world2");
  59252. attribs.push("world3");
  59253. }
  59254. // Get correct effect
  59255. var join = defines.join("\n");
  59256. if (this._cachedDefines !== join) {
  59257. this._cachedDefines = join;
  59258. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  59259. }
  59260. return this._effect.isReady();
  59261. };
  59262. return OutlineRenderer;
  59263. }());
  59264. BABYLON.OutlineRenderer = OutlineRenderer;
  59265. })(BABYLON || (BABYLON = {}));
  59266. //# sourceMappingURL=babylon.outlineRenderer.js.map
  59267. var BABYLON;
  59268. (function (BABYLON) {
  59269. var FaceAdjacencies = (function () {
  59270. function FaceAdjacencies() {
  59271. this.edges = new Array();
  59272. this.edgesConnectedCount = 0;
  59273. }
  59274. return FaceAdjacencies;
  59275. }());
  59276. var EdgesRenderer = (function () {
  59277. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  59278. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  59279. if (epsilon === void 0) { epsilon = 0.95; }
  59280. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  59281. this.edgesWidthScalerForOrthographic = 1000.0;
  59282. this.edgesWidthScalerForPerspective = 50.0;
  59283. this._linesPositions = new Array();
  59284. this._linesNormals = new Array();
  59285. this._linesIndices = new Array();
  59286. this._buffers = {};
  59287. this._checkVerticesInsteadOfIndices = false;
  59288. this._source = source;
  59289. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  59290. this._epsilon = epsilon;
  59291. this._prepareRessources();
  59292. this._generateEdgesLines();
  59293. }
  59294. EdgesRenderer.prototype._prepareRessources = function () {
  59295. if (this._lineShader) {
  59296. return;
  59297. }
  59298. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  59299. attributes: ["position", "normal"],
  59300. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  59301. });
  59302. this._lineShader.disableDepthWrite = true;
  59303. this._lineShader.backFaceCulling = false;
  59304. };
  59305. EdgesRenderer.prototype.dispose = function () {
  59306. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  59307. if (buffer) {
  59308. buffer.dispose();
  59309. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  59310. }
  59311. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  59312. if (buffer) {
  59313. buffer.dispose();
  59314. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  59315. }
  59316. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  59317. this._lineShader.dispose();
  59318. };
  59319. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  59320. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  59321. return 0;
  59322. }
  59323. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  59324. return 1;
  59325. }
  59326. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  59327. return 2;
  59328. }
  59329. return -1;
  59330. };
  59331. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  59332. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  59333. return 0;
  59334. }
  59335. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  59336. return 1;
  59337. }
  59338. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  59339. return 2;
  59340. }
  59341. return -1;
  59342. };
  59343. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  59344. var needToCreateLine;
  59345. if (edge === undefined) {
  59346. needToCreateLine = true;
  59347. }
  59348. else {
  59349. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  59350. needToCreateLine = dotProduct < this._epsilon;
  59351. }
  59352. if (needToCreateLine) {
  59353. var offset = this._linesPositions.length / 3;
  59354. var normal = p0.subtract(p1);
  59355. normal.normalize();
  59356. // Positions
  59357. this._linesPositions.push(p0.x);
  59358. this._linesPositions.push(p0.y);
  59359. this._linesPositions.push(p0.z);
  59360. this._linesPositions.push(p0.x);
  59361. this._linesPositions.push(p0.y);
  59362. this._linesPositions.push(p0.z);
  59363. this._linesPositions.push(p1.x);
  59364. this._linesPositions.push(p1.y);
  59365. this._linesPositions.push(p1.z);
  59366. this._linesPositions.push(p1.x);
  59367. this._linesPositions.push(p1.y);
  59368. this._linesPositions.push(p1.z);
  59369. // Normals
  59370. this._linesNormals.push(p1.x);
  59371. this._linesNormals.push(p1.y);
  59372. this._linesNormals.push(p1.z);
  59373. this._linesNormals.push(-1);
  59374. this._linesNormals.push(p1.x);
  59375. this._linesNormals.push(p1.y);
  59376. this._linesNormals.push(p1.z);
  59377. this._linesNormals.push(1);
  59378. this._linesNormals.push(p0.x);
  59379. this._linesNormals.push(p0.y);
  59380. this._linesNormals.push(p0.z);
  59381. this._linesNormals.push(-1);
  59382. this._linesNormals.push(p0.x);
  59383. this._linesNormals.push(p0.y);
  59384. this._linesNormals.push(p0.z);
  59385. this._linesNormals.push(1);
  59386. // Indices
  59387. this._linesIndices.push(offset);
  59388. this._linesIndices.push(offset + 1);
  59389. this._linesIndices.push(offset + 2);
  59390. this._linesIndices.push(offset);
  59391. this._linesIndices.push(offset + 2);
  59392. this._linesIndices.push(offset + 3);
  59393. }
  59394. };
  59395. EdgesRenderer.prototype._generateEdgesLines = function () {
  59396. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59397. var indices = this._source.getIndices();
  59398. // First let's find adjacencies
  59399. var adjacencies = new Array();
  59400. var faceNormals = new Array();
  59401. var index;
  59402. var faceAdjacencies;
  59403. // Prepare faces
  59404. for (index = 0; index < indices.length; index += 3) {
  59405. faceAdjacencies = new FaceAdjacencies();
  59406. var p0Index = indices[index];
  59407. var p1Index = indices[index + 1];
  59408. var p2Index = indices[index + 2];
  59409. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  59410. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  59411. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  59412. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  59413. faceNormal.normalize();
  59414. faceNormals.push(faceNormal);
  59415. adjacencies.push(faceAdjacencies);
  59416. }
  59417. // Scan
  59418. for (index = 0; index < adjacencies.length; index++) {
  59419. faceAdjacencies = adjacencies[index];
  59420. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  59421. var otherFaceAdjacencies = adjacencies[otherIndex];
  59422. if (faceAdjacencies.edgesConnectedCount === 3) {
  59423. break;
  59424. }
  59425. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  59426. continue;
  59427. }
  59428. var otherP0 = indices[otherIndex * 3];
  59429. var otherP1 = indices[otherIndex * 3 + 1];
  59430. var otherP2 = indices[otherIndex * 3 + 2];
  59431. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  59432. var otherEdgeIndex;
  59433. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  59434. continue;
  59435. }
  59436. switch (edgeIndex) {
  59437. case 0:
  59438. if (this._checkVerticesInsteadOfIndices) {
  59439. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  59440. }
  59441. else {
  59442. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  59443. }
  59444. break;
  59445. case 1:
  59446. if (this._checkVerticesInsteadOfIndices) {
  59447. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  59448. }
  59449. else {
  59450. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  59451. }
  59452. break;
  59453. case 2:
  59454. if (this._checkVerticesInsteadOfIndices) {
  59455. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  59456. }
  59457. else {
  59458. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  59459. }
  59460. break;
  59461. }
  59462. if (otherEdgeIndex === -1) {
  59463. continue;
  59464. }
  59465. faceAdjacencies.edges[edgeIndex] = otherIndex;
  59466. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  59467. faceAdjacencies.edgesConnectedCount++;
  59468. otherFaceAdjacencies.edgesConnectedCount++;
  59469. if (faceAdjacencies.edgesConnectedCount === 3) {
  59470. break;
  59471. }
  59472. }
  59473. }
  59474. }
  59475. // Create lines
  59476. for (index = 0; index < adjacencies.length; index++) {
  59477. // 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
  59478. var current = adjacencies[index];
  59479. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  59480. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  59481. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  59482. }
  59483. // Merge into a single mesh
  59484. var engine = this._source.getScene().getEngine();
  59485. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  59486. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  59487. this._ib = engine.createIndexBuffer(this._linesIndices);
  59488. this._indicesCount = this._linesIndices.length;
  59489. };
  59490. EdgesRenderer.prototype.render = function () {
  59491. if (!this._lineShader.isReady()) {
  59492. return;
  59493. }
  59494. var scene = this._source.getScene();
  59495. var engine = scene.getEngine();
  59496. this._lineShader._preBind();
  59497. // VBOs
  59498. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  59499. scene.resetCachedMaterial();
  59500. this._lineShader.setColor4("color", this._source.edgesColor);
  59501. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  59502. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  59503. }
  59504. else {
  59505. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  59506. }
  59507. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  59508. this._lineShader.bind(this._source.getWorldMatrix());
  59509. // Draw order
  59510. engine.draw(true, 0, this._indicesCount);
  59511. this._lineShader.unbind();
  59512. engine.setDepthWrite(true);
  59513. };
  59514. return EdgesRenderer;
  59515. }());
  59516. BABYLON.EdgesRenderer = EdgesRenderer;
  59517. })(BABYLON || (BABYLON = {}));
  59518. //# sourceMappingURL=babylon.edgesRenderer.js.map
  59519. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  59520. /// <reference path="..\Math\babylon.math.ts" />
  59521. var BABYLON;
  59522. (function (BABYLON) {
  59523. /**
  59524. * Special Glow Blur post process only blurring the alpha channel
  59525. * It enforces keeping the most luminous color in the color channel.
  59526. */
  59527. var GlowBlurPostProcess = (function (_super) {
  59528. __extends(GlowBlurPostProcess, _super);
  59529. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  59530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59531. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  59532. _this.direction = direction;
  59533. _this.blurWidth = blurWidth;
  59534. _this.onApplyObservable.add(function (effect) {
  59535. effect.setFloat2("screenSize", _this.width, _this.height);
  59536. effect.setVector2("direction", _this.direction);
  59537. effect.setFloat("blurWidth", _this.blurWidth);
  59538. });
  59539. return _this;
  59540. }
  59541. return GlowBlurPostProcess;
  59542. }(BABYLON.PostProcess));
  59543. /**
  59544. * The highlight layer Helps adding a glow effect around a mesh.
  59545. *
  59546. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  59547. * glowy meshes to your scene.
  59548. *
  59549. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  59550. */
  59551. var HighlightLayer = (function () {
  59552. /**
  59553. * Instantiates a new highlight Layer and references it to the scene..
  59554. * @param name The name of the layer
  59555. * @param scene The scene to use the layer in
  59556. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  59557. */
  59558. function HighlightLayer(name, scene, options) {
  59559. this.name = name;
  59560. this._vertexBuffers = {};
  59561. this._mainTextureDesiredSize = { width: 0, height: 0 };
  59562. this._meshes = {};
  59563. this._maxSize = 0;
  59564. this._shouldRender = false;
  59565. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  59566. this._excludedMeshes = {};
  59567. /**
  59568. * Specifies whether or not the inner glow is ACTIVE in the layer.
  59569. */
  59570. this.innerGlow = true;
  59571. /**
  59572. * Specifies whether or not the outer glow is ACTIVE in the layer.
  59573. */
  59574. this.outerGlow = true;
  59575. /**
  59576. * Specifies wether the highlight layer is enabled or not.
  59577. */
  59578. this.isEnabled = true;
  59579. /**
  59580. * An event triggered when the highlight layer has been disposed.
  59581. * @type {BABYLON.Observable}
  59582. */
  59583. this.onDisposeObservable = new BABYLON.Observable();
  59584. /**
  59585. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  59586. * @type {BABYLON.Observable}
  59587. */
  59588. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  59589. /**
  59590. * An event triggered when the highlight layer is being blurred.
  59591. * @type {BABYLON.Observable}
  59592. */
  59593. this.onBeforeBlurObservable = new BABYLON.Observable();
  59594. /**
  59595. * An event triggered when the highlight layer has been blurred.
  59596. * @type {BABYLON.Observable}
  59597. */
  59598. this.onAfterBlurObservable = new BABYLON.Observable();
  59599. /**
  59600. * An event triggered when the glowing blurred texture is being merged in the scene.
  59601. * @type {BABYLON.Observable}
  59602. */
  59603. this.onBeforeComposeObservable = new BABYLON.Observable();
  59604. /**
  59605. * An event triggered when the glowing blurred texture has been merged in the scene.
  59606. * @type {BABYLON.Observable}
  59607. */
  59608. this.onAfterComposeObservable = new BABYLON.Observable();
  59609. /**
  59610. * An event triggered when the highlight layer changes its size.
  59611. * @type {BABYLON.Observable}
  59612. */
  59613. this.onSizeChangedObservable = new BABYLON.Observable();
  59614. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59615. var engine = scene.getEngine();
  59616. this._engine = engine;
  59617. this._maxSize = this._engine.getCaps().maxTextureSize;
  59618. this._scene.highlightLayers.push(this);
  59619. // Warn on stencil.
  59620. if (!this._engine.isStencilEnable) {
  59621. 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 }");
  59622. }
  59623. // Adapt options
  59624. this._options = options || {
  59625. mainTextureRatio: 0.25,
  59626. blurTextureSizeRatio: 0.5,
  59627. blurHorizontalSize: 1,
  59628. blurVerticalSize: 1,
  59629. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  59630. };
  59631. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  59632. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  59633. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  59634. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  59635. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  59636. // VBO
  59637. var vertices = [];
  59638. vertices.push(1, 1);
  59639. vertices.push(-1, 1);
  59640. vertices.push(-1, -1);
  59641. vertices.push(1, -1);
  59642. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  59643. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  59644. // Indices
  59645. var indices = [];
  59646. indices.push(0);
  59647. indices.push(1);
  59648. indices.push(2);
  59649. indices.push(0);
  59650. indices.push(2);
  59651. indices.push(3);
  59652. this._indexBuffer = engine.createIndexBuffer(indices);
  59653. // Effect
  59654. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  59655. // Render target
  59656. this.setMainTextureSize();
  59657. // Create Textures and post processes
  59658. this.createTextureAndPostProcesses();
  59659. }
  59660. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  59661. /**
  59662. * Gets the horizontal size of the blur.
  59663. */
  59664. get: function () {
  59665. return this._horizontalBlurPostprocess.blurWidth;
  59666. },
  59667. /**
  59668. * Specifies the horizontal size of the blur.
  59669. */
  59670. set: function (value) {
  59671. this._horizontalBlurPostprocess.blurWidth = value;
  59672. },
  59673. enumerable: true,
  59674. configurable: true
  59675. });
  59676. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  59677. /**
  59678. * Gets the vertical size of the blur.
  59679. */
  59680. get: function () {
  59681. return this._verticalBlurPostprocess.blurWidth;
  59682. },
  59683. /**
  59684. * Specifies the vertical size of the blur.
  59685. */
  59686. set: function (value) {
  59687. this._verticalBlurPostprocess.blurWidth = value;
  59688. },
  59689. enumerable: true,
  59690. configurable: true
  59691. });
  59692. Object.defineProperty(HighlightLayer.prototype, "camera", {
  59693. /**
  59694. * Gets the camera attached to the layer.
  59695. */
  59696. get: function () {
  59697. return this._options.camera;
  59698. },
  59699. enumerable: true,
  59700. configurable: true
  59701. });
  59702. /**
  59703. * Creates the render target textures and post processes used in the highlight layer.
  59704. */
  59705. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  59706. var _this = this;
  59707. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  59708. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  59709. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  59710. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  59711. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  59712. width: this._mainTextureDesiredSize.width,
  59713. height: this._mainTextureDesiredSize.height
  59714. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59715. this._mainTexture.activeCamera = this._options.camera;
  59716. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59717. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59718. this._mainTexture.anisotropicFilteringLevel = 1;
  59719. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59720. this._mainTexture.renderParticles = false;
  59721. this._mainTexture.renderList = null;
  59722. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  59723. width: blurTextureWidth,
  59724. height: blurTextureHeight
  59725. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59726. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59727. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59728. this._blurTexture.anisotropicFilteringLevel = 16;
  59729. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59730. this._blurTexture.renderParticles = false;
  59731. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  59732. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  59733. effect.setTexture("textureSampler", _this._mainTexture);
  59734. });
  59735. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  59736. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  59737. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  59738. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  59739. });
  59740. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  59741. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  59742. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  59743. });
  59744. }
  59745. else {
  59746. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  59747. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  59748. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  59749. });
  59750. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  59751. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  59752. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  59753. });
  59754. }
  59755. this._mainTexture.onAfterUnbindObservable.add(function () {
  59756. _this.onBeforeBlurObservable.notifyObservers(_this);
  59757. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  59758. _this.onAfterBlurObservable.notifyObservers(_this);
  59759. });
  59760. // Custom render function
  59761. var renderSubMesh = function (subMesh) {
  59762. var mesh = subMesh.getRenderingMesh();
  59763. var scene = _this._scene;
  59764. var engine = scene.getEngine();
  59765. // Culling
  59766. engine.setState(subMesh.getMaterial().backFaceCulling);
  59767. // Managing instances
  59768. var batch = mesh._getInstancesRenderList(subMesh._id);
  59769. if (batch.mustReturn) {
  59770. return;
  59771. }
  59772. // Excluded Mesh
  59773. if (_this._excludedMeshes[mesh.uniqueId]) {
  59774. return;
  59775. }
  59776. ;
  59777. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59778. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  59779. var material = subMesh.getMaterial();
  59780. var emissiveTexture = null;
  59781. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  59782. emissiveTexture = material.emissiveTexture;
  59783. }
  59784. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  59785. engine.enableEffect(_this._glowMapGenerationEffect);
  59786. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  59787. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  59788. if (highlightLayerMesh) {
  59789. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  59790. }
  59791. else {
  59792. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  59793. }
  59794. // Alpha test
  59795. if (material && material.needAlphaTesting()) {
  59796. var alphaTexture = material.getAlphaTestTexture();
  59797. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  59798. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59799. }
  59800. // Glow emissive only
  59801. if (emissiveTexture) {
  59802. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  59803. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  59804. }
  59805. // Bones
  59806. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59807. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59808. }
  59809. // Draw
  59810. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  59811. }
  59812. else {
  59813. // Need to reset refresh rate of the shadowMap
  59814. _this._mainTexture.resetRefreshCounter();
  59815. }
  59816. };
  59817. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  59818. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  59819. var index;
  59820. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59821. renderSubMesh(opaqueSubMeshes.data[index]);
  59822. }
  59823. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59824. renderSubMesh(alphaTestSubMeshes.data[index]);
  59825. }
  59826. for (index = 0; index < transparentSubMeshes.length; index++) {
  59827. renderSubMesh(transparentSubMeshes.data[index]);
  59828. }
  59829. };
  59830. this._mainTexture.onClearObservable.add(function (engine) {
  59831. engine.clear(HighlightLayer.neutralColor, true, true, true);
  59832. });
  59833. };
  59834. /**
  59835. * Checks for the readiness of the element composing the layer.
  59836. * @param subMesh the mesh to check for
  59837. * @param useInstances specify wether or not to use instances to render the mesh
  59838. * @param emissiveTexture the associated emissive texture used to generate the glow
  59839. * @return true if ready otherwise, false
  59840. */
  59841. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  59842. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  59843. return false;
  59844. }
  59845. var defines = [];
  59846. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59847. var mesh = subMesh.getMesh();
  59848. var material = subMesh.getMaterial();
  59849. var uv1 = false;
  59850. var uv2 = false;
  59851. // Alpha test
  59852. if (material && material.needAlphaTesting()) {
  59853. var alphaTexture = material.getAlphaTestTexture();
  59854. if (alphaTexture) {
  59855. defines.push("#define ALPHATEST");
  59856. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  59857. alphaTexture.coordinatesIndex === 1) {
  59858. defines.push("#define DIFFUSEUV2");
  59859. uv2 = true;
  59860. }
  59861. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59862. defines.push("#define DIFFUSEUV1");
  59863. uv1 = true;
  59864. }
  59865. }
  59866. }
  59867. // Emissive
  59868. if (emissiveTexture) {
  59869. defines.push("#define EMISSIVE");
  59870. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  59871. emissiveTexture.coordinatesIndex === 1) {
  59872. defines.push("#define EMISSIVEUV2");
  59873. uv2 = true;
  59874. }
  59875. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59876. defines.push("#define EMISSIVEUV1");
  59877. uv1 = true;
  59878. }
  59879. }
  59880. if (uv1) {
  59881. attribs.push(BABYLON.VertexBuffer.UVKind);
  59882. defines.push("#define UV1");
  59883. }
  59884. if (uv2) {
  59885. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59886. defines.push("#define UV2");
  59887. }
  59888. // Bones
  59889. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59890. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59891. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59892. if (mesh.numBoneInfluencers > 4) {
  59893. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59894. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59895. }
  59896. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59897. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59898. }
  59899. else {
  59900. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59901. }
  59902. // Instances
  59903. if (useInstances) {
  59904. defines.push("#define INSTANCES");
  59905. attribs.push("world0");
  59906. attribs.push("world1");
  59907. attribs.push("world2");
  59908. attribs.push("world3");
  59909. }
  59910. // Get correct effect
  59911. var join = defines.join("\n");
  59912. if (this._cachedDefines !== join) {
  59913. this._cachedDefines = join;
  59914. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  59915. }
  59916. return this._glowMapGenerationEffect.isReady();
  59917. };
  59918. /**
  59919. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  59920. */
  59921. HighlightLayer.prototype.render = function () {
  59922. var currentEffect = this._glowMapMergeEffect;
  59923. // Check
  59924. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  59925. return;
  59926. var engine = this._scene.getEngine();
  59927. this.onBeforeComposeObservable.notifyObservers(this);
  59928. // Render
  59929. engine.enableEffect(currentEffect);
  59930. engine.setState(false);
  59931. // Cache
  59932. var previousStencilBuffer = engine.getStencilBuffer();
  59933. var previousStencilFunction = engine.getStencilFunction();
  59934. var previousStencilMask = engine.getStencilMask();
  59935. var previousAlphaMode = engine.getAlphaMode();
  59936. // Texture
  59937. currentEffect.setTexture("textureSampler", this._blurTexture);
  59938. // VBOs
  59939. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  59940. // Draw order
  59941. engine.setAlphaMode(this._options.alphaBlendingMode);
  59942. engine.setStencilMask(0x00);
  59943. engine.setStencilBuffer(true);
  59944. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  59945. if (this.outerGlow) {
  59946. currentEffect.setFloat("offset", 0);
  59947. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  59948. engine.draw(true, 0, 6);
  59949. }
  59950. if (this.innerGlow) {
  59951. currentEffect.setFloat("offset", 1);
  59952. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  59953. engine.draw(true, 0, 6);
  59954. }
  59955. // Restore Cache
  59956. engine.setStencilFunction(previousStencilFunction);
  59957. engine.setStencilMask(previousStencilMask);
  59958. engine.setAlphaMode(previousAlphaMode);
  59959. engine.setStencilBuffer(previousStencilBuffer);
  59960. this.onAfterComposeObservable.notifyObservers(this);
  59961. // Handle size changes.
  59962. var size = this._mainTexture.getSize();
  59963. this.setMainTextureSize();
  59964. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  59965. // Recreate RTT and post processes on size change.
  59966. this.onSizeChangedObservable.notifyObservers(this);
  59967. this.disposeTextureAndPostProcesses();
  59968. this.createTextureAndPostProcesses();
  59969. }
  59970. };
  59971. /**
  59972. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  59973. * @param mesh The mesh to exclude from the highlight layer
  59974. */
  59975. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  59976. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  59977. if (!meshExcluded) {
  59978. this._excludedMeshes[mesh.uniqueId] = {
  59979. mesh: mesh,
  59980. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  59981. mesh.getEngine().setStencilBuffer(false);
  59982. }),
  59983. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  59984. mesh.getEngine().setStencilBuffer(true);
  59985. }),
  59986. };
  59987. }
  59988. };
  59989. /**
  59990. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  59991. * @param mesh The mesh to highlight
  59992. */
  59993. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  59994. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  59995. if (meshExcluded) {
  59996. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  59997. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  59998. }
  59999. this._excludedMeshes[mesh.uniqueId] = undefined;
  60000. };
  60001. /**
  60002. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  60003. * @param mesh The mesh to highlight
  60004. * @param color The color of the highlight
  60005. * @param glowEmissiveOnly Extract the glow from the emissive texture
  60006. */
  60007. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  60008. var _this = this;
  60009. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  60010. var meshHighlight = this._meshes[mesh.uniqueId];
  60011. if (meshHighlight) {
  60012. meshHighlight.color = color;
  60013. }
  60014. else {
  60015. this._meshes[mesh.uniqueId] = {
  60016. mesh: mesh,
  60017. color: color,
  60018. // Lambda required for capture due to Observable this context
  60019. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  60020. if (_this._excludedMeshes[mesh.uniqueId]) {
  60021. _this.defaultStencilReference(mesh);
  60022. }
  60023. else {
  60024. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  60025. }
  60026. }),
  60027. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  60028. glowEmissiveOnly: glowEmissiveOnly
  60029. };
  60030. }
  60031. this._shouldRender = true;
  60032. };
  60033. /**
  60034. * Remove a mesh from the highlight layer in order to make it stop glowing.
  60035. * @param mesh The mesh to highlight
  60036. */
  60037. HighlightLayer.prototype.removeMesh = function (mesh) {
  60038. var meshHighlight = this._meshes[mesh.uniqueId];
  60039. if (meshHighlight) {
  60040. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  60041. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  60042. }
  60043. this._meshes[mesh.uniqueId] = undefined;
  60044. this._shouldRender = false;
  60045. for (var meshHighlightToCheck in this._meshes) {
  60046. if (meshHighlightToCheck) {
  60047. this._shouldRender = true;
  60048. break;
  60049. }
  60050. }
  60051. };
  60052. /**
  60053. * Returns true if the layer contains information to display, otherwise false.
  60054. */
  60055. HighlightLayer.prototype.shouldRender = function () {
  60056. return this.isEnabled && this._shouldRender;
  60057. };
  60058. /**
  60059. * Sets the main texture desired size which is the closest power of two
  60060. * of the engine canvas size.
  60061. */
  60062. HighlightLayer.prototype.setMainTextureSize = function () {
  60063. if (this._options.mainTextureFixedSize) {
  60064. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  60065. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  60066. }
  60067. else {
  60068. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  60069. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  60070. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  60071. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  60072. }
  60073. };
  60074. /**
  60075. * Force the stencil to the normal expected value for none glowing parts
  60076. */
  60077. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  60078. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  60079. };
  60080. /**
  60081. * Dispose only the render target textures and post process.
  60082. */
  60083. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  60084. this._blurTexture.dispose();
  60085. this._mainTexture.dispose();
  60086. this._downSamplePostprocess.dispose();
  60087. this._horizontalBlurPostprocess.dispose();
  60088. this._verticalBlurPostprocess.dispose();
  60089. };
  60090. /**
  60091. * Dispose the highlight layer and free resources.
  60092. */
  60093. HighlightLayer.prototype.dispose = function () {
  60094. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60095. if (vertexBuffer) {
  60096. vertexBuffer.dispose();
  60097. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60098. }
  60099. if (this._indexBuffer) {
  60100. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60101. this._indexBuffer = null;
  60102. }
  60103. // Clean textures and post processes
  60104. this.disposeTextureAndPostProcesses();
  60105. // Clean mesh references
  60106. for (var id in this._meshes) {
  60107. var meshHighlight = this._meshes[id];
  60108. if (meshHighlight && meshHighlight.mesh) {
  60109. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  60110. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  60111. }
  60112. }
  60113. this._meshes = null;
  60114. for (var id in this._excludedMeshes) {
  60115. var meshHighlight = this._excludedMeshes[id];
  60116. if (meshHighlight) {
  60117. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  60118. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  60119. }
  60120. }
  60121. this._excludedMeshes = null;
  60122. // Remove from scene
  60123. var index = this._scene.highlightLayers.indexOf(this, 0);
  60124. if (index > -1) {
  60125. this._scene.highlightLayers.splice(index, 1);
  60126. }
  60127. // Callback
  60128. this.onDisposeObservable.notifyObservers(this);
  60129. this.onDisposeObservable.clear();
  60130. this.onBeforeRenderMainTextureObservable.clear();
  60131. this.onBeforeBlurObservable.clear();
  60132. this.onBeforeComposeObservable.clear();
  60133. this.onAfterComposeObservable.clear();
  60134. this.onSizeChangedObservable.clear();
  60135. };
  60136. return HighlightLayer;
  60137. }());
  60138. /**
  60139. * The neutral color used during the preparation of the glow effect.
  60140. * This is black by default as the blend operation is a blend operation.
  60141. */
  60142. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  60143. /**
  60144. * Stencil value used for glowing meshes.
  60145. */
  60146. HighlightLayer.glowingMeshStencilReference = 0x02;
  60147. /**
  60148. * Stencil value used for the other meshes in the scene.
  60149. */
  60150. HighlightLayer.normalMeshStencilReference = 0x01;
  60151. BABYLON.HighlightLayer = HighlightLayer;
  60152. })(BABYLON || (BABYLON = {}));
  60153. //# sourceMappingURL=babylon.highlightlayer.js.map
  60154. var BABYLON;
  60155. (function (BABYLON) {
  60156. var MeshAssetTask = (function () {
  60157. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  60158. this.name = name;
  60159. this.meshesNames = meshesNames;
  60160. this.rootUrl = rootUrl;
  60161. this.sceneFilename = sceneFilename;
  60162. this.isCompleted = false;
  60163. }
  60164. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60165. var _this = this;
  60166. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60167. _this.loadedMeshes = meshes;
  60168. _this.loadedParticleSystems = particleSystems;
  60169. _this.loadedSkeletons = skeletons;
  60170. _this.isCompleted = true;
  60171. if (_this.onSuccess) {
  60172. _this.onSuccess(_this);
  60173. }
  60174. onSuccess();
  60175. }, null, function () {
  60176. if (_this.onError) {
  60177. _this.onError(_this);
  60178. }
  60179. onError();
  60180. });
  60181. };
  60182. return MeshAssetTask;
  60183. }());
  60184. BABYLON.MeshAssetTask = MeshAssetTask;
  60185. var TextFileAssetTask = (function () {
  60186. function TextFileAssetTask(name, url) {
  60187. this.name = name;
  60188. this.url = url;
  60189. this.isCompleted = false;
  60190. }
  60191. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60192. var _this = this;
  60193. BABYLON.Tools.LoadFile(this.url, function (data) {
  60194. _this.text = data;
  60195. _this.isCompleted = true;
  60196. if (_this.onSuccess) {
  60197. _this.onSuccess(_this);
  60198. }
  60199. onSuccess();
  60200. }, null, scene.database, false, function () {
  60201. if (_this.onError) {
  60202. _this.onError(_this);
  60203. }
  60204. onError();
  60205. });
  60206. };
  60207. return TextFileAssetTask;
  60208. }());
  60209. BABYLON.TextFileAssetTask = TextFileAssetTask;
  60210. var BinaryFileAssetTask = (function () {
  60211. function BinaryFileAssetTask(name, url) {
  60212. this.name = name;
  60213. this.url = url;
  60214. this.isCompleted = false;
  60215. }
  60216. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60217. var _this = this;
  60218. BABYLON.Tools.LoadFile(this.url, function (data) {
  60219. _this.data = data;
  60220. _this.isCompleted = true;
  60221. if (_this.onSuccess) {
  60222. _this.onSuccess(_this);
  60223. }
  60224. onSuccess();
  60225. }, null, scene.database, true, function () {
  60226. if (_this.onError) {
  60227. _this.onError(_this);
  60228. }
  60229. onError();
  60230. });
  60231. };
  60232. return BinaryFileAssetTask;
  60233. }());
  60234. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  60235. var ImageAssetTask = (function () {
  60236. function ImageAssetTask(name, url) {
  60237. this.name = name;
  60238. this.url = url;
  60239. this.isCompleted = false;
  60240. }
  60241. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60242. var _this = this;
  60243. var img = new Image();
  60244. BABYLON.Tools.SetCorsBehavior(this.url, img);
  60245. img.onload = function () {
  60246. _this.image = img;
  60247. _this.isCompleted = true;
  60248. if (_this.onSuccess) {
  60249. _this.onSuccess(_this);
  60250. }
  60251. onSuccess();
  60252. };
  60253. img.onerror = function () {
  60254. if (_this.onError) {
  60255. _this.onError(_this);
  60256. }
  60257. onError();
  60258. };
  60259. img.src = this.url;
  60260. };
  60261. return ImageAssetTask;
  60262. }());
  60263. BABYLON.ImageAssetTask = ImageAssetTask;
  60264. var TextureAssetTask = (function () {
  60265. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  60266. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60267. this.name = name;
  60268. this.url = url;
  60269. this.noMipmap = noMipmap;
  60270. this.invertY = invertY;
  60271. this.samplingMode = samplingMode;
  60272. this.isCompleted = false;
  60273. }
  60274. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60275. var _this = this;
  60276. var onload = function () {
  60277. _this.isCompleted = true;
  60278. if (_this.onSuccess) {
  60279. _this.onSuccess(_this);
  60280. }
  60281. onSuccess();
  60282. };
  60283. var onerror = function () {
  60284. if (_this.onError) {
  60285. _this.onError(_this);
  60286. }
  60287. onError();
  60288. };
  60289. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  60290. };
  60291. return TextureAssetTask;
  60292. }());
  60293. BABYLON.TextureAssetTask = TextureAssetTask;
  60294. var CubeTextureAssetTask = (function () {
  60295. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  60296. this.name = name;
  60297. this.url = url;
  60298. this.extensions = extensions;
  60299. this.noMipmap = noMipmap;
  60300. this.files = files;
  60301. this.isCompleted = false;
  60302. }
  60303. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60304. var _this = this;
  60305. var onload = function () {
  60306. _this.isCompleted = true;
  60307. if (_this.onSuccess) {
  60308. _this.onSuccess(_this);
  60309. }
  60310. onSuccess();
  60311. };
  60312. var onerror = function () {
  60313. if (_this.onError) {
  60314. _this.onError(_this);
  60315. }
  60316. onError();
  60317. };
  60318. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  60319. };
  60320. return CubeTextureAssetTask;
  60321. }());
  60322. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  60323. var HDRCubeTextureAssetTask = (function () {
  60324. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  60325. if (noMipmap === void 0) { noMipmap = false; }
  60326. if (generateHarmonics === void 0) { generateHarmonics = true; }
  60327. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  60328. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  60329. this.name = name;
  60330. this.url = url;
  60331. this.size = size;
  60332. this.noMipmap = noMipmap;
  60333. this.generateHarmonics = generateHarmonics;
  60334. this.useInGammaSpace = useInGammaSpace;
  60335. this.usePMREMGenerator = usePMREMGenerator;
  60336. this.isCompleted = false;
  60337. }
  60338. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  60339. var _this = this;
  60340. var onload = function () {
  60341. _this.isCompleted = true;
  60342. if (_this.onSuccess) {
  60343. _this.onSuccess(_this);
  60344. }
  60345. onSuccess();
  60346. };
  60347. var onerror = function () {
  60348. if (_this.onError) {
  60349. _this.onError(_this);
  60350. }
  60351. onError();
  60352. };
  60353. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  60354. };
  60355. return HDRCubeTextureAssetTask;
  60356. }());
  60357. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  60358. var AssetsManager = (function () {
  60359. function AssetsManager(scene) {
  60360. this.tasks = new Array();
  60361. this.waitingTasksCount = 0;
  60362. this.useDefaultLoadingScreen = true;
  60363. this._scene = scene;
  60364. }
  60365. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  60366. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  60367. this.tasks.push(task);
  60368. return task;
  60369. };
  60370. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  60371. var task = new TextFileAssetTask(taskName, url);
  60372. this.tasks.push(task);
  60373. return task;
  60374. };
  60375. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  60376. var task = new BinaryFileAssetTask(taskName, url);
  60377. this.tasks.push(task);
  60378. return task;
  60379. };
  60380. AssetsManager.prototype.addImageTask = function (taskName, url) {
  60381. var task = new ImageAssetTask(taskName, url);
  60382. this.tasks.push(task);
  60383. return task;
  60384. };
  60385. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  60386. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60387. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  60388. this.tasks.push(task);
  60389. return task;
  60390. };
  60391. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  60392. this.waitingTasksCount--;
  60393. if (this.waitingTasksCount === 0) {
  60394. if (this.onFinish) {
  60395. this.onFinish(this.tasks);
  60396. }
  60397. this._scene.getEngine().hideLoadingUI();
  60398. }
  60399. };
  60400. AssetsManager.prototype._runTask = function (task) {
  60401. var _this = this;
  60402. task.run(this._scene, function () {
  60403. if (_this.onTaskSuccess) {
  60404. _this.onTaskSuccess(task);
  60405. }
  60406. _this._decreaseWaitingTasksCount();
  60407. }, function () {
  60408. if (_this.onTaskError) {
  60409. _this.onTaskError(task);
  60410. }
  60411. _this._decreaseWaitingTasksCount();
  60412. });
  60413. };
  60414. AssetsManager.prototype.reset = function () {
  60415. this.tasks = new Array();
  60416. return this;
  60417. };
  60418. AssetsManager.prototype.load = function () {
  60419. this.waitingTasksCount = this.tasks.length;
  60420. if (this.waitingTasksCount === 0) {
  60421. if (this.onFinish) {
  60422. this.onFinish(this.tasks);
  60423. }
  60424. return this;
  60425. }
  60426. if (this.useDefaultLoadingScreen) {
  60427. this._scene.getEngine().displayLoadingUI();
  60428. }
  60429. for (var index = 0; index < this.tasks.length; index++) {
  60430. var task = this.tasks[index];
  60431. this._runTask(task);
  60432. }
  60433. return this;
  60434. };
  60435. return AssetsManager;
  60436. }());
  60437. BABYLON.AssetsManager = AssetsManager;
  60438. })(BABYLON || (BABYLON = {}));
  60439. //# sourceMappingURL=babylon.assetsManager.js.map
  60440. var BABYLON;
  60441. (function (BABYLON) {
  60442. var MapTexture = (function (_super) {
  60443. __extends(MapTexture, _super);
  60444. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  60445. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60446. if (useMipMap === void 0) { useMipMap = false; }
  60447. if (margin === void 0) { margin = 0; }
  60448. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  60449. _this.name = name;
  60450. _this._size = size;
  60451. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60452. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60453. // Create the rectPackMap that will allocate portion of the texture
  60454. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  60455. // Create the texture that will store the content
  60456. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  60457. return _this;
  60458. }
  60459. /**
  60460. * Allocate a rectangle of a given size in the texture map
  60461. * @param size the size of the rectangle to allocation
  60462. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  60463. */
  60464. MapTexture.prototype.allocateRect = function (size) {
  60465. return this._rectPackingMap.addRect(size);
  60466. };
  60467. /**
  60468. * Free a given rectangle from the texture map
  60469. * @param rectInfo the instance corresponding to the rect to free.
  60470. */
  60471. MapTexture.prototype.freeRect = function (rectInfo) {
  60472. if (rectInfo) {
  60473. rectInfo.freeContent();
  60474. }
  60475. };
  60476. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  60477. /**
  60478. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  60479. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  60480. * @returns {}
  60481. */
  60482. get: function () {
  60483. return this._rectPackingMap.freeSpace;
  60484. },
  60485. enumerable: true,
  60486. configurable: true
  60487. });
  60488. /**
  60489. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  60490. * 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.
  60491. * Don't forget to call unbindTexture when you're done rendering
  60492. * @param rect the zone to render to
  60493. * @param clear true to clear the portion's color/depth data
  60494. */
  60495. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  60496. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  60497. };
  60498. /**
  60499. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  60500. * 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.
  60501. * Don't forget to call unbindTexture when you're done rendering
  60502. * @param pos the position into the texture
  60503. * @param size the portion to fit the clip space to
  60504. * @param clear true to clear the portion's color/depth data
  60505. */
  60506. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  60507. var engine = this.getScene().getEngine();
  60508. engine.bindFramebuffer(this._texture);
  60509. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  60510. if (clear) {
  60511. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  60512. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  60513. }
  60514. };
  60515. /**
  60516. * Unbind the texture map from the rendering engine.
  60517. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  60518. * @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.
  60519. */
  60520. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  60521. // Dump ?
  60522. if (dumpForDebug) {
  60523. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  60524. }
  60525. var engine = this.getScene().getEngine();
  60526. if (this._replacedViewport) {
  60527. engine.setViewport(this._replacedViewport);
  60528. this._replacedViewport = null;
  60529. }
  60530. engine.unBindFramebuffer(this._texture);
  60531. };
  60532. Object.defineProperty(MapTexture.prototype, "canRescale", {
  60533. get: function () {
  60534. return false;
  60535. },
  60536. enumerable: true,
  60537. configurable: true
  60538. });
  60539. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  60540. // Anyway, there's not much point to use this method for this kind of texture I guess
  60541. MapTexture.prototype.clone = function () {
  60542. return null;
  60543. };
  60544. return MapTexture;
  60545. }(BABYLON.Texture));
  60546. BABYLON.MapTexture = MapTexture;
  60547. })(BABYLON || (BABYLON = {}));
  60548. //# sourceMappingURL=babylon.mapTexture.js.map
  60549. var BABYLON;
  60550. (function (BABYLON) {
  60551. /**
  60552. * This class describe a rectangle that were added to the map.
  60553. * You have access to its coordinates either in pixel or normalized (UV)
  60554. */
  60555. var PackedRect = (function () {
  60556. function PackedRect(root, parent, pos, size) {
  60557. this._pos = pos;
  60558. this._size = size;
  60559. this._root = root;
  60560. this._parent = parent;
  60561. this._contentSize = null;
  60562. this._bottomNode = null;
  60563. this._leftNode = null;
  60564. this._initialSize = null;
  60565. this._rightNode = null;
  60566. }
  60567. Object.defineProperty(PackedRect.prototype, "pos", {
  60568. /**
  60569. * @returns the position of this node into the map
  60570. */
  60571. get: function () {
  60572. return this._pos;
  60573. },
  60574. enumerable: true,
  60575. configurable: true
  60576. });
  60577. Object.defineProperty(PackedRect.prototype, "contentSize", {
  60578. /**
  60579. * @returns the size of the rectangle this node handles
  60580. */
  60581. get: function () {
  60582. return this._contentSize;
  60583. },
  60584. enumerable: true,
  60585. configurable: true
  60586. });
  60587. /**
  60588. * Retrieve the inner position (considering the margin) and stores it into the res object
  60589. * @param res must be a valid Vector2 that will contain the inner position after this call
  60590. */
  60591. PackedRect.prototype.getInnerPosToRef = function (res) {
  60592. var m = this._root._margin;
  60593. res.x = this._pos.x + m;
  60594. res.y = this._pos.y + m;
  60595. };
  60596. /**
  60597. * Retrieve the inner size (considering the margin) and stores it into the res object
  60598. * @param res must be a valid Size that will contain the inner size after this call
  60599. */
  60600. PackedRect.prototype.getInnerSizeToRef = function (res) {
  60601. var m = this._root._margin;
  60602. res.width = this._contentSize.width - (m * 2);
  60603. res.height = this._contentSize.height - (m * 2);
  60604. };
  60605. Object.defineProperty(PackedRect.prototype, "UVs", {
  60606. /**
  60607. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  60608. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  60609. */
  60610. get: function () {
  60611. if (!this._contentSize) {
  60612. throw new Error("Can't compute UVs for this object because it's nor allocated");
  60613. }
  60614. return this.getUVsForCustomSize(this._contentSize);
  60615. },
  60616. enumerable: true,
  60617. configurable: true
  60618. });
  60619. /**
  60620. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  60621. * and then using only a part of the PackRect.
  60622. * This method will return the UVs for this part by given the custom size of what you really use
  60623. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  60624. */
  60625. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  60626. var mainWidth = this._root._size.width;
  60627. var mainHeight = this._root._size.height;
  60628. var margin = this._root._margin;
  60629. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  60630. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  60631. var uvs = new Array();
  60632. uvs.push(topLeft);
  60633. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  60634. uvs.push(rightBottom);
  60635. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  60636. return uvs;
  60637. };
  60638. /**
  60639. * Free this rectangle from the map.
  60640. * Call this method when you no longer need the rectangle to be in the map.
  60641. */
  60642. PackedRect.prototype.freeContent = function () {
  60643. if (!this.contentSize) {
  60644. return;
  60645. }
  60646. this._contentSize = null;
  60647. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  60648. this.attemptDefrag();
  60649. };
  60650. Object.defineProperty(PackedRect.prototype, "isUsed", {
  60651. get: function () {
  60652. return this._contentSize != null || this._leftNode != null;
  60653. },
  60654. enumerable: true,
  60655. configurable: true
  60656. });
  60657. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  60658. var node = this.findNode(contentSize);
  60659. // Not enough space...
  60660. if (!node) {
  60661. return null;
  60662. }
  60663. node.splitNode(contentSize);
  60664. return node;
  60665. };
  60666. PackedRect.prototype.findNode = function (size) {
  60667. var resNode = null;
  60668. var margin = this._root._margin * 2;
  60669. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  60670. if (this.isUsed) {
  60671. if (this._leftNode) {
  60672. resNode = this._leftNode.findNode(size);
  60673. }
  60674. if (!resNode && this._rightNode) {
  60675. resNode = this._rightNode.findNode(size);
  60676. }
  60677. if (!resNode && this._bottomNode) {
  60678. resNode = this._bottomNode.findNode(size);
  60679. }
  60680. }
  60681. else if (this._initialSize) {
  60682. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  60683. resNode = this;
  60684. }
  60685. else {
  60686. return null;
  60687. }
  60688. }
  60689. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  60690. resNode = this;
  60691. }
  60692. return resNode;
  60693. };
  60694. PackedRect.prototype.splitNode = function (contentSize) {
  60695. var cs = PackedRect.TpsSize;
  60696. var margin = this._root._margin * 2;
  60697. cs.copyFrom(contentSize);
  60698. cs.width += margin;
  60699. cs.height += margin;
  60700. // 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)
  60701. if (!this._contentSize && this._initialSize) {
  60702. this._contentSize = cs.clone();
  60703. 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));
  60704. return this._leftNode.splitNode(contentSize);
  60705. }
  60706. else {
  60707. this._contentSize = cs.clone();
  60708. this._initialSize = cs.clone();
  60709. if (cs.width !== this._size.width) {
  60710. 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));
  60711. }
  60712. if (cs.height !== this._size.height) {
  60713. 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));
  60714. }
  60715. return this;
  60716. }
  60717. };
  60718. PackedRect.prototype.attemptDefrag = function () {
  60719. if (!this.isUsed && this.isRecursiveFree) {
  60720. this.clearNode();
  60721. if (this._parent) {
  60722. this._parent.attemptDefrag();
  60723. }
  60724. }
  60725. };
  60726. PackedRect.prototype.clearNode = function () {
  60727. this._initialSize = null;
  60728. this._rightNode = null;
  60729. this._bottomNode = null;
  60730. };
  60731. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  60732. get: function () {
  60733. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  60734. },
  60735. enumerable: true,
  60736. configurable: true
  60737. });
  60738. PackedRect.prototype.evalFreeSize = function (size) {
  60739. var levelSize = 0;
  60740. if (!this.isUsed) {
  60741. var margin = this._root._margin;
  60742. var is = this._initialSize;
  60743. if (is) {
  60744. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  60745. }
  60746. else {
  60747. var size_1 = this._size;
  60748. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  60749. }
  60750. }
  60751. if (this._rightNode) {
  60752. levelSize += this._rightNode.evalFreeSize(0);
  60753. }
  60754. if (this._bottomNode) {
  60755. levelSize += this._bottomNode.evalFreeSize(0);
  60756. }
  60757. return levelSize + size;
  60758. };
  60759. return PackedRect;
  60760. }());
  60761. PackedRect.TpsSize = BABYLON.Size.Zero();
  60762. BABYLON.PackedRect = PackedRect;
  60763. /**
  60764. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  60765. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  60766. * 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.
  60767. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  60768. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  60769. */
  60770. var RectPackingMap = (function (_super) {
  60771. __extends(RectPackingMap, _super);
  60772. /**
  60773. * Create an instance of the object with a dimension using the given size
  60774. * @param size The dimension of the rectangle that will contain all the sub ones.
  60775. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  60776. */
  60777. function RectPackingMap(size, margin) {
  60778. if (margin === void 0) { margin = 0; }
  60779. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  60780. _this._margin = margin;
  60781. _this._root = _this;
  60782. return _this;
  60783. }
  60784. /**
  60785. * Add a rectangle, finding the best location to store it into the map
  60786. * @param size the dimension of the rectangle to store
  60787. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  60788. */
  60789. RectPackingMap.prototype.addRect = function (size) {
  60790. var node = this.findAndSplitNode(size);
  60791. return node;
  60792. };
  60793. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  60794. /**
  60795. * Return the current space free normalized between [0;1]
  60796. * @returns {}
  60797. */
  60798. get: function () {
  60799. var freeSize = 0;
  60800. freeSize = this.evalFreeSize(freeSize);
  60801. return freeSize / (this._size.width * this._size.height);
  60802. },
  60803. enumerable: true,
  60804. configurable: true
  60805. });
  60806. return RectPackingMap;
  60807. }(PackedRect));
  60808. BABYLON.RectPackingMap = RectPackingMap;
  60809. })(BABYLON || (BABYLON = {}));
  60810. //# sourceMappingURL=babylon.rectPackingMap.js.map
  60811. var BABYLON;
  60812. (function (BABYLON) {
  60813. var DynamicFloatArrayElementInfo = (function () {
  60814. function DynamicFloatArrayElementInfo() {
  60815. }
  60816. return DynamicFloatArrayElementInfo;
  60817. }());
  60818. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  60819. /**
  60820. * 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.
  60821. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  60822. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  60823. * 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.
  60824. * 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.
  60825. * 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".
  60826. */
  60827. var DynamicFloatArray = (function () {
  60828. /**
  60829. * Construct an instance of the dynamic float array
  60830. * @param stride size of one element in float (i.e. not bytes!)
  60831. * @param initialElementCount the number of available entries at construction
  60832. */
  60833. function DynamicFloatArray(stride, initialElementCount) {
  60834. this.compareValueOffset = null;
  60835. this.sortingAscending = true;
  60836. this._stride = stride;
  60837. this.buffer = new Float32Array(stride * initialElementCount);
  60838. this._lastUsed = 0;
  60839. this._firstFree = 0;
  60840. this._allEntries = new Array(initialElementCount);
  60841. this._freeEntries = new Array(initialElementCount);
  60842. for (var i = 0; i < initialElementCount; i++) {
  60843. var element = new DynamicFloatArrayElementInfo();
  60844. element.offset = i * stride;
  60845. this._allEntries[i] = element;
  60846. this._freeEntries[initialElementCount - i - 1] = element;
  60847. }
  60848. }
  60849. /**
  60850. * Allocate an element in the array.
  60851. * @return the element info instance that contains the offset into the main buffer of the element's location.
  60852. * Beware, this offset may change when you call pack()
  60853. */
  60854. DynamicFloatArray.prototype.allocElement = function () {
  60855. if (this._freeEntries.length === 0) {
  60856. this._growBuffer();
  60857. }
  60858. var el = this._freeEntries.pop();
  60859. this._lastUsed = Math.max(el.offset, this._lastUsed);
  60860. if (el.offset === this._firstFree) {
  60861. if (this._freeEntries.length > 0) {
  60862. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  60863. }
  60864. else {
  60865. this._firstFree += this._stride;
  60866. }
  60867. }
  60868. return el;
  60869. };
  60870. /**
  60871. * Free the element corresponding to the given element info
  60872. * @param elInfo the element that describe the allocated element
  60873. */
  60874. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  60875. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  60876. this._freeEntries.push(elInfo);
  60877. };
  60878. /**
  60879. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  60880. * 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().
  60881. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  60882. */
  60883. DynamicFloatArray.prototype.pack = function () {
  60884. // no free slot? no need to pack
  60885. if (this._freeEntries.length === 0) {
  60886. return this.buffer;
  60887. }
  60888. // If the buffer is already packed the last used will always be lower than the first free
  60889. // 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.
  60890. if (this._lastUsed < this._firstFree) {
  60891. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  60892. return elementsBuffer_1;
  60893. }
  60894. var s = this._stride;
  60895. // 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
  60896. var lastFree = new DynamicFloatArrayElementInfo();
  60897. lastFree.offset = this.totalElementCount * s;
  60898. this._freeEntries.push(lastFree);
  60899. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  60900. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  60901. var firstFreeSlotOffset = sortedFree[0].offset;
  60902. var freeZoneSize = 1;
  60903. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  60904. var prevOffset = sortedFree[0].offset;
  60905. for (var i = 1; i < sortedFree.length; i++) {
  60906. // 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
  60907. if (firstFreeSlotOffset >= occupiedZoneSize) {
  60908. break;
  60909. }
  60910. var curFree = sortedFree[i];
  60911. var curOffset = curFree.offset;
  60912. // Compute the distance between this offset and the previous
  60913. var distance = curOffset - prevOffset;
  60914. // If the distance is the stride size, they are adjacent, it good, move to the next
  60915. if (distance === s) {
  60916. // Free zone is one element bigger
  60917. ++freeZoneSize;
  60918. // as we're about to iterate to the next, the cur becomes the previous...
  60919. prevOffset = curOffset;
  60920. continue;
  60921. }
  60922. // Distance is bigger, which means there's x element between the previous free and this one
  60923. var usedRange = (distance / s) - 1;
  60924. // Two cases the free zone is smaller than the data to move or bigger
  60925. // Copy what can fit in the free zone
  60926. var curMoveOffset = curOffset - s;
  60927. var copyCount = Math.min(freeZoneSize, usedRange);
  60928. for (var j = 0; j < copyCount; j++) {
  60929. var freeI = firstFreeSlotOffset / s;
  60930. var curI = curMoveOffset / s;
  60931. var moveEl = sortedAll[curI];
  60932. this._moveElement(moveEl, firstFreeSlotOffset);
  60933. var replacedEl = sortedAll[freeI];
  60934. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  60935. replacedEl.offset = curMoveOffset;
  60936. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  60937. sortedAll[freeI] = moveEl;
  60938. sortedAll[curI] = replacedEl;
  60939. curMoveOffset -= s;
  60940. firstFreeSlotOffset += s;
  60941. }
  60942. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  60943. if (freeZoneSize <= usedRange) {
  60944. firstFreeSlotOffset = curMoveOffset + s;
  60945. freeZoneSize = 1 + copyCount;
  60946. }
  60947. else {
  60948. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  60949. }
  60950. // as we're about to iterate to the next, the cur becomes the previous...
  60951. prevOffset = curOffset;
  60952. }
  60953. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  60954. this._lastUsed = firstFreeSlotOffset - s;
  60955. this._firstFree = firstFreeSlotOffset;
  60956. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  60957. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  60958. this._allEntries = sortedAll;
  60959. return elementsBuffer;
  60960. };
  60961. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  60962. for (var i = 0; i < this._stride; i++) {
  60963. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  60964. }
  60965. element.offset = destOffset;
  60966. };
  60967. DynamicFloatArray.prototype._growBuffer = function () {
  60968. // Allocate the new buffer with 50% more entries, copy the content of the current one
  60969. var newElCount = Math.floor(this.totalElementCount * 1.5);
  60970. var newBuffer = new Float32Array(newElCount * this._stride);
  60971. newBuffer.set(this.buffer);
  60972. var curCount = this.totalElementCount;
  60973. var addedCount = newElCount - this.totalElementCount;
  60974. for (var i = 0; i < addedCount; i++) {
  60975. var element = new DynamicFloatArrayElementInfo();
  60976. element.offset = (curCount + i) * this.stride;
  60977. this._allEntries.push(element);
  60978. this._freeEntries[addedCount - i - 1] = element;
  60979. }
  60980. this._firstFree = curCount * this.stride;
  60981. this.buffer = newBuffer;
  60982. };
  60983. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  60984. /**
  60985. * Get the total count of entries that can fit in the current buffer
  60986. * @returns the elements count
  60987. */
  60988. get: function () {
  60989. return this._allEntries.length;
  60990. },
  60991. enumerable: true,
  60992. configurable: true
  60993. });
  60994. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  60995. /**
  60996. * Get the count of free entries that can still be allocated without resizing the buffer
  60997. * @returns the free elements count
  60998. */
  60999. get: function () {
  61000. return this._freeEntries.length;
  61001. },
  61002. enumerable: true,
  61003. configurable: true
  61004. });
  61005. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  61006. /**
  61007. * Get the count of allocated elements
  61008. * @returns the allocated elements count
  61009. */
  61010. get: function () {
  61011. return this._allEntries.length - this._freeEntries.length;
  61012. },
  61013. enumerable: true,
  61014. configurable: true
  61015. });
  61016. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  61017. /**
  61018. * Return the size of one element in float
  61019. * @returns the size in float
  61020. */
  61021. get: function () {
  61022. return this._stride;
  61023. },
  61024. enumerable: true,
  61025. configurable: true
  61026. });
  61027. DynamicFloatArray.prototype.sort = function () {
  61028. var _this = this;
  61029. if (!this.compareValueOffset) {
  61030. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  61031. }
  61032. var count = this.usedElementCount;
  61033. // Do we have to (re)create the sort table?
  61034. if (!this._sortTable || this._sortTable.length < count) {
  61035. // 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...
  61036. var newCount = Math.min(this.totalElementCount, count * 2);
  61037. this._sortTable = new Array(newCount);
  61038. }
  61039. if (!this._sortedTable || this._sortedTable.length !== count) {
  61040. this._sortedTable = new Array(count);
  61041. }
  61042. // Because, you know...
  61043. this.pack();
  61044. //let stride = this.stride;
  61045. //for (let i = 0; i < count; i++) {
  61046. // let si = this._sortTable[i];
  61047. // if (!si) {
  61048. // si = new SortInfo();
  61049. // this._sortTable[i] = si;
  61050. // }
  61051. // si.entry = this._allEntries[i];
  61052. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  61053. // si.swapedOffset = null;
  61054. // this._sortedTable[i] = si;
  61055. //}
  61056. var curOffset = 0;
  61057. var stride = this.stride;
  61058. for (var i = 0; i < count; i++, curOffset += stride) {
  61059. var si = this._sortTable[i];
  61060. if (!si) {
  61061. si = new SortInfo();
  61062. this._sortTable[i] = si;
  61063. }
  61064. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  61065. si.offset = curOffset;
  61066. si.swapedOffset = null;
  61067. this._sortedTable[i] = si;
  61068. }
  61069. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  61070. if (this.sortingAscending) {
  61071. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  61072. }
  61073. else {
  61074. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  61075. }
  61076. var swapElements = function (src, dst) {
  61077. for (var i = 0; i < stride; i++) {
  61078. var tps = _this.buffer[dst + i];
  61079. _this.buffer[dst + i] = _this.buffer[src + i];
  61080. _this.buffer[src + i] = tps;
  61081. }
  61082. };
  61083. // 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:
  61084. // 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),
  61085. // and I still want something with a good algorithm complexity.
  61086. // 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,
  61087. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  61088. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  61089. // 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
  61090. // until we find a SortInfo object without a swapedOffset which means we got the right location
  61091. // 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
  61092. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  61093. for (var i = 0; i < count; i++) {
  61094. // Get the element to move
  61095. var sourceSI = this._sortedTable[i];
  61096. var destSI = this._sortTable[i];
  61097. var sourceOff = sourceSI.offset;
  61098. // If the source changed location, find the new one
  61099. if (sourceSI.swapedOffset) {
  61100. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  61101. var curSI = sourceSI;
  61102. while (curSI.swapedOffset) {
  61103. curSI = this._sortTable[curSI.swapedOffset / stride];
  61104. }
  61105. // Finally get the right location
  61106. sourceOff = curSI.offset;
  61107. }
  61108. // Tag the element being replaced with its new location
  61109. destSI.swapedOffset = sourceOff;
  61110. // Swap elements (only if needed)
  61111. if (sourceOff !== destSI.offset) {
  61112. swapElements(sourceOff, destSI.offset);
  61113. }
  61114. // Update the offset in the corresponding DFAE
  61115. //sourceSI.entry.offset = destSI.entry.offset;
  61116. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  61117. }
  61118. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  61119. return true;
  61120. };
  61121. return DynamicFloatArray;
  61122. }());
  61123. BABYLON.DynamicFloatArray = DynamicFloatArray;
  61124. var SortInfo = (function () {
  61125. function SortInfo() {
  61126. this.compareData = this.offset = this.swapedOffset = null;
  61127. }
  61128. return SortInfo;
  61129. }());
  61130. })(BABYLON || (BABYLON = {}));
  61131. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  61132. var BABYLON;
  61133. (function (BABYLON) {
  61134. var serializedGeometries = [];
  61135. var serializeGeometry = function (geometry, serializationGeometries) {
  61136. if (serializedGeometries[geometry.id]) {
  61137. return;
  61138. }
  61139. if (geometry.doNotSerialize) {
  61140. return;
  61141. }
  61142. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  61143. serializationGeometries.boxes.push(geometry.serialize());
  61144. }
  61145. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  61146. serializationGeometries.spheres.push(geometry.serialize());
  61147. }
  61148. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  61149. serializationGeometries.cylinders.push(geometry.serialize());
  61150. }
  61151. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  61152. serializationGeometries.toruses.push(geometry.serialize());
  61153. }
  61154. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  61155. serializationGeometries.grounds.push(geometry.serialize());
  61156. }
  61157. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  61158. serializationGeometries.planes.push(geometry.serialize());
  61159. }
  61160. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  61161. serializationGeometries.torusKnots.push(geometry.serialize());
  61162. }
  61163. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  61164. throw new Error("Unknown primitive type");
  61165. }
  61166. else {
  61167. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  61168. }
  61169. serializedGeometries[geometry.id] = true;
  61170. };
  61171. var serializeMesh = function (mesh, serializationScene) {
  61172. var serializationObject = {};
  61173. // Geometry
  61174. var geometry = mesh._geometry;
  61175. if (geometry) {
  61176. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  61177. // 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
  61178. serializeGeometry(geometry, serializationScene.geometries);
  61179. }
  61180. }
  61181. // Custom
  61182. if (mesh.serialize) {
  61183. mesh.serialize(serializationObject);
  61184. }
  61185. return serializationObject;
  61186. };
  61187. var finalizeSingleMesh = function (mesh, serializationObject) {
  61188. //only works if the mesh is already loaded
  61189. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  61190. //serialize material
  61191. if (mesh.material) {
  61192. if (mesh.material instanceof BABYLON.StandardMaterial) {
  61193. serializationObject.materials = serializationObject.materials || [];
  61194. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  61195. serializationObject.materials.push(mesh.material.serialize());
  61196. }
  61197. }
  61198. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  61199. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  61200. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  61201. serializationObject.multiMaterials.push(mesh.material.serialize());
  61202. }
  61203. }
  61204. }
  61205. //serialize geometry
  61206. var geometry = mesh._geometry;
  61207. if (geometry) {
  61208. if (!serializationObject.geometries) {
  61209. serializationObject.geometries = {};
  61210. serializationObject.geometries.boxes = [];
  61211. serializationObject.geometries.spheres = [];
  61212. serializationObject.geometries.cylinders = [];
  61213. serializationObject.geometries.toruses = [];
  61214. serializationObject.geometries.grounds = [];
  61215. serializationObject.geometries.planes = [];
  61216. serializationObject.geometries.torusKnots = [];
  61217. serializationObject.geometries.vertexData = [];
  61218. }
  61219. serializeGeometry(geometry, serializationObject.geometries);
  61220. }
  61221. // Skeletons
  61222. if (mesh.skeleton) {
  61223. serializationObject.skeletons = serializationObject.skeletons || [];
  61224. serializationObject.skeletons.push(mesh.skeleton.serialize());
  61225. }
  61226. //serialize the actual mesh
  61227. serializationObject.meshes = serializationObject.meshes || [];
  61228. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  61229. }
  61230. };
  61231. var SceneSerializer = (function () {
  61232. function SceneSerializer() {
  61233. }
  61234. SceneSerializer.ClearCache = function () {
  61235. serializedGeometries = [];
  61236. };
  61237. SceneSerializer.Serialize = function (scene) {
  61238. var serializationObject = {};
  61239. SceneSerializer.ClearCache();
  61240. // Scene
  61241. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  61242. serializationObject.autoClear = scene.autoClear;
  61243. serializationObject.clearColor = scene.clearColor.asArray();
  61244. serializationObject.ambientColor = scene.ambientColor.asArray();
  61245. serializationObject.gravity = scene.gravity.asArray();
  61246. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  61247. serializationObject.workerCollisions = scene.workerCollisions;
  61248. // Fog
  61249. if (scene.fogMode && scene.fogMode !== 0) {
  61250. serializationObject.fogMode = scene.fogMode;
  61251. serializationObject.fogColor = scene.fogColor.asArray();
  61252. serializationObject.fogStart = scene.fogStart;
  61253. serializationObject.fogEnd = scene.fogEnd;
  61254. serializationObject.fogDensity = scene.fogDensity;
  61255. }
  61256. //Physics
  61257. if (scene.isPhysicsEnabled()) {
  61258. serializationObject.physicsEnabled = true;
  61259. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  61260. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  61261. }
  61262. // Metadata
  61263. if (scene.metadata) {
  61264. serializationObject.metadata = scene.metadata;
  61265. }
  61266. // Morph targets
  61267. serializationObject.morphTargetManagers = [];
  61268. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  61269. var abstractMesh = _a[_i];
  61270. var manager = abstractMesh.morphTargetManager;
  61271. if (manager) {
  61272. serializationObject.morphTargetManagers.push(manager.serialize());
  61273. }
  61274. }
  61275. // Lights
  61276. serializationObject.lights = [];
  61277. var index;
  61278. var light;
  61279. for (index = 0; index < scene.lights.length; index++) {
  61280. light = scene.lights[index];
  61281. if (!light.doNotSerialize) {
  61282. serializationObject.lights.push(light.serialize());
  61283. }
  61284. }
  61285. // Cameras
  61286. serializationObject.cameras = [];
  61287. for (index = 0; index < scene.cameras.length; index++) {
  61288. var camera = scene.cameras[index];
  61289. if (!camera.doNotSerialize) {
  61290. serializationObject.cameras.push(camera.serialize());
  61291. }
  61292. }
  61293. if (scene.activeCamera) {
  61294. serializationObject.activeCameraID = scene.activeCamera.id;
  61295. }
  61296. // Animations
  61297. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  61298. // Materials
  61299. serializationObject.materials = [];
  61300. serializationObject.multiMaterials = [];
  61301. var material;
  61302. for (index = 0; index < scene.materials.length; index++) {
  61303. material = scene.materials[index];
  61304. if (!material.doNotSerialize) {
  61305. serializationObject.materials.push(material.serialize());
  61306. }
  61307. }
  61308. // MultiMaterials
  61309. serializationObject.multiMaterials = [];
  61310. for (index = 0; index < scene.multiMaterials.length; index++) {
  61311. var multiMaterial = scene.multiMaterials[index];
  61312. serializationObject.multiMaterials.push(multiMaterial.serialize());
  61313. }
  61314. // Skeletons
  61315. serializationObject.skeletons = [];
  61316. for (index = 0; index < scene.skeletons.length; index++) {
  61317. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  61318. }
  61319. // Geometries
  61320. serializationObject.geometries = {};
  61321. serializationObject.geometries.boxes = [];
  61322. serializationObject.geometries.spheres = [];
  61323. serializationObject.geometries.cylinders = [];
  61324. serializationObject.geometries.toruses = [];
  61325. serializationObject.geometries.grounds = [];
  61326. serializationObject.geometries.planes = [];
  61327. serializationObject.geometries.torusKnots = [];
  61328. serializationObject.geometries.vertexData = [];
  61329. serializedGeometries = [];
  61330. var geometries = scene.getGeometries();
  61331. for (index = 0; index < geometries.length; index++) {
  61332. var geometry = geometries[index];
  61333. if (geometry.isReady()) {
  61334. serializeGeometry(geometry, serializationObject.geometries);
  61335. }
  61336. }
  61337. // Meshes
  61338. serializationObject.meshes = [];
  61339. for (index = 0; index < scene.meshes.length; index++) {
  61340. var abstractMesh = scene.meshes[index];
  61341. if (abstractMesh instanceof BABYLON.Mesh) {
  61342. var mesh = abstractMesh;
  61343. if (!mesh.doNotSerialize) {
  61344. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  61345. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  61346. }
  61347. }
  61348. }
  61349. }
  61350. // Particles Systems
  61351. serializationObject.particleSystems = [];
  61352. for (index = 0; index < scene.particleSystems.length; index++) {
  61353. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  61354. }
  61355. // Lens flares
  61356. serializationObject.lensFlareSystems = [];
  61357. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  61358. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  61359. }
  61360. // Shadows
  61361. serializationObject.shadowGenerators = [];
  61362. for (index = 0; index < scene.lights.length; index++) {
  61363. light = scene.lights[index];
  61364. var shadowGenerator = light.getShadowGenerator();
  61365. // Only support serialization for official generator so far.
  61366. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  61367. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  61368. }
  61369. }
  61370. // Action Manager
  61371. if (scene.actionManager) {
  61372. serializationObject.actions = scene.actionManager.serialize("scene");
  61373. }
  61374. // Audio
  61375. serializationObject.sounds = [];
  61376. for (index = 0; index < scene.soundTracks.length; index++) {
  61377. var soundtrack = scene.soundTracks[index];
  61378. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  61379. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  61380. }
  61381. }
  61382. return serializationObject;
  61383. };
  61384. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  61385. if (withParents === void 0) { withParents = false; }
  61386. if (withChildren === void 0) { withChildren = false; }
  61387. var serializationObject = {};
  61388. SceneSerializer.ClearCache();
  61389. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  61390. if (withParents || withChildren) {
  61391. //deliberate for loop! not for each, appended should be processed as well.
  61392. for (var i = 0; i < toSerialize.length; ++i) {
  61393. if (withChildren) {
  61394. toSerialize[i].getDescendants().forEach(function (node) {
  61395. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  61396. toSerialize.push(node);
  61397. }
  61398. });
  61399. }
  61400. //make sure the array doesn't contain the object already
  61401. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  61402. toSerialize.push(toSerialize[i].parent);
  61403. }
  61404. }
  61405. }
  61406. toSerialize.forEach(function (mesh) {
  61407. finalizeSingleMesh(mesh, serializationObject);
  61408. });
  61409. return serializationObject;
  61410. };
  61411. return SceneSerializer;
  61412. }());
  61413. BABYLON.SceneSerializer = SceneSerializer;
  61414. })(BABYLON || (BABYLON = {}));
  61415. //# sourceMappingURL=babylon.sceneSerializer.js.map
  61416. var BABYLON;
  61417. (function (BABYLON) {
  61418. var ReflectionProbe = (function () {
  61419. function ReflectionProbe(name, size, scene, generateMipMaps) {
  61420. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61421. var _this = this;
  61422. this.name = name;
  61423. this._viewMatrix = BABYLON.Matrix.Identity();
  61424. this._target = BABYLON.Vector3.Zero();
  61425. this._add = BABYLON.Vector3.Zero();
  61426. this.invertYAxis = false;
  61427. this.position = BABYLON.Vector3.Zero();
  61428. this._scene = scene;
  61429. this._scene.reflectionProbes.push(this);
  61430. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  61431. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  61432. switch (faceIndex) {
  61433. case 0:
  61434. _this._add.copyFromFloats(1, 0, 0);
  61435. break;
  61436. case 1:
  61437. _this._add.copyFromFloats(-1, 0, 0);
  61438. break;
  61439. case 2:
  61440. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  61441. break;
  61442. case 3:
  61443. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  61444. break;
  61445. case 4:
  61446. _this._add.copyFromFloats(0, 0, 1);
  61447. break;
  61448. case 5:
  61449. _this._add.copyFromFloats(0, 0, -1);
  61450. break;
  61451. }
  61452. if (_this._attachedMesh) {
  61453. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  61454. }
  61455. _this.position.addToRef(_this._add, _this._target);
  61456. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  61457. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  61458. });
  61459. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  61460. scene.updateTransformMatrix(true);
  61461. });
  61462. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  61463. }
  61464. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  61465. get: function () {
  61466. return this._renderTargetTexture.samples;
  61467. },
  61468. set: function (value) {
  61469. this._renderTargetTexture.samples = value;
  61470. },
  61471. enumerable: true,
  61472. configurable: true
  61473. });
  61474. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  61475. get: function () {
  61476. return this._renderTargetTexture.refreshRate;
  61477. },
  61478. set: function (value) {
  61479. this._renderTargetTexture.refreshRate = value;
  61480. },
  61481. enumerable: true,
  61482. configurable: true
  61483. });
  61484. ReflectionProbe.prototype.getScene = function () {
  61485. return this._scene;
  61486. };
  61487. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  61488. get: function () {
  61489. return this._renderTargetTexture;
  61490. },
  61491. enumerable: true,
  61492. configurable: true
  61493. });
  61494. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  61495. get: function () {
  61496. return this._renderTargetTexture.renderList;
  61497. },
  61498. enumerable: true,
  61499. configurable: true
  61500. });
  61501. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  61502. this._attachedMesh = mesh;
  61503. };
  61504. ReflectionProbe.prototype.dispose = function () {
  61505. var index = this._scene.reflectionProbes.indexOf(this);
  61506. if (index !== -1) {
  61507. // Remove from the scene if found
  61508. this._scene.reflectionProbes.splice(index, 1);
  61509. }
  61510. if (this._renderTargetTexture) {
  61511. this._renderTargetTexture.dispose();
  61512. this._renderTargetTexture = null;
  61513. }
  61514. };
  61515. return ReflectionProbe;
  61516. }());
  61517. BABYLON.ReflectionProbe = ReflectionProbe;
  61518. })(BABYLON || (BABYLON = {}));
  61519. //# sourceMappingURL=babylon.reflectionProbe.js.map
  61520. var BABYLON;
  61521. (function (BABYLON) {
  61522. var Layer = (function () {
  61523. function Layer(name, imgUrl, scene, isBackground, color) {
  61524. this.name = name;
  61525. this.scale = new BABYLON.Vector2(1, 1);
  61526. this.offset = new BABYLON.Vector2(0, 0);
  61527. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  61528. this._vertexBuffers = {};
  61529. // Events
  61530. /**
  61531. * An event triggered when the layer is disposed.
  61532. * @type {BABYLON.Observable}
  61533. */
  61534. this.onDisposeObservable = new BABYLON.Observable();
  61535. /**
  61536. * An event triggered before rendering the scene
  61537. * @type {BABYLON.Observable}
  61538. */
  61539. this.onBeforeRenderObservable = new BABYLON.Observable();
  61540. /**
  61541. * An event triggered after rendering the scene
  61542. * @type {BABYLON.Observable}
  61543. */
  61544. this.onAfterRenderObservable = new BABYLON.Observable();
  61545. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  61546. this.isBackground = isBackground === undefined ? true : isBackground;
  61547. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  61548. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61549. this._scene.layers.push(this);
  61550. var engine = scene.getEngine();
  61551. // VBO
  61552. var vertices = [];
  61553. vertices.push(1, 1);
  61554. vertices.push(-1, 1);
  61555. vertices.push(-1, -1);
  61556. vertices.push(1, -1);
  61557. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61558. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  61559. // Indices
  61560. var indices = [];
  61561. indices.push(0);
  61562. indices.push(1);
  61563. indices.push(2);
  61564. indices.push(0);
  61565. indices.push(2);
  61566. indices.push(3);
  61567. this._indexBuffer = engine.createIndexBuffer(indices);
  61568. // Effects
  61569. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  61570. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  61571. }
  61572. Object.defineProperty(Layer.prototype, "onDispose", {
  61573. set: function (callback) {
  61574. if (this._onDisposeObserver) {
  61575. this.onDisposeObservable.remove(this._onDisposeObserver);
  61576. }
  61577. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  61578. },
  61579. enumerable: true,
  61580. configurable: true
  61581. });
  61582. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  61583. set: function (callback) {
  61584. if (this._onBeforeRenderObserver) {
  61585. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  61586. }
  61587. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  61588. },
  61589. enumerable: true,
  61590. configurable: true
  61591. });
  61592. Object.defineProperty(Layer.prototype, "onAfterRender", {
  61593. set: function (callback) {
  61594. if (this._onAfterRenderObserver) {
  61595. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  61596. }
  61597. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  61598. },
  61599. enumerable: true,
  61600. configurable: true
  61601. });
  61602. Layer.prototype.render = function () {
  61603. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  61604. // Check
  61605. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  61606. return;
  61607. var engine = this._scene.getEngine();
  61608. this.onBeforeRenderObservable.notifyObservers(this);
  61609. // Render
  61610. engine.enableEffect(currentEffect);
  61611. engine.setState(false);
  61612. // Texture
  61613. currentEffect.setTexture("textureSampler", this.texture);
  61614. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  61615. // Color
  61616. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  61617. // Scale / offset
  61618. currentEffect.setVector2("offset", this.offset);
  61619. currentEffect.setVector2("scale", this.scale);
  61620. // VBOs
  61621. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  61622. // Draw order
  61623. if (!this.alphaTest) {
  61624. engine.setAlphaMode(this.alphaBlendingMode);
  61625. engine.draw(true, 0, 6);
  61626. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61627. }
  61628. else {
  61629. engine.draw(true, 0, 6);
  61630. }
  61631. this.onAfterRenderObservable.notifyObservers(this);
  61632. };
  61633. Layer.prototype.dispose = function () {
  61634. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61635. if (vertexBuffer) {
  61636. vertexBuffer.dispose();
  61637. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61638. }
  61639. if (this._indexBuffer) {
  61640. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61641. this._indexBuffer = null;
  61642. }
  61643. if (this.texture) {
  61644. this.texture.dispose();
  61645. this.texture = null;
  61646. }
  61647. // Remove from scene
  61648. var index = this._scene.layers.indexOf(this);
  61649. this._scene.layers.splice(index, 1);
  61650. // Callback
  61651. this.onDisposeObservable.notifyObservers(this);
  61652. this.onDisposeObservable.clear();
  61653. this.onAfterRenderObservable.clear();
  61654. this.onBeforeRenderObservable.clear();
  61655. };
  61656. return Layer;
  61657. }());
  61658. BABYLON.Layer = Layer;
  61659. })(BABYLON || (BABYLON = {}));
  61660. //# sourceMappingURL=babylon.layer.js.map
  61661. BABYLON.Effect.ShadersStore={"defaultVertexShader":"\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>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\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#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":"#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;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\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<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\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_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#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\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\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>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\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#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef MICROSURFACEMAP\nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\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\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec3 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#include<fresnelFunction>\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\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\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#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE \nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientOcclusionColor.rgb=mix(ambientOcclusionColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a*vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#else\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED \nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo.rgb;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo.rgb=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#else\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface=microSurfaceTexel.r;\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=lightDiffuseContribution*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=(lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=(shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#endif\n#else\nvec3 finalDiffuse=lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#endif\n#endif\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution+=vAmbientColor;\nshadowedOnlyLightDiffuseContribution*=surfaceAlbedo.rgb;\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution,0.0);\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#ifdef EMISSIVEASILLUMINATION\nfinalColor.rgb+=(surfaceEmissiveColor*vLightingIntensity.y);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nuniform vec2 biasAndScale;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5; \n#endif\ndepth+=biasAndScale.x;\n#ifdef ESM\ndepth=exp(-min(87.,biasAndScale.y*depth));\n#endif\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","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}","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","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}","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}"};
  61662. 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#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#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(normal,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangent.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangent.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#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","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 vec3 vBumpInfos;\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#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithESMCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","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#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithESMCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.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"};
  61663. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  61664. module.exports = BABYLON;
  61665. };