babylon.max.js 3.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Scalar = (function () {
  67. function Scalar() {
  68. }
  69. /**
  70. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  71. */
  72. Scalar.Lerp = function (start, end, amount) {
  73. return start + ((end - start) * amount);
  74. };
  75. /**
  76. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  77. */
  78. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  79. var squared = amount * amount;
  80. var cubed = amount * squared;
  81. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  82. var part2 = (-2.0 * cubed) + (3.0 * squared);
  83. var part3 = (cubed - (2.0 * squared)) + amount;
  84. var part4 = cubed - squared;
  85. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  86. };
  87. return Scalar;
  88. }());
  89. BABYLON.Scalar = Scalar;
  90. var Color3 = (function () {
  91. /**
  92. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  93. */
  94. function Color3(r, g, b) {
  95. if (r === void 0) { r = 0; }
  96. if (g === void 0) { g = 0; }
  97. if (b === void 0) { b = 0; }
  98. this.r = r;
  99. this.g = g;
  100. this.b = b;
  101. }
  102. /**
  103. * Returns a string with the Color3 current values.
  104. */
  105. Color3.prototype.toString = function () {
  106. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  107. };
  108. /**
  109. * Returns the string "Color3".
  110. */
  111. Color3.prototype.getClassName = function () {
  112. return "Color3";
  113. };
  114. /**
  115. * Returns the Color3 hash code.
  116. */
  117. Color3.prototype.getHashCode = function () {
  118. var hash = this.r || 0;
  119. hash = (hash * 397) ^ (this.g || 0);
  120. hash = (hash * 397) ^ (this.b || 0);
  121. return hash;
  122. };
  123. // Operators
  124. /**
  125. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  126. * Returns the Color3.
  127. */
  128. Color3.prototype.toArray = function (array, index) {
  129. if (index === undefined) {
  130. index = 0;
  131. }
  132. array[index] = this.r;
  133. array[index + 1] = this.g;
  134. array[index + 2] = this.b;
  135. return this;
  136. };
  137. /**
  138. * Returns a new Color4 object from the current Color3 and the passed alpha.
  139. */
  140. Color3.prototype.toColor4 = function (alpha) {
  141. if (alpha === void 0) { alpha = 1; }
  142. return new Color4(this.r, this.g, this.b, alpha);
  143. };
  144. /**
  145. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  146. */
  147. Color3.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. /**
  153. * Returns the luminance value (float).
  154. */
  155. Color3.prototype.toLuminance = function () {
  156. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  157. };
  158. /**
  159. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  160. * Returns this new object.
  161. */
  162. Color3.prototype.multiply = function (otherColor) {
  163. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  164. };
  165. /**
  166. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  167. * Returns the current Color3.
  168. */
  169. Color3.prototype.multiplyToRef = function (otherColor, result) {
  170. result.r = this.r * otherColor.r;
  171. result.g = this.g * otherColor.g;
  172. result.b = this.b * otherColor.b;
  173. return this;
  174. };
  175. /**
  176. * Boolean : True if the rgb values are equal to the passed ones.
  177. */
  178. Color3.prototype.equals = function (otherColor) {
  179. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  180. };
  181. /**
  182. * Boolean : True if the rgb values are equal to the passed ones.
  183. */
  184. Color3.prototype.equalsFloats = function (r, g, b) {
  185. return this.r === r && this.g === g && this.b === b;
  186. };
  187. /**
  188. * Multiplies in place each rgb value by scale.
  189. * Returns the updated Color3.
  190. */
  191. Color3.prototype.scale = function (scale) {
  192. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  193. };
  194. /**
  195. * Multiplies the rgb values by scale and stores the result into "result".
  196. * Returns the unmodified current Color3.
  197. */
  198. Color3.prototype.scaleToRef = function (scale, result) {
  199. result.r = this.r * scale;
  200. result.g = this.g * scale;
  201. result.b = this.b * scale;
  202. return this;
  203. };
  204. /**
  205. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  206. */
  207. Color3.prototype.add = function (otherColor) {
  208. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  209. };
  210. /**
  211. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  212. * Returns the unmodified current Color3.
  213. */
  214. Color3.prototype.addToRef = function (otherColor, result) {
  215. result.r = this.r + otherColor.r;
  216. result.g = this.g + otherColor.g;
  217. result.b = this.b + otherColor.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  222. */
  223. Color3.prototype.subtract = function (otherColor) {
  224. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  225. };
  226. /**
  227. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  228. * Returns the unmodified current Color3.
  229. */
  230. Color3.prototype.subtractToRef = function (otherColor, result) {
  231. result.r = this.r - otherColor.r;
  232. result.g = this.g - otherColor.g;
  233. result.b = this.b - otherColor.b;
  234. return this;
  235. };
  236. /**
  237. * Returns a new Color3 copied the current one.
  238. */
  239. Color3.prototype.clone = function () {
  240. return new Color3(this.r, this.g, this.b);
  241. };
  242. /**
  243. * Copies the rgb values from the source in the current Color3.
  244. * Returns the updated Color3.
  245. */
  246. Color3.prototype.copyFrom = function (source) {
  247. this.r = source.r;
  248. this.g = source.g;
  249. this.b = source.b;
  250. return this;
  251. };
  252. /**
  253. * Updates the Color3 rgb values from the passed floats.
  254. * Returns the Color3.
  255. */
  256. Color3.prototype.copyFromFloats = function (r, g, b) {
  257. this.r = r;
  258. this.g = g;
  259. this.b = b;
  260. return this;
  261. };
  262. /**
  263. * Updates the Color3 rgb values from the passed floats.
  264. * Returns the Color3.
  265. */
  266. Color3.prototype.set = function (r, g, b) {
  267. return this.copyFromFloats(r, g, b);
  268. };
  269. /**
  270. * Returns the Color3 hexadecimal code as a string.
  271. */
  272. Color3.prototype.toHexString = function () {
  273. var intR = (this.r * 255) | 0;
  274. var intG = (this.g * 255) | 0;
  275. var intB = (this.b * 255) | 0;
  276. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  277. };
  278. /**
  279. * Returns a new Color3 converted to linear space.
  280. */
  281. Color3.prototype.toLinearSpace = function () {
  282. var convertedColor = new Color3();
  283. this.toLinearSpaceToRef(convertedColor);
  284. return convertedColor;
  285. };
  286. /**
  287. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  288. * Returns the unmodified Color3.
  289. */
  290. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  291. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  292. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  293. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  294. return this;
  295. };
  296. /**
  297. * Returns a new Color3 converted to gamma space.
  298. */
  299. Color3.prototype.toGammaSpace = function () {
  300. var convertedColor = new Color3();
  301. this.toGammaSpaceToRef(convertedColor);
  302. return convertedColor;
  303. };
  304. /**
  305. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  306. * Returns the unmodified Color3.
  307. */
  308. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  309. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  310. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  311. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  312. return this;
  313. };
  314. // Statics
  315. /**
  316. * Creates a new Color3 from the string containing valid hexadecimal values.
  317. */
  318. Color3.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  320. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  321. return new Color3(0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. return Color3.FromInts(r, g, b);
  327. };
  328. /**
  329. * Creates a new Vector3 from the startind index of the passed array.
  330. */
  331. Color3.FromArray = function (array, offset) {
  332. if (offset === void 0) { offset = 0; }
  333. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  334. };
  335. /**
  336. * Creates a new Color3 from integer values ( < 256).
  337. */
  338. Color3.FromInts = function (r, g, b) {
  339. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  340. };
  341. /**
  342. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  343. */
  344. Color3.Lerp = function (start, end, amount) {
  345. var r = start.r + ((end.r - start.r) * amount);
  346. var g = start.g + ((end.g - start.g) * amount);
  347. var b = start.b + ((end.b - start.b) * amount);
  348. return new Color3(r, g, b);
  349. };
  350. Color3.Red = function () { return new Color3(1, 0, 0); };
  351. Color3.Green = function () { return new Color3(0, 1, 0); };
  352. Color3.Blue = function () { return new Color3(0, 0, 1); };
  353. Color3.Black = function () { return new Color3(0, 0, 0); };
  354. Color3.White = function () { return new Color3(1, 1, 1); };
  355. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  356. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  357. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  358. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  359. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  360. return Color3;
  361. }());
  362. BABYLON.Color3 = Color3;
  363. var Color4 = (function () {
  364. /**
  365. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  366. */
  367. function Color4(r, g, b, a) {
  368. this.r = r;
  369. this.g = g;
  370. this.b = b;
  371. this.a = a;
  372. }
  373. // Operators
  374. /**
  375. * Adds in place the passed Color4 values to the current Color4.
  376. * Returns the updated Color4.
  377. */
  378. Color4.prototype.addInPlace = function (right) {
  379. this.r += right.r;
  380. this.g += right.g;
  381. this.b += right.b;
  382. this.a += right.a;
  383. return this;
  384. };
  385. /**
  386. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  387. */
  388. Color4.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. /**
  394. * Stores from the starting index in the passed array the Color4 successive values.
  395. * Returns the Color4.
  396. */
  397. Color4.prototype.toArray = function (array, index) {
  398. if (index === undefined) {
  399. index = 0;
  400. }
  401. array[index] = this.r;
  402. array[index + 1] = this.g;
  403. array[index + 2] = this.b;
  404. array[index + 3] = this.a;
  405. return this;
  406. };
  407. /**
  408. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  409. */
  410. Color4.prototype.add = function (right) {
  411. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  412. };
  413. /**
  414. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  415. */
  416. Color4.prototype.subtract = function (right) {
  417. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  418. };
  419. /**
  420. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  421. * Returns the Color4.
  422. */
  423. Color4.prototype.subtractToRef = function (right, result) {
  424. result.r = this.r - right.r;
  425. result.g = this.g - right.g;
  426. result.b = this.b - right.b;
  427. result.a = this.a - right.a;
  428. return this;
  429. };
  430. /**
  431. * Creates a new Color4 with the current Color4 values multiplied by scale.
  432. */
  433. Color4.prototype.scale = function (scale) {
  434. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  435. };
  436. /**
  437. * Multiplies the current Color4 values by scale and stores the result in "result".
  438. * Returns the Color4.
  439. */
  440. Color4.prototype.scaleToRef = function (scale, result) {
  441. result.r = this.r * scale;
  442. result.g = this.g * scale;
  443. result.b = this.b * scale;
  444. result.a = this.a * scale;
  445. return this;
  446. };
  447. /**
  448. * Multipy an RGBA Color4 value by another and return a new Color4 object
  449. * @param color The Color4 (RGBA) value to multiply by
  450. * @returns A new Color4.
  451. */
  452. Color4.prototype.multiply = function (color) {
  453. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  454. };
  455. /**
  456. * Multipy an RGBA Color4 value by another and push the result in a reference value
  457. * @param color The Color4 (RGBA) value to multiply by
  458. * @param result The Color4 (RGBA) to fill the result in
  459. * @returns the result Color4.
  460. */
  461. Color4.prototype.multiplyToRef = function (color, result) {
  462. result.r = this.r * color.r;
  463. result.g = this.g * color.g;
  464. result.b = this.b * color.b;
  465. result.a = this.a * color.a;
  466. return result;
  467. };
  468. /**
  469. * Returns a string with the Color4 values.
  470. */
  471. Color4.prototype.toString = function () {
  472. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  473. };
  474. /**
  475. * Returns the string "Color4"
  476. */
  477. Color4.prototype.getClassName = function () {
  478. return "Color4";
  479. };
  480. /**
  481. * Return the Color4 hash code as a number.
  482. */
  483. Color4.prototype.getHashCode = function () {
  484. var hash = this.r || 0;
  485. hash = (hash * 397) ^ (this.g || 0);
  486. hash = (hash * 397) ^ (this.b || 0);
  487. hash = (hash * 397) ^ (this.a || 0);
  488. return hash;
  489. };
  490. /**
  491. * Creates a new Color4 copied from the current one.
  492. */
  493. Color4.prototype.clone = function () {
  494. return new Color4(this.r, this.g, this.b, this.a);
  495. };
  496. /**
  497. * Copies the passed Color4 values into the current one.
  498. * Returns the updated Color4.
  499. */
  500. Color4.prototype.copyFrom = function (source) {
  501. this.r = source.r;
  502. this.g = source.g;
  503. this.b = source.b;
  504. this.a = source.a;
  505. return this;
  506. };
  507. /**
  508. * Copies the passed float values into the current one.
  509. * Returns the updated Color4.
  510. */
  511. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  512. this.r = r;
  513. this.g = g;
  514. this.b = b;
  515. this.a = a;
  516. return this;
  517. };
  518. /**
  519. * Copies the passed float values into the current one.
  520. * Returns the updated Color4.
  521. */
  522. Color4.prototype.set = function (r, g, b, a) {
  523. return this.copyFromFloats(r, g, b, a);
  524. };
  525. /**
  526. * Returns a string containing the hexadecimal Color4 code.
  527. */
  528. Color4.prototype.toHexString = function () {
  529. var intR = (this.r * 255) | 0;
  530. var intG = (this.g * 255) | 0;
  531. var intB = (this.b * 255) | 0;
  532. var intA = (this.a * 255) | 0;
  533. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  534. };
  535. // Statics
  536. /**
  537. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  538. */
  539. Color4.FromHexString = function (hex) {
  540. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  541. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  542. return new Color4(0.0, 0.0, 0.0, 0.0);
  543. }
  544. var r = parseInt(hex.substring(1, 3), 16);
  545. var g = parseInt(hex.substring(3, 5), 16);
  546. var b = parseInt(hex.substring(5, 7), 16);
  547. var a = parseInt(hex.substring(7, 9), 16);
  548. return Color4.FromInts(r, g, b, a);
  549. };
  550. /**
  551. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  552. */
  553. Color4.Lerp = function (left, right, amount) {
  554. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  555. Color4.LerpToRef(left, right, amount, result);
  556. return result;
  557. };
  558. /**
  559. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  560. */
  561. Color4.LerpToRef = function (left, right, amount, result) {
  562. result.r = left.r + (right.r - left.r) * amount;
  563. result.g = left.g + (right.g - left.g) * amount;
  564. result.b = left.b + (right.b - left.b) * amount;
  565. result.a = left.a + (right.a - left.a) * amount;
  566. };
  567. /**
  568. * Creates a new Color4 from the starting index element of the passed array.
  569. */
  570. Color4.FromArray = function (array, offset) {
  571. if (offset === void 0) { offset = 0; }
  572. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  573. };
  574. /**
  575. * Creates a new Color4 from the passed integers ( < 256 ).
  576. */
  577. Color4.FromInts = function (r, g, b, a) {
  578. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  579. };
  580. Color4.CheckColors4 = function (colors, count) {
  581. // Check if color3 was used
  582. if (colors.length === count * 3) {
  583. var colors4 = [];
  584. for (var index = 0; index < colors.length; index += 3) {
  585. var newIndex = (index / 3) * 4;
  586. colors4[newIndex] = colors[index];
  587. colors4[newIndex + 1] = colors[index + 1];
  588. colors4[newIndex + 2] = colors[index + 2];
  589. colors4[newIndex + 3] = 1.0;
  590. }
  591. return colors4;
  592. }
  593. return colors;
  594. };
  595. return Color4;
  596. }());
  597. BABYLON.Color4 = Color4;
  598. var Vector2 = (function () {
  599. /**
  600. * Creates a new Vector2 from the passed x and y coordinates.
  601. */
  602. function Vector2(x, y) {
  603. this.x = x;
  604. this.y = y;
  605. }
  606. /**
  607. * Returns a string with the Vector2 coordinates.
  608. */
  609. Vector2.prototype.toString = function () {
  610. return "{X: " + this.x + " Y:" + this.y + "}";
  611. };
  612. /**
  613. * Returns the string "Vector2"
  614. */
  615. Vector2.prototype.getClassName = function () {
  616. return "Vector2";
  617. };
  618. /**
  619. * Returns the Vector2 hash code as a number.
  620. */
  621. Vector2.prototype.getHashCode = function () {
  622. var hash = this.x || 0;
  623. hash = (hash * 397) ^ (this.y || 0);
  624. return hash;
  625. };
  626. // Operators
  627. /**
  628. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  629. * Returns the Vector2.
  630. */
  631. Vector2.prototype.toArray = function (array, index) {
  632. if (index === void 0) { index = 0; }
  633. array[index] = this.x;
  634. array[index + 1] = this.y;
  635. return this;
  636. };
  637. /**
  638. * Returns a new array with 2 elements : the Vector2 coordinates.
  639. */
  640. Vector2.prototype.asArray = function () {
  641. var result = [];
  642. this.toArray(result, 0);
  643. return result;
  644. };
  645. /**
  646. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  647. * Returns the updated Vector2.
  648. */
  649. Vector2.prototype.copyFrom = function (source) {
  650. this.x = source.x;
  651. this.y = source.y;
  652. return this;
  653. };
  654. /**
  655. * Sets the Vector2 coordinates with the passed floats.
  656. * Returns the updated Vector2.
  657. */
  658. Vector2.prototype.copyFromFloats = function (x, y) {
  659. this.x = x;
  660. this.y = y;
  661. return this;
  662. };
  663. /**
  664. * Sets the Vector2 coordinates with the passed floats.
  665. * Returns the updated Vector2.
  666. */
  667. Vector2.prototype.set = function (x, y) {
  668. return this.copyFromFloats(x, y);
  669. };
  670. /**
  671. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  672. */
  673. Vector2.prototype.add = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  678. * Returns the Vector2.
  679. */
  680. Vector2.prototype.addToRef = function (otherVector, result) {
  681. result.x = this.x + otherVector.x;
  682. result.y = this.y + otherVector.y;
  683. return this;
  684. };
  685. /**
  686. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  687. * Returns the updated Vector2.
  688. */
  689. Vector2.prototype.addInPlace = function (otherVector) {
  690. this.x += otherVector.x;
  691. this.y += otherVector.y;
  692. return this;
  693. };
  694. /**
  695. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  696. */
  697. Vector2.prototype.addVector3 = function (otherVector) {
  698. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  699. };
  700. /**
  701. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  702. */
  703. Vector2.prototype.subtract = function (otherVector) {
  704. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  705. };
  706. /**
  707. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  708. * Returns the Vector2.
  709. */
  710. Vector2.prototype.subtractToRef = function (otherVector, result) {
  711. result.x = this.x - otherVector.x;
  712. result.y = this.y - otherVector.y;
  713. return this;
  714. };
  715. /**
  716. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.subtractInPlace = function (otherVector) {
  720. this.x -= otherVector.x;
  721. this.y -= otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Multiplies in place the current Vector2 coordinates by the passed ones.
  726. * Returns the updated Vector2.
  727. */
  728. Vector2.prototype.multiplyInPlace = function (otherVector) {
  729. this.x *= otherVector.x;
  730. this.y *= otherVector.y;
  731. return this;
  732. };
  733. /**
  734. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  735. */
  736. Vector2.prototype.multiply = function (otherVector) {
  737. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  738. };
  739. /**
  740. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  741. * Returns the Vector2.
  742. */
  743. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  744. result.x = this.x * otherVector.x;
  745. result.y = this.y * otherVector.y;
  746. return this;
  747. };
  748. /**
  749. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  750. */
  751. Vector2.prototype.multiplyByFloats = function (x, y) {
  752. return new Vector2(this.x * x, this.y * y);
  753. };
  754. /**
  755. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  756. */
  757. Vector2.prototype.divide = function (otherVector) {
  758. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  759. };
  760. /**
  761. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  762. * Returns the Vector2.
  763. */
  764. Vector2.prototype.divideToRef = function (otherVector, result) {
  765. result.x = this.x / otherVector.x;
  766. result.y = this.y / otherVector.y;
  767. return this;
  768. };
  769. /**
  770. * Returns a new Vector2 with current Vector2 negated coordinates.
  771. */
  772. Vector2.prototype.negate = function () {
  773. return new Vector2(-this.x, -this.y);
  774. };
  775. /**
  776. * Multiply the Vector2 coordinates by scale.
  777. * Returns the updated Vector2.
  778. */
  779. Vector2.prototype.scaleInPlace = function (scale) {
  780. this.x *= scale;
  781. this.y *= scale;
  782. return this;
  783. };
  784. /**
  785. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  786. */
  787. Vector2.prototype.scale = function (scale) {
  788. return new Vector2(this.x * scale, this.y * scale);
  789. };
  790. /**
  791. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  792. */
  793. Vector2.prototype.equals = function (otherVector) {
  794. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  795. };
  796. /**
  797. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  798. */
  799. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  800. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  801. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  802. };
  803. // Properties
  804. /**
  805. * Returns the vector length (float).
  806. */
  807. Vector2.prototype.length = function () {
  808. return Math.sqrt(this.x * this.x + this.y * this.y);
  809. };
  810. /**
  811. * Returns the vector squared length (float);
  812. */
  813. Vector2.prototype.lengthSquared = function () {
  814. return (this.x * this.x + this.y * this.y);
  815. };
  816. // Methods
  817. /**
  818. * Normalize the vector.
  819. * Returns the updated Vector2.
  820. */
  821. Vector2.prototype.normalize = function () {
  822. var len = this.length();
  823. if (len === 0)
  824. return this;
  825. var num = 1.0 / len;
  826. this.x *= num;
  827. this.y *= num;
  828. return this;
  829. };
  830. /**
  831. * Returns a new Vector2 copied from the Vector2.
  832. */
  833. Vector2.prototype.clone = function () {
  834. return new Vector2(this.x, this.y);
  835. };
  836. // Statics
  837. /**
  838. * Returns a new Vector2(0, 0)
  839. */
  840. Vector2.Zero = function () {
  841. return new Vector2(0, 0);
  842. };
  843. /**
  844. * Returns a new Vector2 set from the passed index element of the passed array.
  845. */
  846. Vector2.FromArray = function (array, offset) {
  847. if (offset === void 0) { offset = 0; }
  848. return new Vector2(array[offset], array[offset + 1]);
  849. };
  850. /**
  851. * Sets "result" from the passed index element of the passed array.
  852. */
  853. Vector2.FromArrayToRef = function (array, offset, result) {
  854. result.x = array[offset];
  855. result.y = array[offset + 1];
  856. };
  857. /**
  858. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  859. */
  860. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  861. var squared = amount * amount;
  862. var cubed = amount * squared;
  863. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  864. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  865. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  866. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  867. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  868. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  869. return new Vector2(x, y);
  870. };
  871. /**
  872. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  873. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  874. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  875. */
  876. Vector2.Clamp = function (value, min, max) {
  877. var x = value.x;
  878. x = (x > max.x) ? max.x : x;
  879. x = (x < min.x) ? min.x : x;
  880. var y = value.y;
  881. y = (y > max.y) ? max.y : y;
  882. y = (y < min.y) ? min.y : y;
  883. return new Vector2(x, y);
  884. };
  885. /**
  886. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  887. */
  888. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  889. var squared = amount * amount;
  890. var cubed = amount * squared;
  891. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  892. var part2 = (-2.0 * cubed) + (3.0 * squared);
  893. var part3 = (cubed - (2.0 * squared)) + amount;
  894. var part4 = cubed - squared;
  895. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  896. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  897. return new Vector2(x, y);
  898. };
  899. /**
  900. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  901. */
  902. Vector2.Lerp = function (start, end, amount) {
  903. var x = start.x + ((end.x - start.x) * amount);
  904. var y = start.y + ((end.y - start.y) * amount);
  905. return new Vector2(x, y);
  906. };
  907. /**
  908. * Returns the dot product (float) of the vector "left" and the vector "right".
  909. */
  910. Vector2.Dot = function (left, right) {
  911. return left.x * right.x + left.y * right.y;
  912. };
  913. /**
  914. * Returns a new Vector2 equal to the normalized passed vector.
  915. */
  916. Vector2.Normalize = function (vector) {
  917. var newVector = vector.clone();
  918. newVector.normalize();
  919. return newVector;
  920. };
  921. /**
  922. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  923. */
  924. Vector2.Minimize = function (left, right) {
  925. var x = (left.x < right.x) ? left.x : right.x;
  926. var y = (left.y < right.y) ? left.y : right.y;
  927. return new Vector2(x, y);
  928. };
  929. /**
  930. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  931. */
  932. Vector2.Maximize = function (left, right) {
  933. var x = (left.x > right.x) ? left.x : right.x;
  934. var y = (left.y > right.y) ? left.y : right.y;
  935. return new Vector2(x, y);
  936. };
  937. /**
  938. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  939. */
  940. Vector2.Transform = function (vector, transformation) {
  941. var r = Vector2.Zero();
  942. Vector2.TransformToRef(vector, transformation, r);
  943. return r;
  944. };
  945. /**
  946. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  947. */
  948. Vector2.TransformToRef = function (vector, transformation, result) {
  949. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  950. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  951. result.x = x;
  952. result.y = y;
  953. };
  954. /**
  955. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  956. */
  957. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  958. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  959. var sign = a < 0 ? -1 : 1;
  960. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  961. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  962. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  963. };
  964. /**
  965. * Returns the distance (float) between the vectors "value1" and "value2".
  966. */
  967. Vector2.Distance = function (value1, value2) {
  968. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  969. };
  970. /**
  971. * Returns the squared distance (float) between the vectors "value1" and "value2".
  972. */
  973. Vector2.DistanceSquared = function (value1, value2) {
  974. var x = value1.x - value2.x;
  975. var y = value1.y - value2.y;
  976. return (x * x) + (y * y);
  977. };
  978. /**
  979. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  980. */
  981. Vector2.Center = function (value1, value2) {
  982. var center = value1.add(value2);
  983. center.scaleInPlace(0.5);
  984. return center;
  985. };
  986. /**
  987. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  988. */
  989. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  990. var l2 = Vector2.DistanceSquared(segA, segB);
  991. if (l2 === 0.0) {
  992. return Vector2.Distance(p, segA);
  993. }
  994. var v = segB.subtract(segA);
  995. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  996. var proj = segA.add(v.multiplyByFloats(t, t));
  997. return Vector2.Distance(p, proj);
  998. };
  999. return Vector2;
  1000. }());
  1001. BABYLON.Vector2 = Vector2;
  1002. var Vector3 = (function () {
  1003. /**
  1004. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1005. * A Vector3 is the main object used in 3D geometry.
  1006. * It can represent etiher the coordinates of a point the space, either a direction.
  1007. */
  1008. function Vector3(x, y, z) {
  1009. this.x = x;
  1010. this.y = y;
  1011. this.z = z;
  1012. }
  1013. /**
  1014. * Returns a string with the Vector3 coordinates.
  1015. */
  1016. Vector3.prototype.toString = function () {
  1017. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1018. };
  1019. /**
  1020. * Returns the string "Vector3"
  1021. */
  1022. Vector3.prototype.getClassName = function () {
  1023. return "Vector3";
  1024. };
  1025. /**
  1026. * Returns the Vector hash code.
  1027. */
  1028. Vector3.prototype.getHashCode = function () {
  1029. var hash = this.x || 0;
  1030. hash = (hash * 397) ^ (this.y || 0);
  1031. hash = (hash * 397) ^ (this.z || 0);
  1032. return hash;
  1033. };
  1034. // Operators
  1035. /**
  1036. * Returns a new array with three elements : the coordinates the Vector3.
  1037. */
  1038. Vector3.prototype.asArray = function () {
  1039. var result = [];
  1040. this.toArray(result, 0);
  1041. return result;
  1042. };
  1043. /**
  1044. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1045. * Returns the Vector3.
  1046. */
  1047. Vector3.prototype.toArray = function (array, index) {
  1048. if (index === void 0) { index = 0; }
  1049. array[index] = this.x;
  1050. array[index + 1] = this.y;
  1051. array[index + 2] = this.z;
  1052. return this;
  1053. };
  1054. /**
  1055. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1056. */
  1057. Vector3.prototype.toQuaternion = function () {
  1058. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1059. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1060. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1061. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1062. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1063. var cosy = Math.cos(this.y * 0.5);
  1064. var siny = Math.sin(this.y * 0.5);
  1065. result.x = coszMinusx * siny;
  1066. result.y = -sinzMinusx * siny;
  1067. result.z = sinxPlusz * cosy;
  1068. result.w = cosxPlusz * cosy;
  1069. return result;
  1070. };
  1071. /**
  1072. * Adds the passed vector to the current Vector3.
  1073. * Returns the updated Vector3.
  1074. */
  1075. Vector3.prototype.addInPlace = function (otherVector) {
  1076. this.x += otherVector.x;
  1077. this.y += otherVector.y;
  1078. this.z += otherVector.z;
  1079. return this;
  1080. };
  1081. /**
  1082. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1083. */
  1084. Vector3.prototype.add = function (otherVector) {
  1085. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1086. };
  1087. /**
  1088. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1089. * Returns the current Vector3.
  1090. */
  1091. Vector3.prototype.addToRef = function (otherVector, result) {
  1092. result.x = this.x + otherVector.x;
  1093. result.y = this.y + otherVector.y;
  1094. result.z = this.z + otherVector.z;
  1095. return this;
  1096. };
  1097. /**
  1098. * Subtract the passed vector from the current Vector3.
  1099. * Returns the updated Vector3.
  1100. */
  1101. Vector3.prototype.subtractInPlace = function (otherVector) {
  1102. this.x -= otherVector.x;
  1103. this.y -= otherVector.y;
  1104. this.z -= otherVector.z;
  1105. return this;
  1106. };
  1107. /**
  1108. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1109. */
  1110. Vector3.prototype.subtract = function (otherVector) {
  1111. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1112. };
  1113. /**
  1114. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1115. * Returns the current Vector3.
  1116. */
  1117. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1118. result.x = this.x - otherVector.x;
  1119. result.y = this.y - otherVector.y;
  1120. result.z = this.z - otherVector.z;
  1121. return this;
  1122. };
  1123. /**
  1124. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1125. */
  1126. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1127. return new Vector3(this.x - x, this.y - y, this.z - z);
  1128. };
  1129. /**
  1130. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1131. * Returns the current Vector3.
  1132. */
  1133. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1134. result.x = this.x - x;
  1135. result.y = this.y - y;
  1136. result.z = this.z - z;
  1137. return this;
  1138. };
  1139. /**
  1140. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1141. */
  1142. Vector3.prototype.negate = function () {
  1143. return new Vector3(-this.x, -this.y, -this.z);
  1144. };
  1145. /**
  1146. * Multiplies the Vector3 coordinates by the float "scale".
  1147. * Returns the updated Vector3.
  1148. */
  1149. Vector3.prototype.scaleInPlace = function (scale) {
  1150. this.x *= scale;
  1151. this.y *= scale;
  1152. this.z *= scale;
  1153. return this;
  1154. };
  1155. /**
  1156. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1157. */
  1158. Vector3.prototype.scale = function (scale) {
  1159. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1160. };
  1161. /**
  1162. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1163. * Returns the current Vector3.
  1164. */
  1165. Vector3.prototype.scaleToRef = function (scale, result) {
  1166. result.x = this.x * scale;
  1167. result.y = this.y * scale;
  1168. result.z = this.z * scale;
  1169. return this;
  1170. };
  1171. /**
  1172. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1173. */
  1174. Vector3.prototype.equals = function (otherVector) {
  1175. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1176. };
  1177. /**
  1178. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1179. */
  1180. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1181. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1182. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1183. };
  1184. /**
  1185. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1186. */
  1187. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1188. return this.x === x && this.y === y && this.z === z;
  1189. };
  1190. /**
  1191. * Muliplies the current Vector3 coordinates by the passed ones.
  1192. * Returns the updated Vector3.
  1193. */
  1194. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1195. this.x *= otherVector.x;
  1196. this.y *= otherVector.y;
  1197. this.z *= otherVector.z;
  1198. return this;
  1199. };
  1200. /**
  1201. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1202. */
  1203. Vector3.prototype.multiply = function (otherVector) {
  1204. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1205. };
  1206. /**
  1207. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1208. * Returns the current Vector3.
  1209. */
  1210. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1211. result.x = this.x * otherVector.x;
  1212. result.y = this.y * otherVector.y;
  1213. result.z = this.z * otherVector.z;
  1214. return this;
  1215. };
  1216. /**
  1217. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1218. */
  1219. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1220. return new Vector3(this.x * x, this.y * y, this.z * z);
  1221. };
  1222. /**
  1223. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1224. */
  1225. Vector3.prototype.divide = function (otherVector) {
  1226. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1227. };
  1228. /**
  1229. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1230. * Returns the current Vector3.
  1231. */
  1232. Vector3.prototype.divideToRef = function (otherVector, result) {
  1233. result.x = this.x / otherVector.x;
  1234. result.y = this.y / otherVector.y;
  1235. result.z = this.z / otherVector.z;
  1236. return this;
  1237. };
  1238. /**
  1239. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1240. * Returns the updated Vector3.
  1241. */
  1242. Vector3.prototype.MinimizeInPlace = function (other) {
  1243. if (other.x < this.x)
  1244. this.x = other.x;
  1245. if (other.y < this.y)
  1246. this.y = other.y;
  1247. if (other.z < this.z)
  1248. this.z = other.z;
  1249. return this;
  1250. };
  1251. /**
  1252. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1253. * Returns the updated Vector3.
  1254. */
  1255. Vector3.prototype.MaximizeInPlace = function (other) {
  1256. if (other.x > this.x)
  1257. this.x = other.x;
  1258. if (other.y > this.y)
  1259. this.y = other.y;
  1260. if (other.z > this.z)
  1261. this.z = other.z;
  1262. return this;
  1263. };
  1264. // Properties
  1265. /**
  1266. * Returns the length of the Vector3 (float).
  1267. */
  1268. Vector3.prototype.length = function () {
  1269. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1270. };
  1271. /**
  1272. * Returns the squared length of the Vector3 (float).
  1273. */
  1274. Vector3.prototype.lengthSquared = function () {
  1275. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1276. };
  1277. // Methods
  1278. /**
  1279. * Normalize the current Vector3.
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.normalize = function () {
  1283. var len = this.length();
  1284. if (len === 0 || len === 1.0)
  1285. return this;
  1286. var num = 1.0 / len;
  1287. this.x *= num;
  1288. this.y *= num;
  1289. this.z *= num;
  1290. return this;
  1291. };
  1292. /**
  1293. * Returns a new Vector3 copied from the current Vector3.
  1294. */
  1295. Vector3.prototype.clone = function () {
  1296. return new Vector3(this.x, this.y, this.z);
  1297. };
  1298. /**
  1299. * Copies the passed vector coordinates to the current Vector3 ones.
  1300. * Returns the updated Vector3.
  1301. */
  1302. Vector3.prototype.copyFrom = function (source) {
  1303. this.x = source.x;
  1304. this.y = source.y;
  1305. this.z = source.z;
  1306. return this;
  1307. };
  1308. /**
  1309. * Copies the passed floats to the current Vector3 coordinates.
  1310. * Returns the updated Vector3.
  1311. */
  1312. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1313. this.x = x;
  1314. this.y = y;
  1315. this.z = z;
  1316. return this;
  1317. };
  1318. /**
  1319. * Copies the passed floats to the current Vector3 coordinates.
  1320. * Returns the updated Vector3.
  1321. */
  1322. Vector3.prototype.set = function (x, y, z) {
  1323. return this.copyFromFloats(x, y, z);
  1324. };
  1325. // Statics
  1326. /**
  1327. *
  1328. */
  1329. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1330. var d0 = Vector3.Dot(vector0, axis) - size;
  1331. var d1 = Vector3.Dot(vector1, axis) - size;
  1332. var s = d0 / (d0 - d1);
  1333. return s;
  1334. };
  1335. /**
  1336. * Returns a new Vector3 set from the index "offset" of the passed array.
  1337. */
  1338. Vector3.FromArray = function (array, offset) {
  1339. if (!offset) {
  1340. offset = 0;
  1341. }
  1342. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1343. };
  1344. /**
  1345. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1346. * This function is deprecated. Use FromArray instead.
  1347. */
  1348. Vector3.FromFloatArray = function (array, offset) {
  1349. return Vector3.FromArray(array, offset);
  1350. };
  1351. /**
  1352. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1353. */
  1354. Vector3.FromArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. };
  1359. /**
  1360. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1361. * This function is deprecated. Use FromArrayToRef instead.
  1362. */
  1363. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1364. return Vector3.FromArrayToRef(array, offset, result);
  1365. };
  1366. /**
  1367. * Sets the passed vector "result" with the passed floats.
  1368. */
  1369. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1370. result.x = x;
  1371. result.y = y;
  1372. result.z = z;
  1373. };
  1374. /**
  1375. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1376. */
  1377. Vector3.Zero = function () {
  1378. return new Vector3(0.0, 0.0, 0.0);
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1382. */
  1383. Vector3.Up = function () {
  1384. return new Vector3(0.0, 1.0, 0.0);
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1388. */
  1389. Vector3.Forward = function () {
  1390. return new Vector3(0.0, 0.0, 1.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1394. */
  1395. Vector3.Right = function () {
  1396. return new Vector3(1.0, 0.0, 0.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1400. */
  1401. Vector3.Left = function () {
  1402. return new Vector3(-1.0, 0.0, 0.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1406. * This method computes tranformed coordinates only, not transformed direction vectors.
  1407. */
  1408. Vector3.TransformCoordinates = function (vector, transformation) {
  1409. var result = Vector3.Zero();
  1410. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1411. return result;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1418. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1419. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1420. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1421. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1422. result.x = x / w;
  1423. result.y = y / w;
  1424. result.z = z / w;
  1425. };
  1426. /**
  1427. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1428. * This method computes tranformed coordinates only, not transformed direction vectors.
  1429. */
  1430. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1431. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1432. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1433. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1434. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1435. result.x = rx / rw;
  1436. result.y = ry / rw;
  1437. result.z = rz / rw;
  1438. };
  1439. /**
  1440. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1441. * This methods computes transformed normalized direction vectors only.
  1442. */
  1443. Vector3.TransformNormal = function (vector, transformation) {
  1444. var result = Vector3.Zero();
  1445. Vector3.TransformNormalToRef(vector, transformation, result);
  1446. return result;
  1447. };
  1448. /**
  1449. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1450. * This methods computes transformed normalized direction vectors only.
  1451. */
  1452. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1453. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1454. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1455. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1456. result.x = x;
  1457. result.y = y;
  1458. result.z = z;
  1459. };
  1460. /**
  1461. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1462. * This methods computes transformed normalized direction vectors only.
  1463. */
  1464. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1465. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1466. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1467. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1468. };
  1469. /**
  1470. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1471. */
  1472. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1473. var squared = amount * amount;
  1474. var cubed = amount * squared;
  1475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1481. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1482. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1483. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1484. return new Vector3(x, y, z);
  1485. };
  1486. /**
  1487. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1488. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1489. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1490. */
  1491. Vector3.Clamp = function (value, min, max) {
  1492. var x = value.x;
  1493. x = (x > max.x) ? max.x : x;
  1494. x = (x < min.x) ? min.x : x;
  1495. var y = value.y;
  1496. y = (y > max.y) ? max.y : y;
  1497. y = (y < min.y) ? min.y : y;
  1498. var z = value.z;
  1499. z = (z > max.z) ? max.z : z;
  1500. z = (z < min.z) ? min.z : z;
  1501. return new Vector3(x, y, z);
  1502. };
  1503. /**
  1504. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1505. */
  1506. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1507. var squared = amount * amount;
  1508. var cubed = amount * squared;
  1509. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1510. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1511. var part3 = (cubed - (2.0 * squared)) + amount;
  1512. var part4 = cubed - squared;
  1513. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1514. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1515. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1516. return new Vector3(x, y, z);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1520. */
  1521. Vector3.Lerp = function (start, end, amount) {
  1522. var result = new Vector3(0, 0, 0);
  1523. Vector3.LerpToRef(start, end, amount, result);
  1524. return result;
  1525. };
  1526. /**
  1527. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1528. */
  1529. Vector3.LerpToRef = function (start, end, amount, result) {
  1530. result.x = start.x + ((end.x - start.x) * amount);
  1531. result.y = start.y + ((end.y - start.y) * amount);
  1532. result.z = start.z + ((end.z - start.z) * amount);
  1533. };
  1534. /**
  1535. * Returns the dot product (float) between the vectors "left" and "right".
  1536. */
  1537. Vector3.Dot = function (left, right) {
  1538. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1539. };
  1540. /**
  1541. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1542. * The cross product is then orthogonal to both "left" and "right".
  1543. */
  1544. Vector3.Cross = function (left, right) {
  1545. var result = Vector3.Zero();
  1546. Vector3.CrossToRef(left, right, result);
  1547. return result;
  1548. };
  1549. /**
  1550. * Sets the passed vector "result" with the cross product of "left" and "right".
  1551. * The cross product is then orthogonal to both "left" and "right".
  1552. */
  1553. Vector3.CrossToRef = function (left, right, result) {
  1554. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1555. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1556. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1557. result.copyFrom(MathTmp.Vector3[0]);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 as the normalization of the passed vector.
  1561. */
  1562. Vector3.Normalize = function (vector) {
  1563. var result = Vector3.Zero();
  1564. Vector3.NormalizeToRef(vector, result);
  1565. return result;
  1566. };
  1567. /**
  1568. * Sets the passed vector "result" with the normalization of the passed first vector.
  1569. */
  1570. Vector3.NormalizeToRef = function (vector, result) {
  1571. result.copyFrom(vector);
  1572. result.normalize();
  1573. };
  1574. Vector3.Project = function (vector, world, transform, viewport) {
  1575. var cw = viewport.width;
  1576. var ch = viewport.height;
  1577. var cx = viewport.x;
  1578. var cy = viewport.y;
  1579. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1580. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1581. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1582. world.multiplyToRef(transform, matrix);
  1583. matrix.multiplyToRef(viewportMatrix, matrix);
  1584. return Vector3.TransformCoordinates(vector, matrix);
  1585. };
  1586. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1587. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1588. world.multiplyToRef(transform, matrix);
  1589. matrix.invert();
  1590. source.x = source.x / viewportWidth * 2 - 1;
  1591. source.y = -(source.y / viewportHeight * 2 - 1);
  1592. var vector = Vector3.TransformCoordinates(source, matrix);
  1593. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1594. if (MathTools.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1600. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1601. world.multiplyToRef(view, matrix);
  1602. matrix.multiplyToRef(projection, matrix);
  1603. matrix.invert();
  1604. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1605. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1606. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1607. if (MathTools.WithinEpsilon(num, 1.0)) {
  1608. vector = vector.scale(1.0 / num);
  1609. }
  1610. return vector;
  1611. };
  1612. Vector3.Minimize = function (left, right) {
  1613. var min = left.clone();
  1614. min.MinimizeInPlace(right);
  1615. return min;
  1616. };
  1617. Vector3.Maximize = function (left, right) {
  1618. var max = left.clone();
  1619. max.MaximizeInPlace(right);
  1620. return max;
  1621. };
  1622. /**
  1623. * Returns the distance (float) between the vectors "value1" and "value2".
  1624. */
  1625. Vector3.Distance = function (value1, value2) {
  1626. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1627. };
  1628. /**
  1629. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1630. */
  1631. Vector3.DistanceSquared = function (value1, value2) {
  1632. var x = value1.x - value2.x;
  1633. var y = value1.y - value2.y;
  1634. var z = value1.z - value2.z;
  1635. return (x * x) + (y * y) + (z * z);
  1636. };
  1637. /**
  1638. * Returns a new Vector3 located at the center between "value1" and "value2".
  1639. */
  1640. Vector3.Center = function (value1, value2) {
  1641. var center = value1.add(value2);
  1642. center.scaleInPlace(0.5);
  1643. return center;
  1644. };
  1645. /**
  1646. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1647. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1648. * to something in order to rotate it from its local system to the given target system.
  1649. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1650. * Returns a new Vector3.
  1651. */
  1652. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1653. var rotation = Vector3.Zero();
  1654. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1655. return rotation;
  1656. };
  1657. /**
  1658. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1659. */
  1660. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1661. var quat = MathTmp.Quaternion[0];
  1662. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1663. quat.toEulerAnglesToRef(ref);
  1664. };
  1665. return Vector3;
  1666. }());
  1667. BABYLON.Vector3 = Vector3;
  1668. //Vector4 class created for EulerAngle class conversion to Quaternion
  1669. var Vector4 = (function () {
  1670. /**
  1671. * Creates a Vector4 object from the passed floats.
  1672. */
  1673. function Vector4(x, y, z, w) {
  1674. this.x = x;
  1675. this.y = y;
  1676. this.z = z;
  1677. this.w = w;
  1678. }
  1679. /**
  1680. * Returns the string with the Vector4 coordinates.
  1681. */
  1682. Vector4.prototype.toString = function () {
  1683. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1684. };
  1685. /**
  1686. * Returns the string "Vector4".
  1687. */
  1688. Vector4.prototype.getClassName = function () {
  1689. return "Vector4";
  1690. };
  1691. /**
  1692. * Returns the Vector4 hash code.
  1693. */
  1694. Vector4.prototype.getHashCode = function () {
  1695. var hash = this.x || 0;
  1696. hash = (hash * 397) ^ (this.y || 0);
  1697. hash = (hash * 397) ^ (this.z || 0);
  1698. hash = (hash * 397) ^ (this.w || 0);
  1699. return hash;
  1700. };
  1701. // Operators
  1702. /**
  1703. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1704. */
  1705. Vector4.prototype.asArray = function () {
  1706. var result = [];
  1707. this.toArray(result, 0);
  1708. return result;
  1709. };
  1710. /**
  1711. * Populates the passed array from the passed index with the Vector4 coordinates.
  1712. * Returns the Vector4.
  1713. */
  1714. Vector4.prototype.toArray = function (array, index) {
  1715. if (index === undefined) {
  1716. index = 0;
  1717. }
  1718. array[index] = this.x;
  1719. array[index + 1] = this.y;
  1720. array[index + 2] = this.z;
  1721. array[index + 3] = this.w;
  1722. return this;
  1723. };
  1724. /**
  1725. * Adds the passed vector to the current Vector4.
  1726. * Returns the updated Vector4.
  1727. */
  1728. Vector4.prototype.addInPlace = function (otherVector) {
  1729. this.x += otherVector.x;
  1730. this.y += otherVector.y;
  1731. this.z += otherVector.z;
  1732. this.w += otherVector.w;
  1733. return this;
  1734. };
  1735. /**
  1736. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1737. */
  1738. Vector4.prototype.add = function (otherVector) {
  1739. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1740. };
  1741. /**
  1742. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1743. * Returns the current Vector4.
  1744. */
  1745. Vector4.prototype.addToRef = function (otherVector, result) {
  1746. result.x = this.x + otherVector.x;
  1747. result.y = this.y + otherVector.y;
  1748. result.z = this.z + otherVector.z;
  1749. result.w = this.w + otherVector.w;
  1750. return this;
  1751. };
  1752. /**
  1753. * Subtract in place the passed vector from the current Vector4.
  1754. * Returns the updated Vector4.
  1755. */
  1756. Vector4.prototype.subtractInPlace = function (otherVector) {
  1757. this.x -= otherVector.x;
  1758. this.y -= otherVector.y;
  1759. this.z -= otherVector.z;
  1760. this.w -= otherVector.w;
  1761. return this;
  1762. };
  1763. /**
  1764. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1765. */
  1766. Vector4.prototype.subtract = function (otherVector) {
  1767. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1768. };
  1769. /**
  1770. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1771. * Returns the current Vector4.
  1772. */
  1773. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1774. result.x = this.x - otherVector.x;
  1775. result.y = this.y - otherVector.y;
  1776. result.z = this.z - otherVector.z;
  1777. result.w = this.w - otherVector.w;
  1778. return this;
  1779. };
  1780. /**
  1781. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1782. */
  1783. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1784. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1785. };
  1786. /**
  1787. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1788. * Returns the current Vector4.
  1789. */
  1790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1791. result.x = this.x - x;
  1792. result.y = this.y - y;
  1793. result.z = this.z - z;
  1794. result.w = this.w - w;
  1795. return this;
  1796. };
  1797. /**
  1798. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1799. */
  1800. Vector4.prototype.negate = function () {
  1801. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1802. };
  1803. /**
  1804. * Multiplies the current Vector4 coordinates by scale (float).
  1805. * Returns the updated Vector4.
  1806. */
  1807. Vector4.prototype.scaleInPlace = function (scale) {
  1808. this.x *= scale;
  1809. this.y *= scale;
  1810. this.z *= scale;
  1811. this.w *= scale;
  1812. return this;
  1813. };
  1814. /**
  1815. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1816. */
  1817. Vector4.prototype.scale = function (scale) {
  1818. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1819. };
  1820. /**
  1821. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1822. * Returns the current Vector4.
  1823. */
  1824. Vector4.prototype.scaleToRef = function (scale, result) {
  1825. result.x = this.x * scale;
  1826. result.y = this.y * scale;
  1827. result.z = this.z * scale;
  1828. result.w = this.w * scale;
  1829. return this;
  1830. };
  1831. /**
  1832. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1833. */
  1834. Vector4.prototype.equals = function (otherVector) {
  1835. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1836. };
  1837. /**
  1838. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1839. */
  1840. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1841. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1842. return otherVector
  1843. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1844. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1845. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1846. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1847. };
  1848. /**
  1849. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1850. */
  1851. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1852. return this.x === x && this.y === y && this.z === z && this.w === w;
  1853. };
  1854. /**
  1855. * Multiplies in place the current Vector4 by the passed one.
  1856. * Returns the updated Vector4.
  1857. */
  1858. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1859. this.x *= otherVector.x;
  1860. this.y *= otherVector.y;
  1861. this.z *= otherVector.z;
  1862. this.w *= otherVector.w;
  1863. return this;
  1864. };
  1865. /**
  1866. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1867. */
  1868. Vector4.prototype.multiply = function (otherVector) {
  1869. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1870. };
  1871. /**
  1872. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1873. * Returns the current Vector4.
  1874. */
  1875. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1876. result.x = this.x * otherVector.x;
  1877. result.y = this.y * otherVector.y;
  1878. result.z = this.z * otherVector.z;
  1879. result.w = this.w * otherVector.w;
  1880. return this;
  1881. };
  1882. /**
  1883. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1884. */
  1885. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1886. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1887. };
  1888. /**
  1889. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1890. */
  1891. Vector4.prototype.divide = function (otherVector) {
  1892. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1893. };
  1894. /**
  1895. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1896. * Returns the current Vector4.
  1897. */
  1898. Vector4.prototype.divideToRef = function (otherVector, result) {
  1899. result.x = this.x / otherVector.x;
  1900. result.y = this.y / otherVector.y;
  1901. result.z = this.z / otherVector.z;
  1902. result.w = this.w / otherVector.w;
  1903. return this;
  1904. };
  1905. /**
  1906. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1907. */
  1908. Vector4.prototype.MinimizeInPlace = function (other) {
  1909. if (other.x < this.x)
  1910. this.x = other.x;
  1911. if (other.y < this.y)
  1912. this.y = other.y;
  1913. if (other.z < this.z)
  1914. this.z = other.z;
  1915. if (other.w < this.w)
  1916. this.w = other.w;
  1917. return this;
  1918. };
  1919. /**
  1920. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1921. */
  1922. Vector4.prototype.MaximizeInPlace = function (other) {
  1923. if (other.x > this.x)
  1924. this.x = other.x;
  1925. if (other.y > this.y)
  1926. this.y = other.y;
  1927. if (other.z > this.z)
  1928. this.z = other.z;
  1929. if (other.w > this.w)
  1930. this.w = other.w;
  1931. return this;
  1932. };
  1933. // Properties
  1934. /**
  1935. * Returns the Vector4 length (float).
  1936. */
  1937. Vector4.prototype.length = function () {
  1938. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1939. };
  1940. /**
  1941. * Returns the Vector4 squared length (float).
  1942. */
  1943. Vector4.prototype.lengthSquared = function () {
  1944. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1945. };
  1946. // Methods
  1947. /**
  1948. * Normalizes in place the Vector4.
  1949. * Returns the updated Vector4.
  1950. */
  1951. Vector4.prototype.normalize = function () {
  1952. var len = this.length();
  1953. if (len === 0)
  1954. return this;
  1955. var num = 1.0 / len;
  1956. this.x *= num;
  1957. this.y *= num;
  1958. this.z *= num;
  1959. this.w *= num;
  1960. return this;
  1961. };
  1962. /**
  1963. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1964. */
  1965. Vector4.prototype.toVector3 = function () {
  1966. return new Vector3(this.x, this.y, this.z);
  1967. };
  1968. /**
  1969. * Returns a new Vector4 copied from the current one.
  1970. */
  1971. Vector4.prototype.clone = function () {
  1972. return new Vector4(this.x, this.y, this.z, this.w);
  1973. };
  1974. /**
  1975. * Updates the current Vector4 with the passed one coordinates.
  1976. * Returns the updated Vector4.
  1977. */
  1978. Vector4.prototype.copyFrom = function (source) {
  1979. this.x = source.x;
  1980. this.y = source.y;
  1981. this.z = source.z;
  1982. this.w = source.w;
  1983. return this;
  1984. };
  1985. /**
  1986. * Updates the current Vector4 coordinates with the passed floats.
  1987. * Returns the updated Vector4.
  1988. */
  1989. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1990. this.x = x;
  1991. this.y = y;
  1992. this.z = z;
  1993. this.w = w;
  1994. return this;
  1995. };
  1996. /**
  1997. * Updates the current Vector4 coordinates with the passed floats.
  1998. * Returns the updated Vector4.
  1999. */
  2000. Vector4.prototype.set = function (x, y, z, w) {
  2001. return this.copyFromFloats(x, y, z, w);
  2002. };
  2003. // Statics
  2004. /**
  2005. * Returns a new Vector4 set from the starting index of the passed array.
  2006. */
  2007. Vector4.FromArray = function (array, offset) {
  2008. if (!offset) {
  2009. offset = 0;
  2010. }
  2011. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2012. };
  2013. /**
  2014. * Updates the passed vector "result" from the starting index of the passed array.
  2015. */
  2016. Vector4.FromArrayToRef = function (array, offset, result) {
  2017. result.x = array[offset];
  2018. result.y = array[offset + 1];
  2019. result.z = array[offset + 2];
  2020. result.w = array[offset + 3];
  2021. };
  2022. /**
  2023. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2024. */
  2025. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2026. Vector4.FromArrayToRef(array, offset, result);
  2027. };
  2028. /**
  2029. * Updates the passed vector "result" coordinates from the passed floats.
  2030. */
  2031. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2032. result.x = x;
  2033. result.y = y;
  2034. result.z = z;
  2035. result.w = w;
  2036. };
  2037. /**
  2038. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2039. */
  2040. Vector4.Zero = function () {
  2041. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2042. };
  2043. /**
  2044. * Returns a new normalized Vector4 from the passed one.
  2045. */
  2046. Vector4.Normalize = function (vector) {
  2047. var result = Vector4.Zero();
  2048. Vector4.NormalizeToRef(vector, result);
  2049. return result;
  2050. };
  2051. /**
  2052. * Updates the passed vector "result" from the normalization of the passed one.
  2053. */
  2054. Vector4.NormalizeToRef = function (vector, result) {
  2055. result.copyFrom(vector);
  2056. result.normalize();
  2057. };
  2058. Vector4.Minimize = function (left, right) {
  2059. var min = left.clone();
  2060. min.MinimizeInPlace(right);
  2061. return min;
  2062. };
  2063. Vector4.Maximize = function (left, right) {
  2064. var max = left.clone();
  2065. max.MaximizeInPlace(right);
  2066. return max;
  2067. };
  2068. /**
  2069. * Returns the distance (float) between the vectors "value1" and "value2".
  2070. */
  2071. Vector4.Distance = function (value1, value2) {
  2072. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2073. };
  2074. /**
  2075. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2076. */
  2077. Vector4.DistanceSquared = function (value1, value2) {
  2078. var x = value1.x - value2.x;
  2079. var y = value1.y - value2.y;
  2080. var z = value1.z - value2.z;
  2081. var w = value1.w - value2.w;
  2082. return (x * x) + (y * y) + (z * z) + (w * w);
  2083. };
  2084. /**
  2085. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2086. */
  2087. Vector4.Center = function (value1, value2) {
  2088. var center = value1.add(value2);
  2089. center.scaleInPlace(0.5);
  2090. return center;
  2091. };
  2092. /**
  2093. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2094. * This methods computes transformed normalized direction vectors only.
  2095. */
  2096. Vector4.TransformNormal = function (vector, transformation) {
  2097. var result = Vector4.Zero();
  2098. Vector4.TransformNormalToRef(vector, transformation, result);
  2099. return result;
  2100. };
  2101. /**
  2102. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2103. * This methods computes transformed normalized direction vectors only.
  2104. */
  2105. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2106. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2107. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2108. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2109. result.x = x;
  2110. result.y = y;
  2111. result.z = z;
  2112. result.w = vector.w;
  2113. };
  2114. /**
  2115. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2116. * This methods computes transformed normalized direction vectors only.
  2117. */
  2118. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2119. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2120. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2121. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2122. result.w = w;
  2123. };
  2124. return Vector4;
  2125. }());
  2126. BABYLON.Vector4 = Vector4;
  2127. var Size = (function () {
  2128. /**
  2129. * Creates a Size object from the passed width and height (floats).
  2130. */
  2131. function Size(width, height) {
  2132. this.width = width;
  2133. this.height = height;
  2134. }
  2135. // Returns a string with the Size width and height.
  2136. Size.prototype.toString = function () {
  2137. return "{W: " + this.width + ", H: " + this.height + "}";
  2138. };
  2139. /**
  2140. * Returns the string "Size"
  2141. */
  2142. Size.prototype.getClassName = function () {
  2143. return "Size";
  2144. };
  2145. /**
  2146. * Returns the Size hash code.
  2147. */
  2148. Size.prototype.getHashCode = function () {
  2149. var hash = this.width || 0;
  2150. hash = (hash * 397) ^ (this.height || 0);
  2151. return hash;
  2152. };
  2153. /**
  2154. * Updates the current size from the passed one.
  2155. * Returns the updated Size.
  2156. */
  2157. Size.prototype.copyFrom = function (src) {
  2158. this.width = src.width;
  2159. this.height = src.height;
  2160. };
  2161. /**
  2162. * Updates in place the current Size from the passed floats.
  2163. * Returns the updated Size.
  2164. */
  2165. Size.prototype.copyFromFloats = function (width, height) {
  2166. this.width = width;
  2167. this.height = height;
  2168. return this;
  2169. };
  2170. /**
  2171. * Updates in place the current Size from the passed floats.
  2172. * Returns the updated Size.
  2173. */
  2174. Size.prototype.set = function (width, height) {
  2175. return this.copyFromFloats(width, height);
  2176. };
  2177. /**
  2178. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2179. */
  2180. Size.prototype.multiplyByFloats = function (w, h) {
  2181. return new Size(this.width * w, this.height * h);
  2182. };
  2183. /**
  2184. * Returns a new Size copied from the passed one.
  2185. */
  2186. Size.prototype.clone = function () {
  2187. return new Size(this.width, this.height);
  2188. };
  2189. /**
  2190. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2191. */
  2192. Size.prototype.equals = function (other) {
  2193. if (!other) {
  2194. return false;
  2195. }
  2196. return (this.width === other.width) && (this.height === other.height);
  2197. };
  2198. Object.defineProperty(Size.prototype, "surface", {
  2199. /**
  2200. * Returns the surface of the Size : width * height (float).
  2201. */
  2202. get: function () {
  2203. return this.width * this.height;
  2204. },
  2205. enumerable: true,
  2206. configurable: true
  2207. });
  2208. /**
  2209. * Returns a new Size set to (0.0, 0.0)
  2210. */
  2211. Size.Zero = function () {
  2212. return new Size(0.0, 0.0);
  2213. };
  2214. /**
  2215. * Returns a new Size set as the addition result of the current Size and the passed one.
  2216. */
  2217. Size.prototype.add = function (otherSize) {
  2218. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2223. */
  2224. Size.prototype.subtract = function (otherSize) {
  2225. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2226. return r;
  2227. };
  2228. /**
  2229. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2230. */
  2231. Size.Lerp = function (start, end, amount) {
  2232. var w = start.width + ((end.width - start.width) * amount);
  2233. var h = start.height + ((end.height - start.height) * amount);
  2234. return new Size(w, h);
  2235. };
  2236. return Size;
  2237. }());
  2238. BABYLON.Size = Size;
  2239. var Quaternion = (function () {
  2240. /**
  2241. * Creates a new Quaternion from the passed floats.
  2242. */
  2243. function Quaternion(x, y, z, w) {
  2244. if (x === void 0) { x = 0.0; }
  2245. if (y === void 0) { y = 0.0; }
  2246. if (z === void 0) { z = 0.0; }
  2247. if (w === void 0) { w = 1.0; }
  2248. this.x = x;
  2249. this.y = y;
  2250. this.z = z;
  2251. this.w = w;
  2252. }
  2253. /**
  2254. * Returns a string with the Quaternion coordinates.
  2255. */
  2256. Quaternion.prototype.toString = function () {
  2257. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2258. };
  2259. /**
  2260. * Returns the string "Quaternion".
  2261. */
  2262. Quaternion.prototype.getClassName = function () {
  2263. return "Quaternion";
  2264. };
  2265. /**
  2266. * Returns the Quaternion hash code.
  2267. */
  2268. Quaternion.prototype.getHashCode = function () {
  2269. var hash = this.x || 0;
  2270. hash = (hash * 397) ^ (this.y || 0);
  2271. hash = (hash * 397) ^ (this.z || 0);
  2272. hash = (hash * 397) ^ (this.w || 0);
  2273. return hash;
  2274. };
  2275. /**
  2276. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2277. */
  2278. Quaternion.prototype.asArray = function () {
  2279. return [this.x, this.y, this.z, this.w];
  2280. };
  2281. /**
  2282. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2283. */
  2284. Quaternion.prototype.equals = function (otherQuaternion) {
  2285. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2286. };
  2287. /**
  2288. * Returns a new Quaternion copied from the current one.
  2289. */
  2290. Quaternion.prototype.clone = function () {
  2291. return new Quaternion(this.x, this.y, this.z, this.w);
  2292. };
  2293. /**
  2294. * Updates the current Quaternion from the passed one coordinates.
  2295. * Returns the updated Quaterion.
  2296. */
  2297. Quaternion.prototype.copyFrom = function (other) {
  2298. this.x = other.x;
  2299. this.y = other.y;
  2300. this.z = other.z;
  2301. this.w = other.w;
  2302. return this;
  2303. };
  2304. /**
  2305. * Updates the current Quaternion from the passed float coordinates.
  2306. * Returns the updated Quaterion.
  2307. */
  2308. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2309. this.x = x;
  2310. this.y = y;
  2311. this.z = z;
  2312. this.w = w;
  2313. return this;
  2314. };
  2315. /**
  2316. * Updates the current Quaternion from the passed float coordinates.
  2317. * Returns the updated Quaterion.
  2318. */
  2319. Quaternion.prototype.set = function (x, y, z, w) {
  2320. return this.copyFromFloats(x, y, z, w);
  2321. };
  2322. /**
  2323. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2324. */
  2325. Quaternion.prototype.add = function (other) {
  2326. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2327. };
  2328. /**
  2329. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2330. */
  2331. Quaternion.prototype.subtract = function (other) {
  2332. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2333. };
  2334. /**
  2335. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2336. */
  2337. Quaternion.prototype.scale = function (value) {
  2338. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2339. };
  2340. /**
  2341. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2342. */
  2343. Quaternion.prototype.multiply = function (q1) {
  2344. var result = new Quaternion(0, 0, 0, 1.0);
  2345. this.multiplyToRef(q1, result);
  2346. return result;
  2347. };
  2348. /**
  2349. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2350. * Returns the current Quaternion.
  2351. */
  2352. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2353. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2354. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2355. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2356. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2357. result.copyFromFloats(x, y, z, w);
  2358. return this;
  2359. };
  2360. /**
  2361. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2362. * Returns the updated Quaternion.
  2363. */
  2364. Quaternion.prototype.multiplyInPlace = function (q1) {
  2365. this.multiplyToRef(q1, this);
  2366. return this;
  2367. };
  2368. /**
  2369. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2370. * Returns the current Quaternion.
  2371. */
  2372. Quaternion.prototype.conjugateToRef = function (ref) {
  2373. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2374. return this;
  2375. };
  2376. /**
  2377. * Conjugates in place the current Quaternion.
  2378. * Returns the updated Quaternion.
  2379. */
  2380. Quaternion.prototype.conjugateInPlace = function () {
  2381. this.x *= -1;
  2382. this.y *= -1;
  2383. this.z *= -1;
  2384. return this;
  2385. };
  2386. /**
  2387. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2388. */
  2389. Quaternion.prototype.conjugate = function () {
  2390. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2391. return result;
  2392. };
  2393. /**
  2394. * Returns the Quaternion length (float).
  2395. */
  2396. Quaternion.prototype.length = function () {
  2397. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2398. };
  2399. /**
  2400. * Normalize in place the current Quaternion.
  2401. * Returns the updated Quaternion.
  2402. */
  2403. Quaternion.prototype.normalize = function () {
  2404. var length = 1.0 / this.length();
  2405. this.x *= length;
  2406. this.y *= length;
  2407. this.z *= length;
  2408. this.w *= length;
  2409. return this;
  2410. };
  2411. /**
  2412. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2413. */
  2414. Quaternion.prototype.toEulerAngles = function (order) {
  2415. if (order === void 0) { order = "YZX"; }
  2416. var result = Vector3.Zero();
  2417. this.toEulerAnglesToRef(result, order);
  2418. return result;
  2419. };
  2420. /**
  2421. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2422. * Returns the current Quaternion.
  2423. */
  2424. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2425. if (order === void 0) { order = "YZX"; }
  2426. var qz = this.z;
  2427. var qx = this.x;
  2428. var qy = this.y;
  2429. var qw = this.w;
  2430. var sqw = qw * qw;
  2431. var sqz = qz * qz;
  2432. var sqx = qx * qx;
  2433. var sqy = qy * qy;
  2434. var zAxisY = qy * qz - qx * qw;
  2435. var limit = .4999999;
  2436. if (zAxisY < -limit) {
  2437. result.y = 2 * Math.atan2(qy, qw);
  2438. result.x = Math.PI / 2;
  2439. result.z = 0;
  2440. }
  2441. else if (zAxisY > limit) {
  2442. result.y = 2 * Math.atan2(qy, qw);
  2443. result.x = -Math.PI / 2;
  2444. result.z = 0;
  2445. }
  2446. else {
  2447. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2448. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2449. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2450. }
  2451. return this;
  2452. };
  2453. /**
  2454. * Updates the passed rotation matrix with the current Quaternion values.
  2455. * Returns the current Quaternion.
  2456. */
  2457. Quaternion.prototype.toRotationMatrix = function (result) {
  2458. var xx = this.x * this.x;
  2459. var yy = this.y * this.y;
  2460. var zz = this.z * this.z;
  2461. var xy = this.x * this.y;
  2462. var zw = this.z * this.w;
  2463. var zx = this.z * this.x;
  2464. var yw = this.y * this.w;
  2465. var yz = this.y * this.z;
  2466. var xw = this.x * this.w;
  2467. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2468. result.m[1] = 2.0 * (xy + zw);
  2469. result.m[2] = 2.0 * (zx - yw);
  2470. result.m[3] = 0;
  2471. result.m[4] = 2.0 * (xy - zw);
  2472. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2473. result.m[6] = 2.0 * (yz + xw);
  2474. result.m[7] = 0;
  2475. result.m[8] = 2.0 * (zx + yw);
  2476. result.m[9] = 2.0 * (yz - xw);
  2477. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2478. result.m[11] = 0;
  2479. result.m[12] = 0;
  2480. result.m[13] = 0;
  2481. result.m[14] = 0;
  2482. result.m[15] = 1.0;
  2483. result._markAsUpdated();
  2484. return this;
  2485. };
  2486. /**
  2487. * Updates the current Quaternion from the passed rotation matrix values.
  2488. * Returns the updated Quaternion.
  2489. */
  2490. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2491. Quaternion.FromRotationMatrixToRef(matrix, this);
  2492. return this;
  2493. };
  2494. // Statics
  2495. /**
  2496. * Returns a new Quaternion set from the passed rotation matrix values.
  2497. */
  2498. Quaternion.FromRotationMatrix = function (matrix) {
  2499. var result = new Quaternion();
  2500. Quaternion.FromRotationMatrixToRef(matrix, result);
  2501. return result;
  2502. };
  2503. /**
  2504. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2505. */
  2506. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2507. var data = matrix.m;
  2508. var m11 = data[0], m12 = data[4], m13 = data[8];
  2509. var m21 = data[1], m22 = data[5], m23 = data[9];
  2510. var m31 = data[2], m32 = data[6], m33 = data[10];
  2511. var trace = m11 + m22 + m33;
  2512. var s;
  2513. if (trace > 0) {
  2514. s = 0.5 / Math.sqrt(trace + 1.0);
  2515. result.w = 0.25 / s;
  2516. result.x = (m32 - m23) * s;
  2517. result.y = (m13 - m31) * s;
  2518. result.z = (m21 - m12) * s;
  2519. }
  2520. else if (m11 > m22 && m11 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2522. result.w = (m32 - m23) / s;
  2523. result.x = 0.25 * s;
  2524. result.y = (m12 + m21) / s;
  2525. result.z = (m13 + m31) / s;
  2526. }
  2527. else if (m22 > m33) {
  2528. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2529. result.w = (m13 - m31) / s;
  2530. result.x = (m12 + m21) / s;
  2531. result.y = 0.25 * s;
  2532. result.z = (m23 + m32) / s;
  2533. }
  2534. else {
  2535. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2536. result.w = (m21 - m12) / s;
  2537. result.x = (m13 + m31) / s;
  2538. result.y = (m23 + m32) / s;
  2539. result.z = 0.25 * s;
  2540. }
  2541. };
  2542. /**
  2543. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2544. */
  2545. Quaternion.Zero = function () {
  2546. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2547. };
  2548. /**
  2549. * Returns a new Quaternion as the inverted current Quaternion.
  2550. */
  2551. Quaternion.Inverse = function (q) {
  2552. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2553. };
  2554. /**
  2555. * Returns the identity Quaternion.
  2556. */
  2557. Quaternion.Identity = function () {
  2558. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2559. };
  2560. Quaternion.IsIdentity = function (quaternion) {
  2561. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2562. };
  2563. /**
  2564. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2565. */
  2566. Quaternion.RotationAxis = function (axis, angle) {
  2567. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2568. };
  2569. /**
  2570. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2571. */
  2572. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2573. var sin = Math.sin(angle / 2);
  2574. axis.normalize();
  2575. result.w = Math.cos(angle / 2);
  2576. result.x = axis.x * sin;
  2577. result.y = axis.y * sin;
  2578. result.z = axis.z * sin;
  2579. return result;
  2580. };
  2581. /**
  2582. * Retuns a new Quaternion set from the starting index of the passed array.
  2583. */
  2584. Quaternion.FromArray = function (array, offset) {
  2585. if (!offset) {
  2586. offset = 0;
  2587. }
  2588. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2589. };
  2590. /**
  2591. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2592. */
  2593. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2594. var q = new Quaternion();
  2595. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2596. return q;
  2597. };
  2598. /**
  2599. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2600. */
  2601. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2602. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2603. var halfRoll = roll * 0.5;
  2604. var halfPitch = pitch * 0.5;
  2605. var halfYaw = yaw * 0.5;
  2606. var sinRoll = Math.sin(halfRoll);
  2607. var cosRoll = Math.cos(halfRoll);
  2608. var sinPitch = Math.sin(halfPitch);
  2609. var cosPitch = Math.cos(halfPitch);
  2610. var sinYaw = Math.sin(halfYaw);
  2611. var cosYaw = Math.cos(halfYaw);
  2612. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2613. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2614. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2615. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2616. };
  2617. /**
  2618. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2619. */
  2620. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2621. var result = new Quaternion();
  2622. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2623. return result;
  2624. };
  2625. /**
  2626. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2627. */
  2628. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2629. // Produces a quaternion from Euler angles in the z-x-z orientation
  2630. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2631. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2632. var halfBeta = beta * 0.5;
  2633. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2634. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2635. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2636. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2637. };
  2638. /**
  2639. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2640. * cf to Vector3.RotationFromAxis() documentation.
  2641. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2642. */
  2643. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2644. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2645. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2646. return quat;
  2647. };
  2648. /**
  2649. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2650. * cf to Vector3.RotationFromAxis() documentation.
  2651. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2652. */
  2653. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2654. var rotMat = MathTmp.Matrix[0];
  2655. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2656. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2657. };
  2658. Quaternion.Slerp = function (left, right, amount) {
  2659. var result = Quaternion.Identity();
  2660. Quaternion.SlerpToRef(left, right, amount, result);
  2661. return result;
  2662. };
  2663. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2664. var num2;
  2665. var num3;
  2666. var num = amount;
  2667. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2668. var flag = false;
  2669. if (num4 < 0) {
  2670. flag = true;
  2671. num4 = -num4;
  2672. }
  2673. if (num4 > 0.999999) {
  2674. num3 = 1 - num;
  2675. num2 = flag ? -num : num;
  2676. }
  2677. else {
  2678. var num5 = Math.acos(num4);
  2679. var num6 = (1.0 / Math.sin(num5));
  2680. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2681. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2682. }
  2683. result.x = (num3 * left.x) + (num2 * right.x);
  2684. result.y = (num3 * left.y) + (num2 * right.y);
  2685. result.z = (num3 * left.z) + (num2 * right.z);
  2686. result.w = (num3 * left.w) + (num2 * right.w);
  2687. };
  2688. /**
  2689. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2690. */
  2691. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2692. var squared = amount * amount;
  2693. var cubed = amount * squared;
  2694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2696. var part3 = (cubed - (2.0 * squared)) + amount;
  2697. var part4 = cubed - squared;
  2698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2701. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2702. return new Quaternion(x, y, z, w);
  2703. };
  2704. return Quaternion;
  2705. }());
  2706. BABYLON.Quaternion = Quaternion;
  2707. var Matrix = (function () {
  2708. function Matrix() {
  2709. this.m = new Float32Array(16);
  2710. this._markAsUpdated();
  2711. }
  2712. Matrix.prototype._markAsUpdated = function () {
  2713. this.updateFlag = Matrix._updateFlagSeed++;
  2714. };
  2715. // Properties
  2716. /**
  2717. * Boolean : True is the matrix is the identity matrix
  2718. */
  2719. Matrix.prototype.isIdentity = function () {
  2720. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2721. return false;
  2722. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2726. return false;
  2727. return true;
  2728. };
  2729. /**
  2730. * Returns the matrix determinant (float).
  2731. */
  2732. Matrix.prototype.determinant = function () {
  2733. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2734. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2735. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2736. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2737. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2738. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2739. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2740. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2741. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2742. };
  2743. // Methods
  2744. /**
  2745. * Returns the matrix underlying array.
  2746. */
  2747. Matrix.prototype.toArray = function () {
  2748. return this.m;
  2749. };
  2750. /**
  2751. * Returns the matrix underlying array.
  2752. */
  2753. Matrix.prototype.asArray = function () {
  2754. return this.toArray();
  2755. };
  2756. /**
  2757. * Inverts in place the Matrix.
  2758. * Returns the Matrix inverted.
  2759. */
  2760. Matrix.prototype.invert = function () {
  2761. this.invertToRef(this);
  2762. return this;
  2763. };
  2764. /**
  2765. * Sets all the matrix elements to zero.
  2766. * Returns the Matrix.
  2767. */
  2768. Matrix.prototype.reset = function () {
  2769. for (var index = 0; index < 16; index++) {
  2770. this.m[index] = 0.0;
  2771. }
  2772. this._markAsUpdated();
  2773. return this;
  2774. };
  2775. /**
  2776. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2777. */
  2778. Matrix.prototype.add = function (other) {
  2779. var result = new Matrix();
  2780. this.addToRef(other, result);
  2781. return result;
  2782. };
  2783. /**
  2784. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2785. * Returns the Matrix.
  2786. */
  2787. Matrix.prototype.addToRef = function (other, result) {
  2788. for (var index = 0; index < 16; index++) {
  2789. result.m[index] = this.m[index] + other.m[index];
  2790. }
  2791. result._markAsUpdated();
  2792. return this;
  2793. };
  2794. /**
  2795. * Adds in place the passed matrix to the current Matrix.
  2796. * Returns the updated Matrix.
  2797. */
  2798. Matrix.prototype.addToSelf = function (other) {
  2799. for (var index = 0; index < 16; index++) {
  2800. this.m[index] += other.m[index];
  2801. }
  2802. this._markAsUpdated();
  2803. return this;
  2804. };
  2805. /**
  2806. * Sets the passed matrix with the current inverted Matrix.
  2807. * Returns the unmodified current Matrix.
  2808. */
  2809. Matrix.prototype.invertToRef = function (other) {
  2810. var l1 = this.m[0];
  2811. var l2 = this.m[1];
  2812. var l3 = this.m[2];
  2813. var l4 = this.m[3];
  2814. var l5 = this.m[4];
  2815. var l6 = this.m[5];
  2816. var l7 = this.m[6];
  2817. var l8 = this.m[7];
  2818. var l9 = this.m[8];
  2819. var l10 = this.m[9];
  2820. var l11 = this.m[10];
  2821. var l12 = this.m[11];
  2822. var l13 = this.m[12];
  2823. var l14 = this.m[13];
  2824. var l15 = this.m[14];
  2825. var l16 = this.m[15];
  2826. var l17 = (l11 * l16) - (l12 * l15);
  2827. var l18 = (l10 * l16) - (l12 * l14);
  2828. var l19 = (l10 * l15) - (l11 * l14);
  2829. var l20 = (l9 * l16) - (l12 * l13);
  2830. var l21 = (l9 * l15) - (l11 * l13);
  2831. var l22 = (l9 * l14) - (l10 * l13);
  2832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2837. var l28 = (l7 * l16) - (l8 * l15);
  2838. var l29 = (l6 * l16) - (l8 * l14);
  2839. var l30 = (l6 * l15) - (l7 * l14);
  2840. var l31 = (l5 * l16) - (l8 * l13);
  2841. var l32 = (l5 * l15) - (l7 * l13);
  2842. var l33 = (l5 * l14) - (l6 * l13);
  2843. var l34 = (l7 * l12) - (l8 * l11);
  2844. var l35 = (l6 * l12) - (l8 * l10);
  2845. var l36 = (l6 * l11) - (l7 * l10);
  2846. var l37 = (l5 * l12) - (l8 * l9);
  2847. var l38 = (l5 * l11) - (l7 * l9);
  2848. var l39 = (l5 * l10) - (l6 * l9);
  2849. other.m[0] = l23 * l27;
  2850. other.m[4] = l24 * l27;
  2851. other.m[8] = l25 * l27;
  2852. other.m[12] = l26 * l27;
  2853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2865. other._markAsUpdated();
  2866. return this;
  2867. };
  2868. /**
  2869. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2870. * Returns the updated Matrix.
  2871. */
  2872. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2873. this.m[12] = x;
  2874. this.m[13] = y;
  2875. this.m[14] = z;
  2876. this._markAsUpdated();
  2877. return this;
  2878. };
  2879. /**
  2880. * Inserts the translation vector in the current Matrix.
  2881. * Returns the updated Matrix.
  2882. */
  2883. Matrix.prototype.setTranslation = function (vector3) {
  2884. this.m[12] = vector3.x;
  2885. this.m[13] = vector3.y;
  2886. this.m[14] = vector3.z;
  2887. this._markAsUpdated();
  2888. return this;
  2889. };
  2890. /**
  2891. * Returns a new Vector3 as the extracted translation from the Matrix.
  2892. */
  2893. Matrix.prototype.getTranslation = function () {
  2894. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2895. };
  2896. /**
  2897. * Fill a Vector3 with the extracted translation from the Matrix.
  2898. */
  2899. Matrix.prototype.getTranslationToRef = function (result) {
  2900. result.x = this.m[12];
  2901. result.y = this.m[13];
  2902. result.z = this.m[14];
  2903. return this;
  2904. };
  2905. /**
  2906. * Remove rotation and scaling part from the Matrix.
  2907. * Returns the updated Matrix.
  2908. */
  2909. Matrix.prototype.removeRotationAndScaling = function () {
  2910. this.setRowFromFloats(0, 1, 0, 0, 0);
  2911. this.setRowFromFloats(1, 0, 1, 0, 0);
  2912. this.setRowFromFloats(2, 0, 0, 1, 0);
  2913. return this;
  2914. };
  2915. /**
  2916. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2917. */
  2918. Matrix.prototype.multiply = function (other) {
  2919. var result = new Matrix();
  2920. this.multiplyToRef(other, result);
  2921. return result;
  2922. };
  2923. /**
  2924. * Updates the current Matrix from the passed one values.
  2925. * Returns the updated Matrix.
  2926. */
  2927. Matrix.prototype.copyFrom = function (other) {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = other.m[index];
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Populates the passed array from the starting index with the Matrix values.
  2936. * Returns the Matrix.
  2937. */
  2938. Matrix.prototype.copyToArray = function (array, offset) {
  2939. if (offset === void 0) { offset = 0; }
  2940. for (var index = 0; index < 16; index++) {
  2941. array[offset + index] = this.m[index];
  2942. }
  2943. return this;
  2944. };
  2945. /**
  2946. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2947. */
  2948. Matrix.prototype.multiplyToRef = function (other, result) {
  2949. this.multiplyToArray(other, result.m, 0);
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2957. var tm0 = this.m[0];
  2958. var tm1 = this.m[1];
  2959. var tm2 = this.m[2];
  2960. var tm3 = this.m[3];
  2961. var tm4 = this.m[4];
  2962. var tm5 = this.m[5];
  2963. var tm6 = this.m[6];
  2964. var tm7 = this.m[7];
  2965. var tm8 = this.m[8];
  2966. var tm9 = this.m[9];
  2967. var tm10 = this.m[10];
  2968. var tm11 = this.m[11];
  2969. var tm12 = this.m[12];
  2970. var tm13 = this.m[13];
  2971. var tm14 = this.m[14];
  2972. var tm15 = this.m[15];
  2973. var om0 = other.m[0];
  2974. var om1 = other.m[1];
  2975. var om2 = other.m[2];
  2976. var om3 = other.m[3];
  2977. var om4 = other.m[4];
  2978. var om5 = other.m[5];
  2979. var om6 = other.m[6];
  2980. var om7 = other.m[7];
  2981. var om8 = other.m[8];
  2982. var om9 = other.m[9];
  2983. var om10 = other.m[10];
  2984. var om11 = other.m[11];
  2985. var om12 = other.m[12];
  2986. var om13 = other.m[13];
  2987. var om14 = other.m[14];
  2988. var om15 = other.m[15];
  2989. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2990. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2991. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2992. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2993. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2994. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2995. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2996. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2997. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2998. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2999. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3000. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3001. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3002. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3003. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3004. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3005. return this;
  3006. };
  3007. /**
  3008. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3009. */
  3010. Matrix.prototype.equals = function (value) {
  3011. return value &&
  3012. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3013. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3014. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3015. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3016. };
  3017. /**
  3018. * Returns a new Matrix from the current Matrix.
  3019. */
  3020. Matrix.prototype.clone = function () {
  3021. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3022. };
  3023. /**
  3024. * Returns the string "Matrix"
  3025. */
  3026. Matrix.prototype.getClassName = function () {
  3027. return "Matrix";
  3028. };
  3029. /**
  3030. * Returns the Matrix hash code.
  3031. */
  3032. Matrix.prototype.getHashCode = function () {
  3033. var hash = this.m[0] || 0;
  3034. for (var i = 1; i < 16; i++) {
  3035. hash = (hash * 397) ^ (this.m[i] || 0);
  3036. }
  3037. return hash;
  3038. };
  3039. /**
  3040. * Decomposes the current Matrix into :
  3041. * - a scale vector3 passed as a reference to update,
  3042. * - a rotation quaternion passed as a reference to update,
  3043. * - a translation vector3 passed as a reference to update.
  3044. * Returns the boolean `true`.
  3045. */
  3046. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3047. translation.x = this.m[12];
  3048. translation.y = this.m[13];
  3049. translation.z = this.m[14];
  3050. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3051. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3052. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3053. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3054. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3055. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3056. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3057. rotation.x = 0;
  3058. rotation.y = 0;
  3059. rotation.z = 0;
  3060. rotation.w = 1;
  3061. return false;
  3062. }
  3063. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3064. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3065. return true;
  3066. };
  3067. /**
  3068. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3069. */
  3070. Matrix.prototype.getRotationMatrix = function () {
  3071. var result = Matrix.Identity();
  3072. this.getRotationMatrixToRef(result);
  3073. return result;
  3074. };
  3075. /**
  3076. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3077. * Returns the current Matrix.
  3078. */
  3079. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3080. var m = this.m;
  3081. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3082. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3083. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3084. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3085. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3086. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3087. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3088. return this;
  3089. };
  3090. // Statics
  3091. /**
  3092. * Returns a new Matrix set from the starting index of the passed array.
  3093. */
  3094. Matrix.FromArray = function (array, offset) {
  3095. var result = new Matrix();
  3096. if (!offset) {
  3097. offset = 0;
  3098. }
  3099. Matrix.FromArrayToRef(array, offset, result);
  3100. return result;
  3101. };
  3102. /**
  3103. * Sets the passed "result" matrix from the starting index of the passed array.
  3104. */
  3105. Matrix.FromArrayToRef = function (array, offset, result) {
  3106. for (var index = 0; index < 16; index++) {
  3107. result.m[index] = array[index + offset];
  3108. }
  3109. result._markAsUpdated();
  3110. };
  3111. /**
  3112. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3113. */
  3114. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3115. for (var index = 0; index < 16; index++) {
  3116. result.m[index] = array[index + offset] * scale;
  3117. }
  3118. result._markAsUpdated();
  3119. };
  3120. /**
  3121. * Sets the passed matrix "result" with the 16 passed floats.
  3122. */
  3123. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3124. result.m[0] = initialM11;
  3125. result.m[1] = initialM12;
  3126. result.m[2] = initialM13;
  3127. result.m[3] = initialM14;
  3128. result.m[4] = initialM21;
  3129. result.m[5] = initialM22;
  3130. result.m[6] = initialM23;
  3131. result.m[7] = initialM24;
  3132. result.m[8] = initialM31;
  3133. result.m[9] = initialM32;
  3134. result.m[10] = initialM33;
  3135. result.m[11] = initialM34;
  3136. result.m[12] = initialM41;
  3137. result.m[13] = initialM42;
  3138. result.m[14] = initialM43;
  3139. result.m[15] = initialM44;
  3140. result._markAsUpdated();
  3141. };
  3142. /**
  3143. * Returns the index-th row of the current matrix as a new Vector4.
  3144. */
  3145. Matrix.prototype.getRow = function (index) {
  3146. if (index < 0 || index > 3) {
  3147. return null;
  3148. }
  3149. var i = index * 4;
  3150. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3151. };
  3152. /**
  3153. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3154. * Returns the updated Matrix.
  3155. */
  3156. Matrix.prototype.setRow = function (index, row) {
  3157. if (index < 0 || index > 3) {
  3158. return this;
  3159. }
  3160. var i = index * 4;
  3161. this.m[i + 0] = row.x;
  3162. this.m[i + 1] = row.y;
  3163. this.m[i + 2] = row.z;
  3164. this.m[i + 3] = row.w;
  3165. this._markAsUpdated();
  3166. return this;
  3167. };
  3168. /**
  3169. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3170. * Returns the updated Matrix.
  3171. */
  3172. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3173. if (index < 0 || index > 3) {
  3174. return this;
  3175. }
  3176. var i = index * 4;
  3177. this.m[i + 0] = x;
  3178. this.m[i + 1] = y;
  3179. this.m[i + 2] = z;
  3180. this.m[i + 3] = w;
  3181. this._markAsUpdated();
  3182. return this;
  3183. };
  3184. /**
  3185. * Returns a new Matrix set from the 16 passed floats.
  3186. */
  3187. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3188. var result = new Matrix();
  3189. result.m[0] = initialM11;
  3190. result.m[1] = initialM12;
  3191. result.m[2] = initialM13;
  3192. result.m[3] = initialM14;
  3193. result.m[4] = initialM21;
  3194. result.m[5] = initialM22;
  3195. result.m[6] = initialM23;
  3196. result.m[7] = initialM24;
  3197. result.m[8] = initialM31;
  3198. result.m[9] = initialM32;
  3199. result.m[10] = initialM33;
  3200. result.m[11] = initialM34;
  3201. result.m[12] = initialM41;
  3202. result.m[13] = initialM42;
  3203. result.m[14] = initialM43;
  3204. result.m[15] = initialM44;
  3205. return result;
  3206. };
  3207. /**
  3208. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3209. */
  3210. Matrix.Compose = function (scale, rotation, translation) {
  3211. var result = Matrix.Identity();
  3212. Matrix.ComposeToRef(scale, rotation, translation, result);
  3213. return result;
  3214. };
  3215. /**
  3216. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3219. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3220. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3221. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3222. result.setTranslation(translation);
  3223. };
  3224. /**
  3225. * Returns a new indentity Matrix.
  3226. */
  3227. Matrix.Identity = function () {
  3228. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3229. };
  3230. /**
  3231. * Sets the passed "result" as an identity matrix.
  3232. */
  3233. Matrix.IdentityToRef = function (result) {
  3234. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3235. };
  3236. /**
  3237. * Returns a new zero Matrix.
  3238. */
  3239. Matrix.Zero = function () {
  3240. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3241. };
  3242. /**
  3243. * Returns a new rotation matrix for "angle" radians around the X axis.
  3244. */
  3245. Matrix.RotationX = function (angle) {
  3246. var result = new Matrix();
  3247. Matrix.RotationXToRef(angle, result);
  3248. return result;
  3249. };
  3250. /**
  3251. * Returns a new Matrix as the passed inverted one.
  3252. */
  3253. Matrix.Invert = function (source) {
  3254. var result = new Matrix();
  3255. source.invertToRef(result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3260. */
  3261. Matrix.RotationXToRef = function (angle, result) {
  3262. var s = Math.sin(angle);
  3263. var c = Math.cos(angle);
  3264. result.m[0] = 1.0;
  3265. result.m[15] = 1.0;
  3266. result.m[5] = c;
  3267. result.m[10] = c;
  3268. result.m[9] = -s;
  3269. result.m[6] = s;
  3270. result.m[1] = 0.0;
  3271. result.m[2] = 0.0;
  3272. result.m[3] = 0.0;
  3273. result.m[4] = 0.0;
  3274. result.m[7] = 0.0;
  3275. result.m[8] = 0.0;
  3276. result.m[11] = 0.0;
  3277. result.m[12] = 0.0;
  3278. result.m[13] = 0.0;
  3279. result.m[14] = 0.0;
  3280. result._markAsUpdated();
  3281. };
  3282. /**
  3283. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3284. */
  3285. Matrix.RotationY = function (angle) {
  3286. var result = new Matrix();
  3287. Matrix.RotationYToRef(angle, result);
  3288. return result;
  3289. };
  3290. /**
  3291. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationYToRef = function (angle, result) {
  3294. var s = Math.sin(angle);
  3295. var c = Math.cos(angle);
  3296. result.m[5] = 1.0;
  3297. result.m[15] = 1.0;
  3298. result.m[0] = c;
  3299. result.m[2] = -s;
  3300. result.m[8] = s;
  3301. result.m[10] = c;
  3302. result.m[1] = 0.0;
  3303. result.m[3] = 0.0;
  3304. result.m[4] = 0.0;
  3305. result.m[6] = 0.0;
  3306. result.m[7] = 0.0;
  3307. result.m[9] = 0.0;
  3308. result.m[11] = 0.0;
  3309. result.m[12] = 0.0;
  3310. result.m[13] = 0.0;
  3311. result.m[14] = 0.0;
  3312. result._markAsUpdated();
  3313. };
  3314. /**
  3315. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3316. */
  3317. Matrix.RotationZ = function (angle) {
  3318. var result = new Matrix();
  3319. Matrix.RotationZToRef(angle, result);
  3320. return result;
  3321. };
  3322. /**
  3323. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZToRef = function (angle, result) {
  3326. var s = Math.sin(angle);
  3327. var c = Math.cos(angle);
  3328. result.m[10] = 1.0;
  3329. result.m[15] = 1.0;
  3330. result.m[0] = c;
  3331. result.m[1] = s;
  3332. result.m[4] = -s;
  3333. result.m[5] = c;
  3334. result.m[2] = 0.0;
  3335. result.m[3] = 0.0;
  3336. result.m[6] = 0.0;
  3337. result.m[7] = 0.0;
  3338. result.m[8] = 0.0;
  3339. result.m[9] = 0.0;
  3340. result.m[11] = 0.0;
  3341. result.m[12] = 0.0;
  3342. result.m[13] = 0.0;
  3343. result.m[14] = 0.0;
  3344. result._markAsUpdated();
  3345. };
  3346. /**
  3347. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3348. */
  3349. Matrix.RotationAxis = function (axis, angle) {
  3350. var result = Matrix.Zero();
  3351. Matrix.RotationAxisToRef(axis, angle, result);
  3352. return result;
  3353. };
  3354. /**
  3355. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3358. var s = Math.sin(-angle);
  3359. var c = Math.cos(-angle);
  3360. var c1 = 1 - c;
  3361. axis.normalize();
  3362. result.m[0] = (axis.x * axis.x) * c1 + c;
  3363. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3364. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3365. result.m[3] = 0.0;
  3366. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3367. result.m[5] = (axis.y * axis.y) * c1 + c;
  3368. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3369. result.m[7] = 0.0;
  3370. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3371. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3372. result.m[10] = (axis.z * axis.z) * c1 + c;
  3373. result.m[11] = 0.0;
  3374. result.m[15] = 1.0;
  3375. result._markAsUpdated();
  3376. };
  3377. /**
  3378. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3379. */
  3380. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3381. var result = new Matrix();
  3382. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3383. return result;
  3384. };
  3385. /**
  3386. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3389. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3390. this._tempQuaternion.toRotationMatrix(result);
  3391. };
  3392. /**
  3393. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3394. */
  3395. Matrix.Scaling = function (x, y, z) {
  3396. var result = Matrix.Zero();
  3397. Matrix.ScalingToRef(x, y, z, result);
  3398. return result;
  3399. };
  3400. /**
  3401. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.ScalingToRef = function (x, y, z, result) {
  3404. result.m[0] = x;
  3405. result.m[1] = 0.0;
  3406. result.m[2] = 0.0;
  3407. result.m[3] = 0.0;
  3408. result.m[4] = 0.0;
  3409. result.m[5] = y;
  3410. result.m[6] = 0.0;
  3411. result.m[7] = 0.0;
  3412. result.m[8] = 0.0;
  3413. result.m[9] = 0.0;
  3414. result.m[10] = z;
  3415. result.m[11] = 0.0;
  3416. result.m[12] = 0.0;
  3417. result.m[13] = 0.0;
  3418. result.m[14] = 0.0;
  3419. result.m[15] = 1.0;
  3420. result._markAsUpdated();
  3421. };
  3422. /**
  3423. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3424. */
  3425. Matrix.Translation = function (x, y, z) {
  3426. var result = Matrix.Identity();
  3427. Matrix.TranslationToRef(x, y, z, result);
  3428. return result;
  3429. };
  3430. /**
  3431. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.TranslationToRef = function (x, y, z, result) {
  3434. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3435. };
  3436. /**
  3437. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3438. */
  3439. Matrix.Lerp = function (startValue, endValue, gradient) {
  3440. var result = Matrix.Zero();
  3441. for (var index = 0; index < 16; index++) {
  3442. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3443. }
  3444. result._markAsUpdated();
  3445. return result;
  3446. };
  3447. /**
  3448. * Returns a new Matrix whose values are computed by :
  3449. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3450. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3451. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3452. */
  3453. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3454. var startScale = new Vector3(0, 0, 0);
  3455. var startRotation = new Quaternion();
  3456. var startTranslation = new Vector3(0, 0, 0);
  3457. startValue.decompose(startScale, startRotation, startTranslation);
  3458. var endScale = new Vector3(0, 0, 0);
  3459. var endRotation = new Quaternion();
  3460. var endTranslation = new Vector3(0, 0, 0);
  3461. endValue.decompose(endScale, endRotation, endTranslation);
  3462. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3463. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3464. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3465. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3466. };
  3467. /**
  3468. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3469. * This methods works for a Left-Handed system.
  3470. */
  3471. Matrix.LookAtLH = function (eye, target, up) {
  3472. var result = Matrix.Zero();
  3473. Matrix.LookAtLHToRef(eye, target, up, result);
  3474. return result;
  3475. };
  3476. /**
  3477. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3478. * This methods works for a Left-Handed system.
  3479. */
  3480. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3481. // Z axis
  3482. target.subtractToRef(eye, this._zAxis);
  3483. this._zAxis.normalize();
  3484. // X axis
  3485. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3486. if (this._xAxis.lengthSquared() === 0) {
  3487. this._xAxis.x = 1.0;
  3488. }
  3489. else {
  3490. this._xAxis.normalize();
  3491. }
  3492. // Y axis
  3493. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3494. this._yAxis.normalize();
  3495. // Eye angles
  3496. var ex = -Vector3.Dot(this._xAxis, eye);
  3497. var ey = -Vector3.Dot(this._yAxis, eye);
  3498. var ez = -Vector3.Dot(this._zAxis, eye);
  3499. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3500. };
  3501. /**
  3502. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3503. * This methods works for a Right-Handed system.
  3504. */
  3505. Matrix.LookAtRH = function (eye, target, up) {
  3506. var result = Matrix.Zero();
  3507. Matrix.LookAtRHToRef(eye, target, up, result);
  3508. return result;
  3509. };
  3510. /**
  3511. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3512. * This methods works for a Left-Handed system.
  3513. */
  3514. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3515. // Z axis
  3516. eye.subtractToRef(target, this._zAxis);
  3517. this._zAxis.normalize();
  3518. // X axis
  3519. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3520. if (this._xAxis.lengthSquared() === 0) {
  3521. this._xAxis.x = 1.0;
  3522. }
  3523. else {
  3524. this._xAxis.normalize();
  3525. }
  3526. // Y axis
  3527. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3528. this._yAxis.normalize();
  3529. // Eye angles
  3530. var ex = -Vector3.Dot(this._xAxis, eye);
  3531. var ey = -Vector3.Dot(this._yAxis, eye);
  3532. var ez = -Vector3.Dot(this._zAxis, eye);
  3533. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3534. };
  3535. /**
  3536. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3537. */
  3538. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3539. var matrix = Matrix.Zero();
  3540. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3541. return matrix;
  3542. };
  3543. /**
  3544. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3545. */
  3546. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3547. var n = znear;
  3548. var f = zfar;
  3549. var a = 2.0 / width;
  3550. var b = 2.0 / height;
  3551. var c = 2.0 / (f - n);
  3552. var d = -(f + n) / (f - n);
  3553. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3554. };
  3555. /**
  3556. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3557. */
  3558. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3559. var matrix = Matrix.Zero();
  3560. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3561. return matrix;
  3562. };
  3563. /**
  3564. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3565. */
  3566. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3567. var n = znear;
  3568. var f = zfar;
  3569. var a = 2.0 / (right - left);
  3570. var b = 2.0 / (top - bottom);
  3571. var c = 2.0 / (f - n);
  3572. var d = -(f + n) / (f - n);
  3573. var i0 = (left + right) / (left - right);
  3574. var i1 = (top + bottom) / (bottom - top);
  3575. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3576. };
  3577. /**
  3578. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3579. */
  3580. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3581. var matrix = Matrix.Zero();
  3582. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3583. return matrix;
  3584. };
  3585. /**
  3586. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3587. */
  3588. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3589. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3590. result.m[10] *= -1.0;
  3591. };
  3592. /**
  3593. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3594. */
  3595. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3596. var matrix = Matrix.Zero();
  3597. var n = znear;
  3598. var f = zfar;
  3599. var a = 2.0 * n / width;
  3600. var b = 2.0 * n / height;
  3601. var c = (f + n) / (f - n);
  3602. var d = -2.0 * f * n / (f - n);
  3603. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3604. return matrix;
  3605. };
  3606. /**
  3607. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3608. */
  3609. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3610. var matrix = Matrix.Zero();
  3611. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3616. */
  3617. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3618. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3619. var n = znear;
  3620. var f = zfar;
  3621. var t = 1.0 / (Math.tan(fov * 0.5));
  3622. var a = isVerticalFovFixed ? (t / aspect) : t;
  3623. var b = isVerticalFovFixed ? t : (t * aspect);
  3624. var c = (f + n) / (f - n);
  3625. var d = -2.0 * f * n / (f - n);
  3626. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3627. };
  3628. /**
  3629. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3630. */
  3631. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3632. var matrix = Matrix.Zero();
  3633. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3634. return matrix;
  3635. };
  3636. /**
  3637. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3638. */
  3639. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3640. //alternatively this could be expressed as:
  3641. // m = PerspectiveFovLHToRef
  3642. // m[10] *= -1.0;
  3643. // m[11] *= -1.0;
  3644. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3645. var n = znear;
  3646. var f = zfar;
  3647. var t = 1.0 / (Math.tan(fov * 0.5));
  3648. var a = isVerticalFovFixed ? (t / aspect) : t;
  3649. var b = isVerticalFovFixed ? t : (t * aspect);
  3650. var c = -(f + n) / (f - n);
  3651. var d = -2 * f * n / (f - n);
  3652. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3653. };
  3654. /**
  3655. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3656. */
  3657. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3658. if (rightHanded === void 0) { rightHanded = false; }
  3659. var rightHandedFactor = rightHanded ? -1 : 1;
  3660. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3661. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3662. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3663. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3664. var xScale = 2.0 / (leftTan + rightTan);
  3665. var yScale = 2.0 / (upTan + downTan);
  3666. result.m[0] = xScale;
  3667. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3668. result.m[5] = yScale;
  3669. result.m[6] = result.m[7] = 0.0;
  3670. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3671. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3672. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3673. result.m[10] = -zfar / (znear - zfar);
  3674. result.m[11] = 1.0 * rightHandedFactor;
  3675. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3676. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3677. // result.m[14] = (znear * zfar) / (znear - zfar);
  3678. result._markAsUpdated();
  3679. };
  3680. /**
  3681. * Returns the final transformation matrix : world * view * projection * viewport
  3682. */
  3683. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3684. var cw = viewport.width;
  3685. var ch = viewport.height;
  3686. var cx = viewport.x;
  3687. var cy = viewport.y;
  3688. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3689. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3690. };
  3691. /**
  3692. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3693. */
  3694. Matrix.GetAsMatrix2x2 = function (matrix) {
  3695. return new Float32Array([
  3696. matrix.m[0], matrix.m[1],
  3697. matrix.m[4], matrix.m[5]
  3698. ]);
  3699. };
  3700. /**
  3701. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3702. */
  3703. Matrix.GetAsMatrix3x3 = function (matrix) {
  3704. return new Float32Array([
  3705. matrix.m[0], matrix.m[1], matrix.m[2],
  3706. matrix.m[4], matrix.m[5], matrix.m[6],
  3707. matrix.m[8], matrix.m[9], matrix.m[10]
  3708. ]);
  3709. };
  3710. /**
  3711. * Compute the transpose of the passed Matrix.
  3712. * Returns a new Matrix.
  3713. */
  3714. Matrix.Transpose = function (matrix) {
  3715. var result = new Matrix();
  3716. result.m[0] = matrix.m[0];
  3717. result.m[1] = matrix.m[4];
  3718. result.m[2] = matrix.m[8];
  3719. result.m[3] = matrix.m[12];
  3720. result.m[4] = matrix.m[1];
  3721. result.m[5] = matrix.m[5];
  3722. result.m[6] = matrix.m[9];
  3723. result.m[7] = matrix.m[13];
  3724. result.m[8] = matrix.m[2];
  3725. result.m[9] = matrix.m[6];
  3726. result.m[10] = matrix.m[10];
  3727. result.m[11] = matrix.m[14];
  3728. result.m[12] = matrix.m[3];
  3729. result.m[13] = matrix.m[7];
  3730. result.m[14] = matrix.m[11];
  3731. result.m[15] = matrix.m[15];
  3732. return result;
  3733. };
  3734. /**
  3735. * Returns a new Matrix as the reflection matrix across the passed plane.
  3736. */
  3737. Matrix.Reflection = function (plane) {
  3738. var matrix = new Matrix();
  3739. Matrix.ReflectionToRef(plane, matrix);
  3740. return matrix;
  3741. };
  3742. /**
  3743. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.ReflectionToRef = function (plane, result) {
  3746. plane.normalize();
  3747. var x = plane.normal.x;
  3748. var y = plane.normal.y;
  3749. var z = plane.normal.z;
  3750. var temp = -2 * x;
  3751. var temp2 = -2 * y;
  3752. var temp3 = -2 * z;
  3753. result.m[0] = (temp * x) + 1;
  3754. result.m[1] = temp2 * x;
  3755. result.m[2] = temp3 * x;
  3756. result.m[3] = 0.0;
  3757. result.m[4] = temp * y;
  3758. result.m[5] = (temp2 * y) + 1;
  3759. result.m[6] = temp3 * y;
  3760. result.m[7] = 0.0;
  3761. result.m[8] = temp * z;
  3762. result.m[9] = temp2 * z;
  3763. result.m[10] = (temp3 * z) + 1;
  3764. result.m[11] = 0.0;
  3765. result.m[12] = temp * plane.d;
  3766. result.m[13] = temp2 * plane.d;
  3767. result.m[14] = temp3 * plane.d;
  3768. result.m[15] = 1.0;
  3769. result._markAsUpdated();
  3770. };
  3771. /**
  3772. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3773. */
  3774. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3775. result.m[0] = xaxis.x;
  3776. result.m[1] = xaxis.y;
  3777. result.m[2] = xaxis.z;
  3778. result.m[3] = 0.0;
  3779. result.m[4] = yaxis.x;
  3780. result.m[5] = yaxis.y;
  3781. result.m[6] = yaxis.z;
  3782. result.m[7] = 0.0;
  3783. result.m[8] = zaxis.x;
  3784. result.m[9] = zaxis.y;
  3785. result.m[10] = zaxis.z;
  3786. result.m[11] = 0.0;
  3787. result.m[12] = 0.0;
  3788. result.m[13] = 0.0;
  3789. result.m[14] = 0.0;
  3790. result.m[15] = 1.0;
  3791. result._markAsUpdated();
  3792. };
  3793. /**
  3794. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3795. */
  3796. Matrix.FromQuaternionToRef = function (quat, result) {
  3797. var xx = quat.x * quat.x;
  3798. var yy = quat.y * quat.y;
  3799. var zz = quat.z * quat.z;
  3800. var xy = quat.x * quat.y;
  3801. var zw = quat.z * quat.w;
  3802. var zx = quat.z * quat.x;
  3803. var yw = quat.y * quat.w;
  3804. var yz = quat.y * quat.z;
  3805. var xw = quat.x * quat.w;
  3806. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3807. result.m[1] = 2.0 * (xy + zw);
  3808. result.m[2] = 2.0 * (zx - yw);
  3809. result.m[3] = 0.0;
  3810. result.m[4] = 2.0 * (xy - zw);
  3811. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3812. result.m[6] = 2.0 * (yz + xw);
  3813. result.m[7] = 0.0;
  3814. result.m[8] = 2.0 * (zx + yw);
  3815. result.m[9] = 2.0 * (yz - xw);
  3816. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3817. result.m[11] = 0.0;
  3818. result.m[12] = 0.0;
  3819. result.m[13] = 0.0;
  3820. result.m[14] = 0.0;
  3821. result.m[15] = 1.0;
  3822. result._markAsUpdated();
  3823. };
  3824. return Matrix;
  3825. }());
  3826. Matrix._tempQuaternion = new Quaternion();
  3827. Matrix._xAxis = Vector3.Zero();
  3828. Matrix._yAxis = Vector3.Zero();
  3829. Matrix._zAxis = Vector3.Zero();
  3830. Matrix._updateFlagSeed = 0;
  3831. BABYLON.Matrix = Matrix;
  3832. var Plane = (function () {
  3833. /**
  3834. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3835. */
  3836. function Plane(a, b, c, d) {
  3837. this.normal = new Vector3(a, b, c);
  3838. this.d = d;
  3839. }
  3840. /**
  3841. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3842. */
  3843. Plane.prototype.asArray = function () {
  3844. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3845. };
  3846. // Methods
  3847. /**
  3848. * Returns a new plane copied from the current Plane.
  3849. */
  3850. Plane.prototype.clone = function () {
  3851. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3852. };
  3853. /**
  3854. * Returns the string "Plane".
  3855. */
  3856. Plane.prototype.getClassName = function () {
  3857. return "Plane";
  3858. };
  3859. /**
  3860. * Returns the Plane hash code.
  3861. */
  3862. Plane.prototype.getHashCode = function () {
  3863. var hash = this.normal.getHashCode();
  3864. hash = (hash * 397) ^ (this.d || 0);
  3865. return hash;
  3866. };
  3867. /**
  3868. * Normalize the current Plane in place.
  3869. * Returns the updated Plane.
  3870. */
  3871. Plane.prototype.normalize = function () {
  3872. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3873. var magnitude = 0.0;
  3874. if (norm !== 0) {
  3875. magnitude = 1.0 / norm;
  3876. }
  3877. this.normal.x *= magnitude;
  3878. this.normal.y *= magnitude;
  3879. this.normal.z *= magnitude;
  3880. this.d *= magnitude;
  3881. return this;
  3882. };
  3883. /**
  3884. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3885. */
  3886. Plane.prototype.transform = function (transformation) {
  3887. var transposedMatrix = Matrix.Transpose(transformation);
  3888. var x = this.normal.x;
  3889. var y = this.normal.y;
  3890. var z = this.normal.z;
  3891. var d = this.d;
  3892. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3893. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3894. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3895. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3896. return new Plane(normalX, normalY, normalZ, finalD);
  3897. };
  3898. /**
  3899. * Returns the dot product (float) of the point coordinates and the plane normal.
  3900. */
  3901. Plane.prototype.dotCoordinate = function (point) {
  3902. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3903. };
  3904. /**
  3905. * Updates the current Plane from the plane defined by the three passed points.
  3906. * Returns the updated Plane.
  3907. */
  3908. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3909. var x1 = point2.x - point1.x;
  3910. var y1 = point2.y - point1.y;
  3911. var z1 = point2.z - point1.z;
  3912. var x2 = point3.x - point1.x;
  3913. var y2 = point3.y - point1.y;
  3914. var z2 = point3.z - point1.z;
  3915. var yz = (y1 * z2) - (z1 * y2);
  3916. var xz = (z1 * x2) - (x1 * z2);
  3917. var xy = (x1 * y2) - (y1 * x2);
  3918. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3919. var invPyth;
  3920. if (pyth !== 0) {
  3921. invPyth = 1.0 / pyth;
  3922. }
  3923. else {
  3924. invPyth = 0.0;
  3925. }
  3926. this.normal.x = yz * invPyth;
  3927. this.normal.y = xz * invPyth;
  3928. this.normal.z = xy * invPyth;
  3929. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3930. return this;
  3931. };
  3932. /**
  3933. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3934. */
  3935. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3936. var dot = Vector3.Dot(this.normal, direction);
  3937. return (dot <= epsilon);
  3938. };
  3939. /**
  3940. * Returns the signed distance (float) from the passed point to the Plane.
  3941. */
  3942. Plane.prototype.signedDistanceTo = function (point) {
  3943. return Vector3.Dot(point, this.normal) + this.d;
  3944. };
  3945. // Statics
  3946. /**
  3947. * Returns a new Plane from the passed array.
  3948. */
  3949. Plane.FromArray = function (array) {
  3950. return new Plane(array[0], array[1], array[2], array[3]);
  3951. };
  3952. /**
  3953. * Returns a new Plane defined by the three passed points.
  3954. */
  3955. Plane.FromPoints = function (point1, point2, point3) {
  3956. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3957. result.copyFromPoints(point1, point2, point3);
  3958. return result;
  3959. };
  3960. /**
  3961. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3962. * Note : the vector "normal" is updated because normalized.
  3963. */
  3964. Plane.FromPositionAndNormal = function (origin, normal) {
  3965. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3966. normal.normalize();
  3967. result.normal = normal;
  3968. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3969. return result;
  3970. };
  3971. /**
  3972. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3973. */
  3974. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3975. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3976. return Vector3.Dot(point, normal) + d;
  3977. };
  3978. return Plane;
  3979. }());
  3980. BABYLON.Plane = Plane;
  3981. var Viewport = (function () {
  3982. /**
  3983. * Creates a Viewport object located at (x, y) and sized (width, height).
  3984. */
  3985. function Viewport(x, y, width, height) {
  3986. this.x = x;
  3987. this.y = y;
  3988. this.width = width;
  3989. this.height = height;
  3990. }
  3991. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3992. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3993. };
  3994. /**
  3995. * Returns a new Viewport copied from the current one.
  3996. */
  3997. Viewport.prototype.clone = function () {
  3998. return new Viewport(this.x, this.y, this.width, this.height);
  3999. };
  4000. return Viewport;
  4001. }());
  4002. BABYLON.Viewport = Viewport;
  4003. var Frustum = (function () {
  4004. function Frustum() {
  4005. }
  4006. /**
  4007. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4008. */
  4009. Frustum.GetPlanes = function (transform) {
  4010. var frustumPlanes = [];
  4011. for (var index = 0; index < 6; index++) {
  4012. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4013. }
  4014. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4015. return frustumPlanes;
  4016. };
  4017. /**
  4018. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4019. */
  4020. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4021. // Near
  4022. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4023. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4024. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4025. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4026. frustumPlanes[0].normalize();
  4027. // Far
  4028. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4029. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4030. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4031. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4032. frustumPlanes[1].normalize();
  4033. // Left
  4034. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4035. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4036. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4037. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4038. frustumPlanes[2].normalize();
  4039. // Right
  4040. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4041. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4042. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4043. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4044. frustumPlanes[3].normalize();
  4045. // Top
  4046. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4047. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4048. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4049. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4050. frustumPlanes[4].normalize();
  4051. // Bottom
  4052. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4053. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4054. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4055. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4056. frustumPlanes[5].normalize();
  4057. };
  4058. return Frustum;
  4059. }());
  4060. BABYLON.Frustum = Frustum;
  4061. var Space;
  4062. (function (Space) {
  4063. Space[Space["LOCAL"] = 0] = "LOCAL";
  4064. Space[Space["WORLD"] = 1] = "WORLD";
  4065. Space[Space["BONE"] = 2] = "BONE";
  4066. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4067. var Axis = (function () {
  4068. function Axis() {
  4069. }
  4070. return Axis;
  4071. }());
  4072. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4073. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4074. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4075. BABYLON.Axis = Axis;
  4076. ;
  4077. var BezierCurve = (function () {
  4078. function BezierCurve() {
  4079. }
  4080. /**
  4081. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4082. */
  4083. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4084. // Extract X (which is equal to time here)
  4085. var f0 = 1 - 3 * x2 + 3 * x1;
  4086. var f1 = 3 * x2 - 6 * x1;
  4087. var f2 = 3 * x1;
  4088. var refinedT = t;
  4089. for (var i = 0; i < 5; i++) {
  4090. var refinedT2 = refinedT * refinedT;
  4091. var refinedT3 = refinedT2 * refinedT;
  4092. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4093. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4094. refinedT -= (x - t) * slope;
  4095. refinedT = Math.min(1, Math.max(0, refinedT));
  4096. }
  4097. // Resolve cubic bezier for the given x
  4098. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4099. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4100. Math.pow(refinedT, 3);
  4101. };
  4102. return BezierCurve;
  4103. }());
  4104. BABYLON.BezierCurve = BezierCurve;
  4105. var Orientation;
  4106. (function (Orientation) {
  4107. Orientation[Orientation["CW"] = 0] = "CW";
  4108. Orientation[Orientation["CCW"] = 1] = "CCW";
  4109. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4110. var Angle = (function () {
  4111. /**
  4112. * Creates an Angle object of "radians" radians (float).
  4113. */
  4114. function Angle(radians) {
  4115. var _this = this;
  4116. /**
  4117. * Returns the Angle value in degrees (float).
  4118. */
  4119. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4120. /**
  4121. * Returns the Angle value in radians (float).
  4122. */
  4123. this.radians = function () { return _this._radians; };
  4124. this._radians = radians;
  4125. if (this._radians < 0.0)
  4126. this._radians += (2.0 * Math.PI);
  4127. }
  4128. /**
  4129. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4130. */
  4131. Angle.BetweenTwoPoints = function (a, b) {
  4132. var delta = b.subtract(a);
  4133. var theta = Math.atan2(delta.y, delta.x);
  4134. return new Angle(theta);
  4135. };
  4136. /**
  4137. * Returns a new Angle object from the passed float in radians.
  4138. */
  4139. Angle.FromRadians = function (radians) {
  4140. return new Angle(radians);
  4141. };
  4142. /**
  4143. * Returns a new Angle object from the passed float in degrees.
  4144. */
  4145. Angle.FromDegrees = function (degrees) {
  4146. return new Angle(degrees * Math.PI / 180.0);
  4147. };
  4148. return Angle;
  4149. }());
  4150. BABYLON.Angle = Angle;
  4151. var Arc2 = (function () {
  4152. /**
  4153. * Creates an Arc object from the three passed points : start, middle and end.
  4154. */
  4155. function Arc2(startPoint, midPoint, endPoint) {
  4156. this.startPoint = startPoint;
  4157. this.midPoint = midPoint;
  4158. this.endPoint = endPoint;
  4159. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4160. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4161. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4162. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4163. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4164. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4165. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4166. var a1 = this.startAngle.degrees();
  4167. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4168. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4169. // angles correction
  4170. if (a2 - a1 > +180.0)
  4171. a2 -= 360.0;
  4172. if (a2 - a1 < -180.0)
  4173. a2 += 360.0;
  4174. if (a3 - a2 > +180.0)
  4175. a3 -= 360.0;
  4176. if (a3 - a2 < -180.0)
  4177. a3 += 360.0;
  4178. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4179. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4180. }
  4181. return Arc2;
  4182. }());
  4183. BABYLON.Arc2 = Arc2;
  4184. var Path2 = (function () {
  4185. /**
  4186. * Creates a Path2 object from the starting 2D coordinates x and y.
  4187. */
  4188. function Path2(x, y) {
  4189. this._points = new Array();
  4190. this._length = 0.0;
  4191. this.closed = false;
  4192. this._points.push(new Vector2(x, y));
  4193. }
  4194. /**
  4195. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4196. * Returns the updated Path2.
  4197. */
  4198. Path2.prototype.addLineTo = function (x, y) {
  4199. if (closed) {
  4200. //Tools.Error("cannot add lines to closed paths");
  4201. return this;
  4202. }
  4203. var newPoint = new Vector2(x, y);
  4204. var previousPoint = this._points[this._points.length - 1];
  4205. this._points.push(newPoint);
  4206. this._length += newPoint.subtract(previousPoint).length();
  4207. return this;
  4208. };
  4209. /**
  4210. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4211. * Returns the updated Path2.
  4212. */
  4213. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4214. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4215. if (closed) {
  4216. //Tools.Error("cannot add arcs to closed paths");
  4217. return this;
  4218. }
  4219. var startPoint = this._points[this._points.length - 1];
  4220. var midPoint = new Vector2(midX, midY);
  4221. var endPoint = new Vector2(endX, endY);
  4222. var arc = new Arc2(startPoint, midPoint, endPoint);
  4223. var increment = arc.angle.radians() / numberOfSegments;
  4224. if (arc.orientation === Orientation.CW)
  4225. increment *= -1;
  4226. var currentAngle = arc.startAngle.radians() + increment;
  4227. for (var i = 0; i < numberOfSegments; i++) {
  4228. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4229. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4230. this.addLineTo(x, y);
  4231. currentAngle += increment;
  4232. }
  4233. return this;
  4234. };
  4235. /**
  4236. * Closes the Path2.
  4237. * Returns the Path2.
  4238. */
  4239. Path2.prototype.close = function () {
  4240. this.closed = true;
  4241. return this;
  4242. };
  4243. /**
  4244. * Returns the Path2 total length (float).
  4245. */
  4246. Path2.prototype.length = function () {
  4247. var result = this._length;
  4248. if (!this.closed) {
  4249. var lastPoint = this._points[this._points.length - 1];
  4250. var firstPoint = this._points[0];
  4251. result += (firstPoint.subtract(lastPoint).length());
  4252. }
  4253. return result;
  4254. };
  4255. /**
  4256. * Returns the Path2 internal array of points.
  4257. */
  4258. Path2.prototype.getPoints = function () {
  4259. return this._points;
  4260. };
  4261. /**
  4262. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4263. */
  4264. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4265. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4266. //Tools.Error("normalized length position should be between 0 and 1.");
  4267. return Vector2.Zero();
  4268. }
  4269. var lengthPosition = normalizedLengthPosition * this.length();
  4270. var previousOffset = 0;
  4271. for (var i = 0; i < this._points.length; i++) {
  4272. var j = (i + 1) % this._points.length;
  4273. var a = this._points[i];
  4274. var b = this._points[j];
  4275. var bToA = b.subtract(a);
  4276. var nextOffset = (bToA.length() + previousOffset);
  4277. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4278. var dir = bToA.normalize();
  4279. var localOffset = lengthPosition - previousOffset;
  4280. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4281. }
  4282. previousOffset = nextOffset;
  4283. }
  4284. //Tools.Error("internal error");
  4285. return Vector2.Zero();
  4286. };
  4287. /**
  4288. * Returns a new Path2 starting at the coordinates (x, y).
  4289. */
  4290. Path2.StartingAt = function (x, y) {
  4291. return new Path2(x, y);
  4292. };
  4293. return Path2;
  4294. }());
  4295. BABYLON.Path2 = Path2;
  4296. var Path3D = (function () {
  4297. /**
  4298. * new Path3D(path, normal, raw)
  4299. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4300. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4301. * path : an array of Vector3, the curve axis of the Path3D
  4302. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4303. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4304. */
  4305. function Path3D(path, firstNormal, raw) {
  4306. this.path = path;
  4307. this._curve = new Array();
  4308. this._distances = new Array();
  4309. this._tangents = new Array();
  4310. this._normals = new Array();
  4311. this._binormals = new Array();
  4312. for (var p = 0; p < path.length; p++) {
  4313. this._curve[p] = path[p].clone(); // hard copy
  4314. }
  4315. this._raw = raw || false;
  4316. this._compute(firstNormal);
  4317. }
  4318. /**
  4319. * Returns the Path3D array of successive Vector3 designing its curve.
  4320. */
  4321. Path3D.prototype.getCurve = function () {
  4322. return this._curve;
  4323. };
  4324. /**
  4325. * Returns an array populated with tangent vectors on each Path3D curve point.
  4326. */
  4327. Path3D.prototype.getTangents = function () {
  4328. return this._tangents;
  4329. };
  4330. /**
  4331. * Returns an array populated with normal vectors on each Path3D curve point.
  4332. */
  4333. Path3D.prototype.getNormals = function () {
  4334. return this._normals;
  4335. };
  4336. /**
  4337. * Returns an array populated with binormal vectors on each Path3D curve point.
  4338. */
  4339. Path3D.prototype.getBinormals = function () {
  4340. return this._binormals;
  4341. };
  4342. /**
  4343. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4344. */
  4345. Path3D.prototype.getDistances = function () {
  4346. return this._distances;
  4347. };
  4348. /**
  4349. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4350. * Returns the same object updated.
  4351. */
  4352. Path3D.prototype.update = function (path, firstNormal) {
  4353. for (var p = 0; p < path.length; p++) {
  4354. this._curve[p].x = path[p].x;
  4355. this._curve[p].y = path[p].y;
  4356. this._curve[p].z = path[p].z;
  4357. }
  4358. this._compute(firstNormal);
  4359. return this;
  4360. };
  4361. // private function compute() : computes tangents, normals and binormals
  4362. Path3D.prototype._compute = function (firstNormal) {
  4363. var l = this._curve.length;
  4364. // first and last tangents
  4365. this._tangents[0] = this._getFirstNonNullVector(0);
  4366. if (!this._raw) {
  4367. this._tangents[0].normalize();
  4368. }
  4369. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4370. if (!this._raw) {
  4371. this._tangents[l - 1].normalize();
  4372. }
  4373. // normals and binormals at first point : arbitrary vector with _normalVector()
  4374. var tg0 = this._tangents[0];
  4375. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4376. this._normals[0] = pp0;
  4377. if (!this._raw) {
  4378. this._normals[0].normalize();
  4379. }
  4380. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4381. if (!this._raw) {
  4382. this._binormals[0].normalize();
  4383. }
  4384. this._distances[0] = 0.0;
  4385. // normals and binormals : next points
  4386. var prev; // previous vector (segment)
  4387. var cur; // current vector (segment)
  4388. var curTang; // current tangent
  4389. // previous normal
  4390. var prevBinor; // previous binormal
  4391. for (var i = 1; i < l; i++) {
  4392. // tangents
  4393. prev = this._getLastNonNullVector(i);
  4394. if (i < l - 1) {
  4395. cur = this._getFirstNonNullVector(i);
  4396. this._tangents[i] = prev.add(cur);
  4397. this._tangents[i].normalize();
  4398. }
  4399. this._distances[i] = this._distances[i - 1] + prev.length();
  4400. // normals and binormals
  4401. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4402. curTang = this._tangents[i];
  4403. prevBinor = this._binormals[i - 1];
  4404. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4405. if (!this._raw) {
  4406. this._normals[i].normalize();
  4407. }
  4408. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4409. if (!this._raw) {
  4410. this._binormals[i].normalize();
  4411. }
  4412. }
  4413. };
  4414. // private function getFirstNonNullVector(index)
  4415. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4416. Path3D.prototype._getFirstNonNullVector = function (index) {
  4417. var i = 1;
  4418. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4419. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4420. i++;
  4421. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4422. }
  4423. return nNVector;
  4424. };
  4425. // private function getLastNonNullVector(index)
  4426. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4427. Path3D.prototype._getLastNonNullVector = function (index) {
  4428. var i = 1;
  4429. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4430. while (nLVector.length() === 0 && index > i + 1) {
  4431. i++;
  4432. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4433. }
  4434. return nLVector;
  4435. };
  4436. // private function normalVector(v0, vt, va) :
  4437. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4438. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4439. Path3D.prototype._normalVector = function (v0, vt, va) {
  4440. var normal0;
  4441. var tgl = vt.length();
  4442. if (tgl === 0.0) {
  4443. tgl = 1.0;
  4444. }
  4445. if (va === undefined || va === null) {
  4446. var point;
  4447. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4448. point = new Vector3(0.0, -1.0, 0.0);
  4449. }
  4450. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4451. point = new Vector3(1.0, 0.0, 0.0);
  4452. }
  4453. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4454. point = new Vector3(0.0, 0.0, 1.0);
  4455. }
  4456. normal0 = Vector3.Cross(vt, point);
  4457. }
  4458. else {
  4459. normal0 = Vector3.Cross(vt, va);
  4460. Vector3.CrossToRef(normal0, vt, normal0);
  4461. }
  4462. normal0.normalize();
  4463. return normal0;
  4464. };
  4465. return Path3D;
  4466. }());
  4467. BABYLON.Path3D = Path3D;
  4468. var Curve3 = (function () {
  4469. /**
  4470. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4471. * A Curve3 is designed from a series of successive Vector3.
  4472. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4473. */
  4474. function Curve3(points) {
  4475. this._length = 0.0;
  4476. this._points = points;
  4477. this._length = this._computeLength(points);
  4478. }
  4479. /**
  4480. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4481. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4482. * @param v1 (Vector3) the control point
  4483. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4484. * @param nbPoints (integer) the wanted number of points in the curve
  4485. */
  4486. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4487. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4488. var bez = new Array();
  4489. var equation = function (t, val0, val1, val2) {
  4490. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4491. return res;
  4492. };
  4493. for (var i = 0; i <= nbPoints; i++) {
  4494. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4495. }
  4496. return new Curve3(bez);
  4497. };
  4498. /**
  4499. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4500. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4501. * @param v1 (Vector3) the first control point
  4502. * @param v2 (Vector3) the second control point
  4503. * @param v3 (Vector3) the end point of the Cubic Bezier
  4504. * @param nbPoints (integer) the wanted number of points in the curve
  4505. */
  4506. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4507. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4508. var bez = new Array();
  4509. var equation = function (t, val0, val1, val2, val3) {
  4510. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4511. return res;
  4512. };
  4513. for (var i = 0; i <= nbPoints; i++) {
  4514. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4515. }
  4516. return new Curve3(bez);
  4517. };
  4518. /**
  4519. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4520. * @param p1 (Vector3) the origin point of the Hermite Spline
  4521. * @param t1 (Vector3) the tangent vector at the origin point
  4522. * @param p2 (Vector3) the end point of the Hermite Spline
  4523. * @param t2 (Vector3) the tangent vector at the end point
  4524. * @param nbPoints (integer) the wanted number of points in the curve
  4525. */
  4526. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4527. var hermite = new Array();
  4528. var step = 1.0 / nbPoints;
  4529. for (var i = 0; i <= nbPoints; i++) {
  4530. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4531. }
  4532. return new Curve3(hermite);
  4533. };
  4534. /**
  4535. * Returns a Curve3 object along a CatmullRom Spline curve :
  4536. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4537. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4538. */
  4539. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4540. var totalPoints = new Array();
  4541. totalPoints.push(points[0].clone());
  4542. Array.prototype.push.apply(totalPoints, points);
  4543. totalPoints.push(points[points.length - 1].clone());
  4544. var catmullRom = new Array();
  4545. var step = 1.0 / nbPoints;
  4546. for (var i = 0; i < totalPoints.length - 3; i++) {
  4547. var amount = 0.0;
  4548. for (var c = 0; c < nbPoints; c++) {
  4549. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4550. amount += step;
  4551. }
  4552. }
  4553. i--;
  4554. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4555. return new Curve3(catmullRom);
  4556. };
  4557. /**
  4558. * Returns the Curve3 stored array of successive Vector3
  4559. */
  4560. Curve3.prototype.getPoints = function () {
  4561. return this._points;
  4562. };
  4563. /**
  4564. * Returns the computed length (float) of the curve.
  4565. */
  4566. Curve3.prototype.length = function () {
  4567. return this._length;
  4568. };
  4569. /**
  4570. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4571. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4572. * curveA and curveB keep unchanged.
  4573. */
  4574. Curve3.prototype.continue = function (curve) {
  4575. var lastPoint = this._points[this._points.length - 1];
  4576. var continuedPoints = this._points.slice();
  4577. var curvePoints = curve.getPoints();
  4578. for (var i = 1; i < curvePoints.length; i++) {
  4579. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4580. }
  4581. var continuedCurve = new Curve3(continuedPoints);
  4582. return continuedCurve;
  4583. };
  4584. Curve3.prototype._computeLength = function (path) {
  4585. var l = 0;
  4586. for (var i = 1; i < path.length; i++) {
  4587. l += (path[i].subtract(path[i - 1])).length();
  4588. }
  4589. return l;
  4590. };
  4591. return Curve3;
  4592. }());
  4593. BABYLON.Curve3 = Curve3;
  4594. // SphericalHarmonics
  4595. var SphericalHarmonics = (function () {
  4596. function SphericalHarmonics() {
  4597. this.L00 = Vector3.Zero();
  4598. this.L1_1 = Vector3.Zero();
  4599. this.L10 = Vector3.Zero();
  4600. this.L11 = Vector3.Zero();
  4601. this.L2_2 = Vector3.Zero();
  4602. this.L2_1 = Vector3.Zero();
  4603. this.L20 = Vector3.Zero();
  4604. this.L21 = Vector3.Zero();
  4605. this.L22 = Vector3.Zero();
  4606. }
  4607. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4608. var colorVector = new Vector3(color.r, color.g, color.b);
  4609. var c = colorVector.scale(deltaSolidAngle);
  4610. this.L00 = this.L00.add(c.scale(0.282095));
  4611. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4612. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4613. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4614. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4615. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4616. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4617. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4618. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4619. };
  4620. SphericalHarmonics.prototype.scale = function (scale) {
  4621. this.L00 = this.L00.scale(scale);
  4622. this.L1_1 = this.L1_1.scale(scale);
  4623. this.L10 = this.L10.scale(scale);
  4624. this.L11 = this.L11.scale(scale);
  4625. this.L2_2 = this.L2_2.scale(scale);
  4626. this.L2_1 = this.L2_1.scale(scale);
  4627. this.L20 = this.L20.scale(scale);
  4628. this.L21 = this.L21.scale(scale);
  4629. this.L22 = this.L22.scale(scale);
  4630. };
  4631. return SphericalHarmonics;
  4632. }());
  4633. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4634. // SphericalPolynomial
  4635. var SphericalPolynomial = (function () {
  4636. function SphericalPolynomial() {
  4637. this.x = Vector3.Zero();
  4638. this.y = Vector3.Zero();
  4639. this.z = Vector3.Zero();
  4640. this.xx = Vector3.Zero();
  4641. this.yy = Vector3.Zero();
  4642. this.zz = Vector3.Zero();
  4643. this.xy = Vector3.Zero();
  4644. this.yz = Vector3.Zero();
  4645. this.zx = Vector3.Zero();
  4646. }
  4647. SphericalPolynomial.prototype.addAmbient = function (color) {
  4648. var colorVector = new Vector3(color.r, color.g, color.b);
  4649. this.xx = this.xx.add(colorVector);
  4650. this.yy = this.yy.add(colorVector);
  4651. this.zz = this.zz.add(colorVector);
  4652. };
  4653. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4654. var result = new SphericalPolynomial();
  4655. result.x = harmonics.L11.scale(1.02333);
  4656. result.y = harmonics.L1_1.scale(1.02333);
  4657. result.z = harmonics.L10.scale(1.02333);
  4658. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4659. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4660. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4661. result.yz = harmonics.L2_1.scale(0.858086);
  4662. result.zx = harmonics.L21.scale(0.858086);
  4663. result.xy = harmonics.L2_2.scale(0.858086);
  4664. return result;
  4665. };
  4666. return SphericalPolynomial;
  4667. }());
  4668. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4669. // Vertex formats
  4670. var PositionNormalVertex = (function () {
  4671. function PositionNormalVertex(position, normal) {
  4672. if (position === void 0) { position = Vector3.Zero(); }
  4673. if (normal === void 0) { normal = Vector3.Up(); }
  4674. this.position = position;
  4675. this.normal = normal;
  4676. }
  4677. PositionNormalVertex.prototype.clone = function () {
  4678. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4679. };
  4680. return PositionNormalVertex;
  4681. }());
  4682. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4683. var PositionNormalTextureVertex = (function () {
  4684. function PositionNormalTextureVertex(position, normal, uv) {
  4685. if (position === void 0) { position = Vector3.Zero(); }
  4686. if (normal === void 0) { normal = Vector3.Up(); }
  4687. if (uv === void 0) { uv = Vector2.Zero(); }
  4688. this.position = position;
  4689. this.normal = normal;
  4690. this.uv = uv;
  4691. }
  4692. PositionNormalTextureVertex.prototype.clone = function () {
  4693. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4694. };
  4695. return PositionNormalTextureVertex;
  4696. }());
  4697. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4698. // Temporary pre-allocated objects for engine internal use
  4699. // usage in any internal function :
  4700. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4701. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4702. var Tmp = (function () {
  4703. function Tmp() {
  4704. }
  4705. return Tmp;
  4706. }());
  4707. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4708. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4709. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4710. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4711. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4712. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4713. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4714. Matrix.Zero(), Matrix.Zero(),
  4715. Matrix.Zero(), Matrix.Zero(),
  4716. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4717. BABYLON.Tmp = Tmp;
  4718. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4719. var MathTmp = (function () {
  4720. function MathTmp() {
  4721. }
  4722. return MathTmp;
  4723. }());
  4724. MathTmp.Vector3 = [Vector3.Zero()];
  4725. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4726. MathTmp.Quaternion = [Quaternion.Zero()];
  4727. })(BABYLON || (BABYLON = {}));
  4728. //# sourceMappingURL=babylon.math.js.map
  4729. //# sourceMappingURL=babylon.mixins.js.map
  4730. var BABYLON;
  4731. (function (BABYLON) {
  4732. function generateSerializableMember(type, sourceName) {
  4733. return function (target, propertyKey) {
  4734. if (!target.__serializableMembers) {
  4735. target.__serializableMembers = {};
  4736. }
  4737. if (!target.__serializableMembers[propertyKey]) {
  4738. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4739. }
  4740. };
  4741. }
  4742. function generateExpandMember(setCallback, targetKey) {
  4743. return function (target, propertyKey) {
  4744. var key = targetKey || ("_" + propertyKey);
  4745. Object.defineProperty(target, propertyKey, {
  4746. get: function () {
  4747. return this[key];
  4748. },
  4749. set: function (value) {
  4750. if (this[key] === value) {
  4751. return;
  4752. }
  4753. this[key] = value;
  4754. if (setCallback) {
  4755. target[setCallback].apply(this);
  4756. }
  4757. },
  4758. enumerable: true,
  4759. configurable: true
  4760. });
  4761. };
  4762. }
  4763. function expandToProperty(callback, targetKey) {
  4764. return generateExpandMember(callback, targetKey);
  4765. }
  4766. BABYLON.expandToProperty = expandToProperty;
  4767. function serialize(sourceName) {
  4768. return generateSerializableMember(0, sourceName); // value member
  4769. }
  4770. BABYLON.serialize = serialize;
  4771. function serializeAsTexture(sourceName) {
  4772. return generateSerializableMember(1, sourceName); // texture member
  4773. }
  4774. BABYLON.serializeAsTexture = serializeAsTexture;
  4775. function serializeAsColor3(sourceName) {
  4776. return generateSerializableMember(2, sourceName); // color3 member
  4777. }
  4778. BABYLON.serializeAsColor3 = serializeAsColor3;
  4779. function serializeAsFresnelParameters(sourceName) {
  4780. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4781. }
  4782. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4783. function serializeAsVector2(sourceName) {
  4784. return generateSerializableMember(4, sourceName); // vector2 member
  4785. }
  4786. BABYLON.serializeAsVector2 = serializeAsVector2;
  4787. function serializeAsVector3(sourceName) {
  4788. return generateSerializableMember(5, sourceName); // vector3 member
  4789. }
  4790. BABYLON.serializeAsVector3 = serializeAsVector3;
  4791. function serializeAsMeshReference(sourceName) {
  4792. return generateSerializableMember(6, sourceName); // mesh reference member
  4793. }
  4794. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4795. function serializeAsColorCurves(sourceName) {
  4796. return generateSerializableMember(7, sourceName); // color curves
  4797. }
  4798. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4799. var SerializationHelper = (function () {
  4800. function SerializationHelper() {
  4801. }
  4802. SerializationHelper.Serialize = function (entity, serializationObject) {
  4803. if (!serializationObject) {
  4804. serializationObject = {};
  4805. }
  4806. // Tags
  4807. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4808. // Properties
  4809. for (var property in entity.__serializableMembers) {
  4810. var propertyDescriptor = entity.__serializableMembers[property];
  4811. var targetPropertyName = propertyDescriptor.sourceName || property;
  4812. var propertyType = propertyDescriptor.type;
  4813. var sourceProperty = entity[property];
  4814. if (sourceProperty !== undefined && sourceProperty !== null) {
  4815. switch (propertyType) {
  4816. case 0:
  4817. serializationObject[targetPropertyName] = sourceProperty;
  4818. break;
  4819. case 1:
  4820. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4821. break;
  4822. case 2:
  4823. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4824. break;
  4825. case 3:
  4826. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4827. break;
  4828. case 4:
  4829. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4830. break;
  4831. case 5:
  4832. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4833. break;
  4834. case 6:
  4835. serializationObject[targetPropertyName] = sourceProperty.id;
  4836. break;
  4837. case 7:
  4838. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4839. break;
  4840. }
  4841. }
  4842. }
  4843. return serializationObject;
  4844. };
  4845. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4846. var destination = creationFunction();
  4847. // Tags
  4848. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4849. // Properties
  4850. for (var property in destination.__serializableMembers) {
  4851. var propertyDescriptor = destination.__serializableMembers[property];
  4852. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4853. var propertyType = propertyDescriptor.type;
  4854. if (sourceProperty !== undefined && sourceProperty !== null) {
  4855. switch (propertyType) {
  4856. case 0:
  4857. destination[property] = sourceProperty;
  4858. break;
  4859. case 1:
  4860. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4861. break;
  4862. case 2:
  4863. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4864. break;
  4865. case 3:
  4866. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4867. break;
  4868. case 4:
  4869. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4870. break;
  4871. case 5:
  4872. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4873. break;
  4874. case 6:
  4875. destination[property] = scene.getLastMeshByID(sourceProperty);
  4876. break;
  4877. case 7:
  4878. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4879. break;
  4880. }
  4881. }
  4882. }
  4883. return destination;
  4884. };
  4885. SerializationHelper.Clone = function (creationFunction, source) {
  4886. var destination = creationFunction();
  4887. // Tags
  4888. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4889. // Properties
  4890. for (var property in destination.__serializableMembers) {
  4891. var propertyDescriptor = destination.__serializableMembers[property];
  4892. var sourceProperty = source[property];
  4893. var propertyType = propertyDescriptor.type;
  4894. if (sourceProperty !== undefined && sourceProperty !== null) {
  4895. switch (propertyType) {
  4896. case 0: // Value
  4897. case 6:
  4898. destination[property] = sourceProperty;
  4899. break;
  4900. case 1: // Texture
  4901. case 2: // Color3
  4902. case 3: // FresnelParameters
  4903. case 4: // Vector2
  4904. case 5: // Vector3
  4905. case 7:
  4906. destination[property] = sourceProperty.clone();
  4907. break;
  4908. }
  4909. }
  4910. }
  4911. return destination;
  4912. };
  4913. return SerializationHelper;
  4914. }());
  4915. BABYLON.SerializationHelper = SerializationHelper;
  4916. })(BABYLON || (BABYLON = {}));
  4917. //# sourceMappingURL=babylon.decorators.js.map
  4918. var BABYLON;
  4919. (function (BABYLON) {
  4920. /**
  4921. * A class serves as a medium between the observable and its observers
  4922. */
  4923. var EventState = (function () {
  4924. /**
  4925. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4926. */
  4927. function EventState(mask, skipNextObservers) {
  4928. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4929. this.initalize(mask, skipNextObservers);
  4930. }
  4931. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4932. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4933. this.mask = mask;
  4934. this.skipNextObservers = skipNextObservers;
  4935. return this;
  4936. };
  4937. return EventState;
  4938. }());
  4939. BABYLON.EventState = EventState;
  4940. /**
  4941. * Represent an Observer registered to a given Observable object.
  4942. */
  4943. var Observer = (function () {
  4944. function Observer(callback, mask) {
  4945. this.callback = callback;
  4946. this.mask = mask;
  4947. }
  4948. return Observer;
  4949. }());
  4950. BABYLON.Observer = Observer;
  4951. /**
  4952. * The Observable class is a simple implementation of the Observable pattern.
  4953. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  4954. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4955. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  4956. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  4957. */
  4958. var Observable = (function () {
  4959. function Observable() {
  4960. this._observers = new Array();
  4961. this._eventState = new EventState(0);
  4962. }
  4963. /**
  4964. * Create a new Observer with the specified callback
  4965. * @param callback the callback that will be executed for that Observer
  4966. * @param mask the mask used to filter observers
  4967. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  4968. */
  4969. Observable.prototype.add = function (callback, mask, insertFirst) {
  4970. if (mask === void 0) { mask = -1; }
  4971. if (insertFirst === void 0) { insertFirst = false; }
  4972. if (!callback) {
  4973. return null;
  4974. }
  4975. var observer = new Observer(callback, mask);
  4976. if (insertFirst) {
  4977. this._observers.unshift(observer);
  4978. }
  4979. else {
  4980. this._observers.push(observer);
  4981. }
  4982. return observer;
  4983. };
  4984. /**
  4985. * Remove an Observer from the Observable object
  4986. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4987. */
  4988. Observable.prototype.remove = function (observer) {
  4989. var index = this._observers.indexOf(observer);
  4990. if (index !== -1) {
  4991. this._observers.splice(index, 1);
  4992. return true;
  4993. }
  4994. return false;
  4995. };
  4996. /**
  4997. * Remove a callback from the Observable object
  4998. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4999. */
  5000. Observable.prototype.removeCallback = function (callback) {
  5001. for (var index = 0; index < this._observers.length; index++) {
  5002. if (this._observers[index].callback === callback) {
  5003. this._observers.splice(index, 1);
  5004. return true;
  5005. }
  5006. }
  5007. return false;
  5008. };
  5009. /**
  5010. * Notify all Observers by calling their respective callback with the given data
  5011. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5012. * @param eventData
  5013. * @param mask
  5014. */
  5015. Observable.prototype.notifyObservers = function (eventData, mask) {
  5016. if (mask === void 0) { mask = -1; }
  5017. var state = this._eventState;
  5018. state.mask = mask;
  5019. state.skipNextObservers = false;
  5020. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5021. var obs = _a[_i];
  5022. if (obs.mask & mask) {
  5023. obs.callback(eventData, state);
  5024. }
  5025. if (state.skipNextObservers) {
  5026. return false;
  5027. }
  5028. }
  5029. return true;
  5030. };
  5031. /**
  5032. * return true is the Observable has at least one Observer registered
  5033. */
  5034. Observable.prototype.hasObservers = function () {
  5035. return this._observers.length > 0;
  5036. };
  5037. /**
  5038. * Clear the list of observers
  5039. */
  5040. Observable.prototype.clear = function () {
  5041. this._observers = new Array();
  5042. };
  5043. /**
  5044. * Clone the current observable
  5045. */
  5046. Observable.prototype.clone = function () {
  5047. var result = new Observable();
  5048. result._observers = this._observers.slice(0);
  5049. return result;
  5050. };
  5051. /**
  5052. * Does this observable handles observer registered with a given mask
  5053. * @param {number} trigger - the mask to be tested
  5054. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5055. **/
  5056. Observable.prototype.hasSpecificMask = function (mask) {
  5057. if (mask === void 0) { mask = -1; }
  5058. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5059. var obs = _a[_i];
  5060. if (obs.mask & mask && obs.mask === mask) {
  5061. return true;
  5062. }
  5063. }
  5064. return false;
  5065. };
  5066. return Observable;
  5067. }());
  5068. BABYLON.Observable = Observable;
  5069. })(BABYLON || (BABYLON = {}));
  5070. //# sourceMappingURL=babylon.observable.js.map
  5071. var BABYLON;
  5072. (function (BABYLON) {
  5073. var SmartArray = (function () {
  5074. function SmartArray(capacity) {
  5075. this.length = 0;
  5076. this._duplicateId = 0;
  5077. this.data = new Array(capacity);
  5078. this._id = SmartArray._GlobalId++;
  5079. }
  5080. SmartArray.prototype.push = function (value) {
  5081. this.data[this.length++] = value;
  5082. if (this.length > this.data.length) {
  5083. this.data.length *= 2;
  5084. }
  5085. if (!value.__smartArrayFlags) {
  5086. value.__smartArrayFlags = {};
  5087. }
  5088. value.__smartArrayFlags[this._id] = this._duplicateId;
  5089. };
  5090. SmartArray.prototype.forEach = function (func) {
  5091. for (var index = 0; index < this.length; index++) {
  5092. func(this.data[index]);
  5093. }
  5094. };
  5095. SmartArray.prototype.pushNoDuplicate = function (value) {
  5096. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5097. return false;
  5098. }
  5099. this.push(value);
  5100. return true;
  5101. };
  5102. SmartArray.prototype.sort = function (compareFn) {
  5103. this.data.sort(compareFn);
  5104. };
  5105. SmartArray.prototype.reset = function () {
  5106. this.length = 0;
  5107. this._duplicateId++;
  5108. };
  5109. SmartArray.prototype.dispose = function () {
  5110. this.reset();
  5111. this.data.length = 0;
  5112. };
  5113. SmartArray.prototype.concat = function (array) {
  5114. if (array.length === 0) {
  5115. return;
  5116. }
  5117. if (this.length + array.length > this.data.length) {
  5118. this.data.length = (this.length + array.length) * 2;
  5119. }
  5120. for (var index = 0; index < array.length; index++) {
  5121. this.data[this.length++] = (array.data || array)[index];
  5122. }
  5123. };
  5124. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5125. if (array.length === 0) {
  5126. return;
  5127. }
  5128. if (this.length + array.length > this.data.length) {
  5129. this.data.length = (this.length + array.length) * 2;
  5130. }
  5131. for (var index = 0; index < array.length; index++) {
  5132. var item = (array.data || array)[index];
  5133. this.pushNoDuplicate(item);
  5134. }
  5135. };
  5136. SmartArray.prototype.indexOf = function (value) {
  5137. var position = this.data.indexOf(value);
  5138. if (position >= this.length) {
  5139. return -1;
  5140. }
  5141. return position;
  5142. };
  5143. SmartArray.prototype.contains = function (value) {
  5144. return this.data.indexOf(value) !== -1;
  5145. };
  5146. return SmartArray;
  5147. }());
  5148. // Statics
  5149. SmartArray._GlobalId = 0;
  5150. BABYLON.SmartArray = SmartArray;
  5151. })(BABYLON || (BABYLON = {}));
  5152. //# sourceMappingURL=babylon.smartArray.js.map
  5153. var BABYLON;
  5154. (function (BABYLON) {
  5155. // Screenshots
  5156. var screenshotCanvas;
  5157. var cloneValue = function (source, destinationObject) {
  5158. if (!source)
  5159. return null;
  5160. if (source instanceof BABYLON.Mesh) {
  5161. return null;
  5162. }
  5163. if (source instanceof BABYLON.SubMesh) {
  5164. return source.clone(destinationObject);
  5165. }
  5166. else if (source.clone) {
  5167. return source.clone();
  5168. }
  5169. return null;
  5170. };
  5171. var Tools = (function () {
  5172. function Tools() {
  5173. }
  5174. ;
  5175. /**
  5176. * Interpolates between a and b via alpha
  5177. * @param a The lower value (returned when alpha = 0)
  5178. * @param b The upper value (returned when alpha = 1)
  5179. * @param alpha The interpolation-factor
  5180. * @return The mixed value
  5181. */
  5182. Tools.Mix = function (a, b, alpha) {
  5183. return a * (1 - alpha) + b * alpha;
  5184. };
  5185. Tools.Instantiate = function (className) {
  5186. var arr = className.split(".");
  5187. var fn = (window || this);
  5188. for (var i = 0, len = arr.length; i < len; i++) {
  5189. fn = fn[arr[i]];
  5190. }
  5191. if (typeof fn !== "function") {
  5192. return null;
  5193. }
  5194. return fn;
  5195. };
  5196. Tools.SetImmediate = function (action) {
  5197. if (window.setImmediate) {
  5198. window.setImmediate(action);
  5199. }
  5200. else {
  5201. setTimeout(action, 1);
  5202. }
  5203. };
  5204. Tools.IsExponentOfTwo = function (value) {
  5205. var count = 1;
  5206. do {
  5207. count *= 2;
  5208. } while (count < value);
  5209. return count === value;
  5210. };
  5211. Tools.GetExponentOfTwo = function (value, max) {
  5212. var count = 1;
  5213. do {
  5214. count *= 2;
  5215. } while (count < value);
  5216. if (count > max)
  5217. count = max;
  5218. return count;
  5219. };
  5220. Tools.GetFilename = function (path) {
  5221. var index = path.lastIndexOf("/");
  5222. if (index < 0)
  5223. return path;
  5224. return path.substring(index + 1);
  5225. };
  5226. Tools.GetDOMTextContent = function (element) {
  5227. var result = "";
  5228. var child = element.firstChild;
  5229. while (child) {
  5230. if (child.nodeType === 3) {
  5231. result += child.textContent;
  5232. }
  5233. child = child.nextSibling;
  5234. }
  5235. return result;
  5236. };
  5237. Tools.ToDegrees = function (angle) {
  5238. return angle * 180 / Math.PI;
  5239. };
  5240. Tools.ToRadians = function (angle) {
  5241. return angle * Math.PI / 180;
  5242. };
  5243. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5244. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5245. var output = "";
  5246. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5247. var i = 0;
  5248. var bytes = new Uint8Array(buffer);
  5249. while (i < bytes.length) {
  5250. chr1 = bytes[i++];
  5251. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5252. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5253. enc1 = chr1 >> 2;
  5254. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5255. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5256. enc4 = chr3 & 63;
  5257. if (isNaN(chr2)) {
  5258. enc3 = enc4 = 64;
  5259. }
  5260. else if (isNaN(chr3)) {
  5261. enc4 = 64;
  5262. }
  5263. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5264. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5265. }
  5266. return "data:image/png;base64," + output;
  5267. };
  5268. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5269. if (bias === void 0) { bias = null; }
  5270. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5271. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5272. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5273. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5274. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5275. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5276. }
  5277. if (bias) {
  5278. minimum.x -= minimum.x * bias.x + bias.y;
  5279. minimum.y -= minimum.y * bias.x + bias.y;
  5280. minimum.z -= minimum.z * bias.x + bias.y;
  5281. maximum.x += maximum.x * bias.x + bias.y;
  5282. maximum.y += maximum.y * bias.x + bias.y;
  5283. maximum.z += maximum.z * bias.x + bias.y;
  5284. }
  5285. return {
  5286. minimum: minimum,
  5287. maximum: maximum
  5288. };
  5289. };
  5290. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5291. if (bias === void 0) { bias = null; }
  5292. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5293. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5294. if (!stride) {
  5295. stride = 3;
  5296. }
  5297. for (var index = start; index < start + count; index++) {
  5298. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5299. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5300. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5301. }
  5302. if (bias) {
  5303. minimum.x -= minimum.x * bias.x + bias.y;
  5304. minimum.y -= minimum.y * bias.x + bias.y;
  5305. minimum.z -= minimum.z * bias.x + bias.y;
  5306. maximum.x += maximum.x * bias.x + bias.y;
  5307. maximum.y += maximum.y * bias.x + bias.y;
  5308. maximum.z += maximum.z * bias.x + bias.y;
  5309. }
  5310. return {
  5311. minimum: minimum,
  5312. maximum: maximum
  5313. };
  5314. };
  5315. Tools.Vector2ArrayFeeder = function (array) {
  5316. return function (index) {
  5317. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5318. var length = isFloatArray ? array.length / 2 : array.length;
  5319. if (index >= length) {
  5320. return null;
  5321. }
  5322. if (isFloatArray) {
  5323. var fa = array;
  5324. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5325. }
  5326. var a = array;
  5327. return a[index];
  5328. };
  5329. };
  5330. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5331. if (bias === void 0) { bias = null; }
  5332. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5333. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5334. var i = 0;
  5335. var cur = feeder(i++);
  5336. while (cur) {
  5337. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5338. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5339. cur = feeder(i++);
  5340. }
  5341. if (bias) {
  5342. minimum.x -= minimum.x * bias.x + bias.y;
  5343. minimum.y -= minimum.y * bias.x + bias.y;
  5344. maximum.x += maximum.x * bias.x + bias.y;
  5345. maximum.y += maximum.y * bias.x + bias.y;
  5346. }
  5347. return {
  5348. minimum: minimum,
  5349. maximum: maximum
  5350. };
  5351. };
  5352. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5353. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5354. return undefined;
  5355. return Array.isArray(obj) ? obj : [obj];
  5356. };
  5357. // Misc.
  5358. Tools.GetPointerPrefix = function () {
  5359. var eventPrefix = "pointer";
  5360. // Check if pointer events are supported
  5361. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5362. eventPrefix = "mouse";
  5363. }
  5364. return eventPrefix;
  5365. };
  5366. /**
  5367. * @param func - the function to be called
  5368. * @param requester - the object that will request the next frame. Falls back to window.
  5369. */
  5370. Tools.QueueNewFrame = function (func, requester) {
  5371. if (requester === void 0) { requester = window; }
  5372. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5373. /*if(requester.isPresenting) {
  5374. return;
  5375. } else*/ if (requester.requestAnimationFrame)
  5376. requester.requestAnimationFrame(func);
  5377. else if (requester.msRequestAnimationFrame)
  5378. requester.msRequestAnimationFrame(func);
  5379. else if (requester.webkitRequestAnimationFrame)
  5380. requester.webkitRequestAnimationFrame(func);
  5381. else if (requester.mozRequestAnimationFrame)
  5382. requester.mozRequestAnimationFrame(func);
  5383. else if (requester.oRequestAnimationFrame)
  5384. requester.oRequestAnimationFrame(func);
  5385. else {
  5386. window.setTimeout(func, 16);
  5387. }
  5388. };
  5389. Tools.RequestFullscreen = function (element) {
  5390. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5391. if (!requestFunction)
  5392. return;
  5393. requestFunction.call(element);
  5394. };
  5395. Tools.ExitFullscreen = function () {
  5396. if (document.exitFullscreen) {
  5397. document.exitFullscreen();
  5398. }
  5399. else if (document.mozCancelFullScreen) {
  5400. document.mozCancelFullScreen();
  5401. }
  5402. else if (document.webkitCancelFullScreen) {
  5403. document.webkitCancelFullScreen();
  5404. }
  5405. else if (document.msCancelFullScreen) {
  5406. document.msCancelFullScreen();
  5407. }
  5408. };
  5409. Tools.SetCorsBehavior = function (url, img) {
  5410. if (Tools.CorsBehavior) {
  5411. switch (typeof (Tools.CorsBehavior)) {
  5412. case "function":
  5413. var result = Tools.CorsBehavior(url);
  5414. if (result) {
  5415. img.crossOrigin = result;
  5416. }
  5417. break;
  5418. case "string":
  5419. default:
  5420. img.crossOrigin = Tools.CorsBehavior;
  5421. break;
  5422. }
  5423. }
  5424. };
  5425. // External files
  5426. Tools.CleanUrl = function (url) {
  5427. url = url.replace(/#/mg, "%23");
  5428. return url;
  5429. };
  5430. Tools.LoadImage = function (url, onload, onerror, database) {
  5431. if (url instanceof ArrayBuffer) {
  5432. url = Tools.EncodeArrayBufferTobase64(url);
  5433. }
  5434. url = Tools.CleanUrl(url);
  5435. var img = new Image();
  5436. if (url.substr(0, 5) !== "data:") {
  5437. Tools.SetCorsBehavior(url, img);
  5438. }
  5439. img.onload = function () {
  5440. onload(img);
  5441. };
  5442. img.onerror = function (err) {
  5443. Tools.Error("Error while trying to load image: " + url);
  5444. if (Tools.UseFallbackTexture) {
  5445. img.src = Tools.fallbackTexture;
  5446. onload(img);
  5447. }
  5448. else {
  5449. onerror();
  5450. }
  5451. };
  5452. var noIndexedDB = function () {
  5453. img.src = url;
  5454. };
  5455. var loadFromIndexedDB = function () {
  5456. database.loadImageFromDB(url, img);
  5457. };
  5458. //ANY database to do!
  5459. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5460. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5461. }
  5462. else {
  5463. if (url.indexOf("file:") !== 0) {
  5464. noIndexedDB();
  5465. }
  5466. else {
  5467. var textureName = url.substring(5).toLowerCase();
  5468. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5469. try {
  5470. var blobURL;
  5471. try {
  5472. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5473. }
  5474. catch (ex) {
  5475. // Chrome doesn't support oneTimeOnly parameter
  5476. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5477. }
  5478. img.src = blobURL;
  5479. }
  5480. catch (e) {
  5481. img.src = null;
  5482. }
  5483. }
  5484. else {
  5485. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5486. img.src = Tools.fallbackTexture;
  5487. }
  5488. }
  5489. }
  5490. return img;
  5491. };
  5492. //ANY
  5493. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5494. url = Tools.CleanUrl(url);
  5495. var noIndexedDB = function () {
  5496. var request = new XMLHttpRequest();
  5497. var loadUrl = Tools.BaseUrl + url;
  5498. request.open('GET', loadUrl, true);
  5499. if (useArrayBuffer) {
  5500. request.responseType = "arraybuffer";
  5501. }
  5502. request.onprogress = progressCallBack;
  5503. request.onreadystatechange = function () {
  5504. // In case of undefined state in some browsers.
  5505. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5506. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5507. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5508. callback(!useArrayBuffer ? request.responseText : request.response);
  5509. }
  5510. else {
  5511. if (onError) {
  5512. onError(request);
  5513. }
  5514. else {
  5515. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5516. }
  5517. }
  5518. }
  5519. };
  5520. request.send(null);
  5521. };
  5522. var loadFromIndexedDB = function () {
  5523. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5524. };
  5525. if (url.indexOf("file:") !== -1) {
  5526. var fileName = url.substring(5).toLowerCase();
  5527. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5528. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5529. }
  5530. else {
  5531. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5532. }
  5533. }
  5534. else {
  5535. // Caching all files
  5536. if (database && database.enableSceneOffline) {
  5537. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5538. }
  5539. else {
  5540. noIndexedDB();
  5541. }
  5542. }
  5543. };
  5544. /**
  5545. * Load a script (identified by an url). When the url returns, the
  5546. * content of this file is added into a new script element, attached to the DOM (body element)
  5547. */
  5548. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5549. var head = document.getElementsByTagName('head')[0];
  5550. var script = document.createElement('script');
  5551. script.type = 'text/javascript';
  5552. script.src = scriptUrl;
  5553. var self = this;
  5554. script.onload = function () {
  5555. if (onSuccess) {
  5556. onSuccess();
  5557. }
  5558. };
  5559. script.onerror = function () {
  5560. if (onError) {
  5561. onError();
  5562. }
  5563. };
  5564. head.appendChild(script);
  5565. };
  5566. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5567. var reader = new FileReader();
  5568. reader.onload = function (e) {
  5569. //target doesn't have result from ts 1.3
  5570. callback(e.target['result']);
  5571. };
  5572. reader.onprogress = progressCallback;
  5573. reader.readAsDataURL(fileToLoad);
  5574. };
  5575. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5576. var reader = new FileReader();
  5577. reader.onerror = function (e) {
  5578. Tools.Log("Error while reading file: " + fileToLoad.name);
  5579. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5580. };
  5581. reader.onload = function (e) {
  5582. //target doesn't have result from ts 1.3
  5583. callback(e.target['result']);
  5584. };
  5585. reader.onprogress = progressCallBack;
  5586. if (!useArrayBuffer) {
  5587. // Asynchronous read
  5588. reader.readAsText(fileToLoad);
  5589. }
  5590. else {
  5591. reader.readAsArrayBuffer(fileToLoad);
  5592. }
  5593. };
  5594. //returns a downloadable url to a file content.
  5595. Tools.FileAsURL = function (content) {
  5596. var fileBlob = new Blob([content]);
  5597. var url = window.URL || window.webkitURL;
  5598. var link = url.createObjectURL(fileBlob);
  5599. return link;
  5600. };
  5601. // Misc.
  5602. Tools.Format = function (value, decimals) {
  5603. if (decimals === void 0) { decimals = 2; }
  5604. return value.toFixed(decimals);
  5605. };
  5606. Tools.CheckExtends = function (v, min, max) {
  5607. if (v.x < min.x)
  5608. min.x = v.x;
  5609. if (v.y < min.y)
  5610. min.y = v.y;
  5611. if (v.z < min.z)
  5612. min.z = v.z;
  5613. if (v.x > max.x)
  5614. max.x = v.x;
  5615. if (v.y > max.y)
  5616. max.y = v.y;
  5617. if (v.z > max.z)
  5618. max.z = v.z;
  5619. };
  5620. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5621. for (var prop in source) {
  5622. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5623. continue;
  5624. }
  5625. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5626. continue;
  5627. }
  5628. var sourceValue = source[prop];
  5629. var typeOfSourceValue = typeof sourceValue;
  5630. if (typeOfSourceValue === "function") {
  5631. continue;
  5632. }
  5633. if (typeOfSourceValue === "object") {
  5634. if (sourceValue instanceof Array) {
  5635. destination[prop] = [];
  5636. if (sourceValue.length > 0) {
  5637. if (typeof sourceValue[0] == "object") {
  5638. for (var index = 0; index < sourceValue.length; index++) {
  5639. var clonedValue = cloneValue(sourceValue[index], destination);
  5640. if (destination[prop].indexOf(clonedValue) === -1) {
  5641. destination[prop].push(clonedValue);
  5642. }
  5643. }
  5644. }
  5645. else {
  5646. destination[prop] = sourceValue.slice(0);
  5647. }
  5648. }
  5649. }
  5650. else {
  5651. destination[prop] = cloneValue(sourceValue, destination);
  5652. }
  5653. }
  5654. else {
  5655. destination[prop] = sourceValue;
  5656. }
  5657. }
  5658. };
  5659. Tools.IsEmpty = function (obj) {
  5660. for (var i in obj) {
  5661. return false;
  5662. }
  5663. return true;
  5664. };
  5665. Tools.RegisterTopRootEvents = function (events) {
  5666. for (var index = 0; index < events.length; index++) {
  5667. var event = events[index];
  5668. window.addEventListener(event.name, event.handler, false);
  5669. try {
  5670. if (window.parent) {
  5671. window.parent.addEventListener(event.name, event.handler, false);
  5672. }
  5673. }
  5674. catch (e) {
  5675. // Silently fails...
  5676. }
  5677. }
  5678. };
  5679. Tools.UnregisterTopRootEvents = function (events) {
  5680. for (var index = 0; index < events.length; index++) {
  5681. var event = events[index];
  5682. window.removeEventListener(event.name, event.handler);
  5683. try {
  5684. if (window.parent) {
  5685. window.parent.removeEventListener(event.name, event.handler);
  5686. }
  5687. }
  5688. catch (e) {
  5689. // Silently fails...
  5690. }
  5691. }
  5692. };
  5693. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5694. if (mimeType === void 0) { mimeType = "image/png"; }
  5695. // Read the contents of the framebuffer
  5696. var numberOfChannelsByLine = width * 4;
  5697. var halfHeight = height / 2;
  5698. //Reading datas from WebGL
  5699. var data = engine.readPixels(0, 0, width, height);
  5700. //To flip image on Y axis.
  5701. for (var i = 0; i < halfHeight; i++) {
  5702. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5703. var currentCell = j + i * numberOfChannelsByLine;
  5704. var targetLine = height - i - 1;
  5705. var targetCell = j + targetLine * numberOfChannelsByLine;
  5706. var temp = data[currentCell];
  5707. data[currentCell] = data[targetCell];
  5708. data[targetCell] = temp;
  5709. }
  5710. }
  5711. // Create a 2D canvas to store the result
  5712. if (!screenshotCanvas) {
  5713. screenshotCanvas = document.createElement('canvas');
  5714. }
  5715. screenshotCanvas.width = width;
  5716. screenshotCanvas.height = height;
  5717. var context = screenshotCanvas.getContext('2d');
  5718. // Copy the pixels to a 2D canvas
  5719. var imageData = context.createImageData(width, height);
  5720. var castData = (imageData.data);
  5721. castData.set(data);
  5722. context.putImageData(imageData, 0, 0);
  5723. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5724. };
  5725. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5726. if (mimeType === void 0) { mimeType = "image/png"; }
  5727. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5728. if (successCallback) {
  5729. successCallback(base64Image);
  5730. }
  5731. else {
  5732. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5733. if (("download" in document.createElement("a"))) {
  5734. var a = window.document.createElement("a");
  5735. a.href = base64Image;
  5736. var date = new Date();
  5737. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5738. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5739. window.document.body.appendChild(a);
  5740. a.addEventListener("click", function () {
  5741. a.parentElement.removeChild(a);
  5742. });
  5743. a.click();
  5744. //Or opening a new tab with the image if it is not possible to automatically start download.
  5745. }
  5746. else {
  5747. var newWindow = window.open("");
  5748. var img = newWindow.document.createElement("img");
  5749. img.src = base64Image;
  5750. newWindow.document.body.appendChild(img);
  5751. }
  5752. }
  5753. };
  5754. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5755. if (mimeType === void 0) { mimeType = "image/png"; }
  5756. var width;
  5757. var height;
  5758. // If a precision value is specified
  5759. if (size.precision) {
  5760. width = Math.round(engine.getRenderWidth() * size.precision);
  5761. height = Math.round(width / engine.getAspectRatio(camera));
  5762. }
  5763. else if (size.width && size.height) {
  5764. width = size.width;
  5765. height = size.height;
  5766. }
  5767. else if (size.width && !size.height) {
  5768. width = size.width;
  5769. height = Math.round(width / engine.getAspectRatio(camera));
  5770. }
  5771. else if (size.height && !size.width) {
  5772. height = size.height;
  5773. width = Math.round(height * engine.getAspectRatio(camera));
  5774. }
  5775. else if (!isNaN(size)) {
  5776. height = size;
  5777. width = size;
  5778. }
  5779. else {
  5780. Tools.Error("Invalid 'size' parameter !");
  5781. return;
  5782. }
  5783. if (!screenshotCanvas) {
  5784. screenshotCanvas = document.createElement('canvas');
  5785. }
  5786. screenshotCanvas.width = width;
  5787. screenshotCanvas.height = height;
  5788. var renderContext = screenshotCanvas.getContext("2d");
  5789. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5790. var newWidth = width;
  5791. var newHeight = newWidth / ratio;
  5792. if (newHeight > height) {
  5793. newHeight = height;
  5794. newWidth = newHeight * ratio;
  5795. }
  5796. var offsetX = Math.max(0, width - newWidth) / 2;
  5797. var offsetY = Math.max(0, height - newHeight) / 2;
  5798. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5799. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5800. };
  5801. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5802. if (mimeType === void 0) { mimeType = "image/png"; }
  5803. if (samples === void 0) { samples = 1; }
  5804. var width;
  5805. var height;
  5806. //If a precision value is specified
  5807. if (size.precision) {
  5808. width = Math.round(engine.getRenderWidth() * size.precision);
  5809. height = Math.round(width / engine.getAspectRatio(camera));
  5810. size = { width: width, height: height };
  5811. }
  5812. else if (size.width && size.height) {
  5813. width = size.width;
  5814. height = size.height;
  5815. }
  5816. else if (size.width && !size.height) {
  5817. width = size.width;
  5818. height = Math.round(width / engine.getAspectRatio(camera));
  5819. size = { width: width, height: height };
  5820. }
  5821. else if (size.height && !size.width) {
  5822. height = size.height;
  5823. width = Math.round(height * engine.getAspectRatio(camera));
  5824. size = { width: width, height: height };
  5825. }
  5826. else if (!isNaN(size)) {
  5827. height = size;
  5828. width = size;
  5829. }
  5830. else {
  5831. Tools.Error("Invalid 'size' parameter !");
  5832. return;
  5833. }
  5834. var scene = camera.getScene();
  5835. var previousCamera = null;
  5836. if (scene.activeCamera !== camera) {
  5837. previousCamera = scene.activeCamera;
  5838. scene.activeCamera = camera;
  5839. }
  5840. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5841. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5842. texture.renderList = scene.meshes;
  5843. texture.samples = samples;
  5844. texture.onAfterRenderObservable.add(function () {
  5845. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5846. });
  5847. scene.incrementRenderId();
  5848. scene.resetCachedMaterial();
  5849. texture.render(true);
  5850. texture.dispose();
  5851. if (previousCamera) {
  5852. scene.activeCamera = previousCamera;
  5853. }
  5854. camera.getProjectionMatrix(true); // Force cache refresh;
  5855. };
  5856. // XHR response validator for local file scenario
  5857. Tools.ValidateXHRData = function (xhr, dataType) {
  5858. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5859. if (dataType === void 0) { dataType = 7; }
  5860. try {
  5861. if (dataType & 1) {
  5862. if (xhr.responseText && xhr.responseText.length > 0) {
  5863. return true;
  5864. }
  5865. else if (dataType === 1) {
  5866. return false;
  5867. }
  5868. }
  5869. if (dataType & 2) {
  5870. // Check header width and height since there is no "TGA" magic number
  5871. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5872. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5873. return true;
  5874. }
  5875. else if (dataType === 2) {
  5876. return false;
  5877. }
  5878. }
  5879. if (dataType & 4) {
  5880. // Check for the "DDS" magic number
  5881. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5882. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5883. return true;
  5884. }
  5885. else {
  5886. return false;
  5887. }
  5888. }
  5889. }
  5890. catch (e) {
  5891. // Global protection
  5892. }
  5893. return false;
  5894. };
  5895. /**
  5896. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5897. * Be aware Math.random() could cause collisions, but:
  5898. * "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"
  5899. */
  5900. Tools.RandomId = function () {
  5901. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5902. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5903. return v.toString(16);
  5904. });
  5905. };
  5906. Object.defineProperty(Tools, "NoneLogLevel", {
  5907. get: function () {
  5908. return Tools._NoneLogLevel;
  5909. },
  5910. enumerable: true,
  5911. configurable: true
  5912. });
  5913. Object.defineProperty(Tools, "MessageLogLevel", {
  5914. get: function () {
  5915. return Tools._MessageLogLevel;
  5916. },
  5917. enumerable: true,
  5918. configurable: true
  5919. });
  5920. Object.defineProperty(Tools, "WarningLogLevel", {
  5921. get: function () {
  5922. return Tools._WarningLogLevel;
  5923. },
  5924. enumerable: true,
  5925. configurable: true
  5926. });
  5927. Object.defineProperty(Tools, "ErrorLogLevel", {
  5928. get: function () {
  5929. return Tools._ErrorLogLevel;
  5930. },
  5931. enumerable: true,
  5932. configurable: true
  5933. });
  5934. Object.defineProperty(Tools, "AllLogLevel", {
  5935. get: function () {
  5936. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5937. },
  5938. enumerable: true,
  5939. configurable: true
  5940. });
  5941. Tools._AddLogEntry = function (entry) {
  5942. Tools._LogCache = entry + Tools._LogCache;
  5943. if (Tools.OnNewCacheEntry) {
  5944. Tools.OnNewCacheEntry(entry);
  5945. }
  5946. };
  5947. Tools._FormatMessage = function (message) {
  5948. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5949. var date = new Date();
  5950. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5951. };
  5952. Tools._LogDisabled = function (message) {
  5953. // nothing to do
  5954. };
  5955. Tools._LogEnabled = function (message) {
  5956. var formattedMessage = Tools._FormatMessage(message);
  5957. console.log("BJS - " + formattedMessage);
  5958. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5959. Tools._AddLogEntry(entry);
  5960. };
  5961. Tools._WarnDisabled = function (message) {
  5962. // nothing to do
  5963. };
  5964. Tools._WarnEnabled = function (message) {
  5965. var formattedMessage = Tools._FormatMessage(message);
  5966. console.warn("BJS - " + formattedMessage);
  5967. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5968. Tools._AddLogEntry(entry);
  5969. };
  5970. Tools._ErrorDisabled = function (message) {
  5971. // nothing to do
  5972. };
  5973. Tools._ErrorEnabled = function (message) {
  5974. Tools.errorsCount++;
  5975. var formattedMessage = Tools._FormatMessage(message);
  5976. console.error("BJS - " + formattedMessage);
  5977. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5978. Tools._AddLogEntry(entry);
  5979. };
  5980. Object.defineProperty(Tools, "LogCache", {
  5981. get: function () {
  5982. return Tools._LogCache;
  5983. },
  5984. enumerable: true,
  5985. configurable: true
  5986. });
  5987. Tools.ClearLogCache = function () {
  5988. Tools._LogCache = "";
  5989. Tools.errorsCount = 0;
  5990. };
  5991. Object.defineProperty(Tools, "LogLevels", {
  5992. set: function (level) {
  5993. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5994. Tools.Log = Tools._LogEnabled;
  5995. }
  5996. else {
  5997. Tools.Log = Tools._LogDisabled;
  5998. }
  5999. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6000. Tools.Warn = Tools._WarnEnabled;
  6001. }
  6002. else {
  6003. Tools.Warn = Tools._WarnDisabled;
  6004. }
  6005. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6006. Tools.Error = Tools._ErrorEnabled;
  6007. }
  6008. else {
  6009. Tools.Error = Tools._ErrorDisabled;
  6010. }
  6011. },
  6012. enumerable: true,
  6013. configurable: true
  6014. });
  6015. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6016. get: function () {
  6017. return Tools._PerformanceNoneLogLevel;
  6018. },
  6019. enumerable: true,
  6020. configurable: true
  6021. });
  6022. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6023. get: function () {
  6024. return Tools._PerformanceUserMarkLogLevel;
  6025. },
  6026. enumerable: true,
  6027. configurable: true
  6028. });
  6029. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6030. get: function () {
  6031. return Tools._PerformanceConsoleLogLevel;
  6032. },
  6033. enumerable: true,
  6034. configurable: true
  6035. });
  6036. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6037. set: function (level) {
  6038. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6039. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6040. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6041. return;
  6042. }
  6043. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6044. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6045. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6046. return;
  6047. }
  6048. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6049. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6050. },
  6051. enumerable: true,
  6052. configurable: true
  6053. });
  6054. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6055. };
  6056. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6057. };
  6058. Tools._StartUserMark = function (counterName, condition) {
  6059. if (condition === void 0) { condition = true; }
  6060. if (!condition || !Tools._performance.mark) {
  6061. return;
  6062. }
  6063. Tools._performance.mark(counterName + "-Begin");
  6064. };
  6065. Tools._EndUserMark = function (counterName, condition) {
  6066. if (condition === void 0) { condition = true; }
  6067. if (!condition || !Tools._performance.mark) {
  6068. return;
  6069. }
  6070. Tools._performance.mark(counterName + "-End");
  6071. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6072. };
  6073. Tools._StartPerformanceConsole = function (counterName, condition) {
  6074. if (condition === void 0) { condition = true; }
  6075. if (!condition) {
  6076. return;
  6077. }
  6078. Tools._StartUserMark(counterName, condition);
  6079. if (console.time) {
  6080. console.time(counterName);
  6081. }
  6082. };
  6083. Tools._EndPerformanceConsole = function (counterName, condition) {
  6084. if (condition === void 0) { condition = true; }
  6085. if (!condition) {
  6086. return;
  6087. }
  6088. Tools._EndUserMark(counterName, condition);
  6089. if (console.time) {
  6090. console.timeEnd(counterName);
  6091. }
  6092. };
  6093. Object.defineProperty(Tools, "Now", {
  6094. get: function () {
  6095. if (window.performance && window.performance.now) {
  6096. return window.performance.now();
  6097. }
  6098. return new Date().getTime();
  6099. },
  6100. enumerable: true,
  6101. configurable: true
  6102. });
  6103. /**
  6104. * This method will return the name of the class used to create the instance of the given object.
  6105. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6106. * @param object the object to get the class name from
  6107. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6108. */
  6109. Tools.getClassName = function (object, isType) {
  6110. if (isType === void 0) { isType = false; }
  6111. var name = null;
  6112. if (!isType && object.getClassName) {
  6113. name = object.getClassName();
  6114. }
  6115. else {
  6116. if (object instanceof Object) {
  6117. var classObj = isType ? object : Object.getPrototypeOf(object);
  6118. name = classObj.constructor["__bjsclassName__"];
  6119. }
  6120. if (!name) {
  6121. name = typeof object;
  6122. }
  6123. }
  6124. return name;
  6125. };
  6126. Tools.first = function (array, predicate) {
  6127. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6128. var el = array_1[_i];
  6129. if (predicate(el)) {
  6130. return el;
  6131. }
  6132. }
  6133. };
  6134. /**
  6135. * This method will return the name of the full name of the class, including its owning module (if any).
  6136. * 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).
  6137. * @param object the object to get the class name from
  6138. * @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.
  6139. */
  6140. Tools.getFullClassName = function (object, isType) {
  6141. if (isType === void 0) { isType = false; }
  6142. var className = null;
  6143. var moduleName = null;
  6144. if (!isType && object.getClassName) {
  6145. className = object.getClassName();
  6146. }
  6147. else {
  6148. if (object instanceof Object) {
  6149. var classObj = isType ? object : Object.getPrototypeOf(object);
  6150. className = classObj.constructor["__bjsclassName__"];
  6151. moduleName = classObj.constructor["__bjsmoduleName__"];
  6152. }
  6153. if (!className) {
  6154. className = typeof object;
  6155. }
  6156. }
  6157. if (!className) {
  6158. return null;
  6159. }
  6160. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6161. };
  6162. /**
  6163. * 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.
  6164. * @param array
  6165. */
  6166. Tools.arrayOrStringFeeder = function (array) {
  6167. return function (index) {
  6168. if (index >= array.length) {
  6169. return null;
  6170. }
  6171. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6172. if (val && val.getHashCode) {
  6173. val = val.getHashCode();
  6174. }
  6175. if (typeof val === "string") {
  6176. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6177. }
  6178. return val;
  6179. };
  6180. };
  6181. /**
  6182. * Compute the hashCode of a stream of number
  6183. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6184. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6185. * @return the hash code computed
  6186. */
  6187. Tools.hashCodeFromStream = function (feeder) {
  6188. // Based from here: http://stackoverflow.com/a/7616484/802124
  6189. var hash = 0;
  6190. var index = 0;
  6191. var chr = feeder(index++);
  6192. while (chr != null) {
  6193. hash = ((hash << 5) - hash) + chr;
  6194. hash |= 0; // Convert to 32bit integer
  6195. chr = feeder(index++);
  6196. }
  6197. return hash;
  6198. };
  6199. return Tools;
  6200. }());
  6201. Tools.BaseUrl = "";
  6202. Tools.CorsBehavior = "anonymous";
  6203. Tools.UseFallbackTexture = true;
  6204. // Used in case of a texture loading problem
  6205. 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";
  6206. // Logs
  6207. Tools._NoneLogLevel = 0;
  6208. Tools._MessageLogLevel = 1;
  6209. Tools._WarningLogLevel = 2;
  6210. Tools._ErrorLogLevel = 4;
  6211. Tools._LogCache = "";
  6212. Tools.errorsCount = 0;
  6213. Tools.Log = Tools._LogEnabled;
  6214. Tools.Warn = Tools._WarnEnabled;
  6215. Tools.Error = Tools._ErrorEnabled;
  6216. // Performances
  6217. Tools._PerformanceNoneLogLevel = 0;
  6218. Tools._PerformanceUserMarkLogLevel = 1;
  6219. Tools._PerformanceConsoleLogLevel = 2;
  6220. Tools._performance = window.performance;
  6221. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6222. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6223. BABYLON.Tools = Tools;
  6224. /**
  6225. * This class is used to track a performance counter which is number based.
  6226. * The user has access to many properties which give statistics of different nature
  6227. *
  6228. * The implementer can track two kinds of Performance Counter: time and count
  6229. * 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.
  6230. * 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.
  6231. */
  6232. var PerfCounter = (function () {
  6233. function PerfCounter() {
  6234. this._startMonitoringTime = 0;
  6235. this._min = 0;
  6236. this._max = 0;
  6237. this._average = 0;
  6238. this._lastSecAverage = 0;
  6239. this._current = 0;
  6240. this._totalValueCount = 0;
  6241. this._totalAccumulated = 0;
  6242. this._lastSecAccumulated = 0;
  6243. this._lastSecTime = 0;
  6244. this._lastSecValueCount = 0;
  6245. }
  6246. Object.defineProperty(PerfCounter.prototype, "min", {
  6247. /**
  6248. * Returns the smallest value ever
  6249. */
  6250. get: function () {
  6251. return this._min;
  6252. },
  6253. enumerable: true,
  6254. configurable: true
  6255. });
  6256. Object.defineProperty(PerfCounter.prototype, "max", {
  6257. /**
  6258. * Returns the biggest value ever
  6259. */
  6260. get: function () {
  6261. return this._max;
  6262. },
  6263. enumerable: true,
  6264. configurable: true
  6265. });
  6266. Object.defineProperty(PerfCounter.prototype, "average", {
  6267. /**
  6268. * Returns the average value since the performance counter is running
  6269. */
  6270. get: function () {
  6271. return this._average;
  6272. },
  6273. enumerable: true,
  6274. configurable: true
  6275. });
  6276. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6277. /**
  6278. * Returns the average value of the last second the counter was monitored
  6279. */
  6280. get: function () {
  6281. return this._lastSecAverage;
  6282. },
  6283. enumerable: true,
  6284. configurable: true
  6285. });
  6286. Object.defineProperty(PerfCounter.prototype, "current", {
  6287. /**
  6288. * Returns the current value
  6289. */
  6290. get: function () {
  6291. return this._current;
  6292. },
  6293. enumerable: true,
  6294. configurable: true
  6295. });
  6296. Object.defineProperty(PerfCounter.prototype, "total", {
  6297. get: function () {
  6298. return this._totalAccumulated;
  6299. },
  6300. enumerable: true,
  6301. configurable: true
  6302. });
  6303. /**
  6304. * Call this method to start monitoring a new frame.
  6305. * 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.
  6306. */
  6307. PerfCounter.prototype.fetchNewFrame = function () {
  6308. this._totalValueCount++;
  6309. this._current = 0;
  6310. this._lastSecValueCount++;
  6311. };
  6312. /**
  6313. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6314. * @param newCount the count value to add to the monitored count
  6315. * @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.
  6316. */
  6317. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6318. if (!PerfCounter.Enabled) {
  6319. return;
  6320. }
  6321. this._current += newCount;
  6322. if (fetchResult) {
  6323. this._fetchResult();
  6324. }
  6325. };
  6326. /**
  6327. * Start monitoring this performance counter
  6328. */
  6329. PerfCounter.prototype.beginMonitoring = function () {
  6330. if (!PerfCounter.Enabled) {
  6331. return;
  6332. }
  6333. this._startMonitoringTime = Tools.Now;
  6334. };
  6335. /**
  6336. * Compute the time lapsed since the previous beginMonitoring() call.
  6337. * @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
  6338. */
  6339. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6340. if (newFrame === void 0) { newFrame = true; }
  6341. if (!PerfCounter.Enabled) {
  6342. return;
  6343. }
  6344. if (newFrame) {
  6345. this.fetchNewFrame();
  6346. }
  6347. var currentTime = Tools.Now;
  6348. this._current = currentTime - this._startMonitoringTime;
  6349. if (newFrame) {
  6350. this._fetchResult();
  6351. }
  6352. };
  6353. PerfCounter.prototype._fetchResult = function () {
  6354. this._totalAccumulated += this._current;
  6355. this._lastSecAccumulated += this._current;
  6356. // Min/Max update
  6357. this._min = Math.min(this._min, this._current);
  6358. this._max = Math.max(this._max, this._current);
  6359. this._average = this._totalAccumulated / this._totalValueCount;
  6360. // Reset last sec?
  6361. var now = Tools.Now;
  6362. if ((now - this._lastSecTime) > 1000) {
  6363. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6364. this._lastSecTime = now;
  6365. this._lastSecAccumulated = 0;
  6366. this._lastSecValueCount = 0;
  6367. }
  6368. };
  6369. return PerfCounter;
  6370. }());
  6371. PerfCounter.Enabled = true;
  6372. BABYLON.PerfCounter = PerfCounter;
  6373. /**
  6374. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6375. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6376. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6377. * @param name The name of the class, case should be preserved
  6378. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6379. */
  6380. function className(name, module) {
  6381. return function (target) {
  6382. target["__bjsclassName__"] = name;
  6383. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6384. };
  6385. }
  6386. BABYLON.className = className;
  6387. /**
  6388. * An implementation of a loop for asynchronous functions.
  6389. */
  6390. var AsyncLoop = (function () {
  6391. /**
  6392. * Constroctor.
  6393. * @param iterations the number of iterations.
  6394. * @param _fn the function to run each iteration
  6395. * @param _successCallback the callback that will be called upon succesful execution
  6396. * @param offset starting offset.
  6397. */
  6398. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6399. if (offset === void 0) { offset = 0; }
  6400. this.iterations = iterations;
  6401. this._fn = _fn;
  6402. this._successCallback = _successCallback;
  6403. this.index = offset - 1;
  6404. this._done = false;
  6405. }
  6406. /**
  6407. * Execute the next iteration. Must be called after the last iteration was finished.
  6408. */
  6409. AsyncLoop.prototype.executeNext = function () {
  6410. if (!this._done) {
  6411. if (this.index + 1 < this.iterations) {
  6412. ++this.index;
  6413. this._fn(this);
  6414. }
  6415. else {
  6416. this.breakLoop();
  6417. }
  6418. }
  6419. };
  6420. /**
  6421. * Break the loop and run the success callback.
  6422. */
  6423. AsyncLoop.prototype.breakLoop = function () {
  6424. this._done = true;
  6425. this._successCallback();
  6426. };
  6427. /**
  6428. * Helper function
  6429. */
  6430. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6431. if (offset === void 0) { offset = 0; }
  6432. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6433. loop.executeNext();
  6434. return loop;
  6435. };
  6436. /**
  6437. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6438. * @param iterations total number of iterations
  6439. * @param syncedIterations number of synchronous iterations in each async iteration.
  6440. * @param fn the function to call each iteration.
  6441. * @param callback a success call back that will be called when iterating stops.
  6442. * @param breakFunction a break condition (optional)
  6443. * @param timeout timeout settings for the setTimeout function. default - 0.
  6444. * @constructor
  6445. */
  6446. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6447. if (timeout === void 0) { timeout = 0; }
  6448. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6449. if (breakFunction && breakFunction())
  6450. loop.breakLoop();
  6451. else {
  6452. setTimeout(function () {
  6453. for (var i = 0; i < syncedIterations; ++i) {
  6454. var iteration = (loop.index * syncedIterations) + i;
  6455. if (iteration >= iterations)
  6456. break;
  6457. fn(iteration);
  6458. if (breakFunction && breakFunction()) {
  6459. loop.breakLoop();
  6460. break;
  6461. }
  6462. }
  6463. loop.executeNext();
  6464. }, timeout);
  6465. }
  6466. }, callback);
  6467. };
  6468. return AsyncLoop;
  6469. }());
  6470. BABYLON.AsyncLoop = AsyncLoop;
  6471. })(BABYLON || (BABYLON = {}));
  6472. //# sourceMappingURL=babylon.tools.js.map
  6473. var BABYLON;
  6474. (function (BABYLON) {
  6475. var Internals;
  6476. (function (Internals) {
  6477. var _AlphaState = (function () {
  6478. /**
  6479. * Initializes the state.
  6480. */
  6481. function _AlphaState() {
  6482. this._isAlphaBlendDirty = false;
  6483. this._isBlendFunctionParametersDirty = false;
  6484. this._isBlendEquationParametersDirty = false;
  6485. this._isBlendConstantsDirty = false;
  6486. this._alphaBlend = false;
  6487. this._blendFunctionParameters = new Array(4);
  6488. this._blendEquationParameters = new Array(2);
  6489. this._blendConstants = new Array(4);
  6490. this.reset();
  6491. }
  6492. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6493. get: function () {
  6494. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6495. },
  6496. enumerable: true,
  6497. configurable: true
  6498. });
  6499. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6500. get: function () {
  6501. return this._alphaBlend;
  6502. },
  6503. set: function (value) {
  6504. if (this._alphaBlend === value) {
  6505. return;
  6506. }
  6507. this._alphaBlend = value;
  6508. this._isAlphaBlendDirty = true;
  6509. },
  6510. enumerable: true,
  6511. configurable: true
  6512. });
  6513. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6514. if (this._blendConstants[0] === r &&
  6515. this._blendConstants[1] === g &&
  6516. this._blendConstants[2] === b &&
  6517. this._blendConstants[3] === a) {
  6518. return;
  6519. }
  6520. this._blendConstants[0] = r;
  6521. this._blendConstants[1] = g;
  6522. this._blendConstants[2] = b;
  6523. this._blendConstants[3] = a;
  6524. this._isBlendConstantsDirty = true;
  6525. };
  6526. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6527. if (this._blendFunctionParameters[0] === value0 &&
  6528. this._blendFunctionParameters[1] === value1 &&
  6529. this._blendFunctionParameters[2] === value2 &&
  6530. this._blendFunctionParameters[3] === value3) {
  6531. return;
  6532. }
  6533. this._blendFunctionParameters[0] = value0;
  6534. this._blendFunctionParameters[1] = value1;
  6535. this._blendFunctionParameters[2] = value2;
  6536. this._blendFunctionParameters[3] = value3;
  6537. this._isBlendFunctionParametersDirty = true;
  6538. };
  6539. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6540. if (this._blendEquationParameters[0] === rgb &&
  6541. this._blendEquationParameters[1] === alpha) {
  6542. return;
  6543. }
  6544. this._blendEquationParameters[0] = rgb;
  6545. this._blendEquationParameters[1] = alpha;
  6546. this._isBlendEquationParametersDirty = true;
  6547. };
  6548. _AlphaState.prototype.reset = function () {
  6549. this._alphaBlend = false;
  6550. this._blendFunctionParameters[0] = null;
  6551. this._blendFunctionParameters[1] = null;
  6552. this._blendFunctionParameters[2] = null;
  6553. this._blendFunctionParameters[3] = null;
  6554. this._blendEquationParameters[0] = null;
  6555. this._blendEquationParameters[1] = null;
  6556. this._blendConstants[0] = null;
  6557. this._blendConstants[1] = null;
  6558. this._blendConstants[2] = null;
  6559. this._blendConstants[3] = null;
  6560. this._isAlphaBlendDirty = true;
  6561. this._isBlendFunctionParametersDirty = false;
  6562. this._isBlendEquationParametersDirty = false;
  6563. this._isBlendConstantsDirty = false;
  6564. };
  6565. _AlphaState.prototype.apply = function (gl) {
  6566. if (!this.isDirty) {
  6567. return;
  6568. }
  6569. // Alpha blend
  6570. if (this._isAlphaBlendDirty) {
  6571. if (this._alphaBlend) {
  6572. gl.enable(gl.BLEND);
  6573. }
  6574. else {
  6575. gl.disable(gl.BLEND);
  6576. }
  6577. this._isAlphaBlendDirty = false;
  6578. }
  6579. // Alpha function
  6580. if (this._isBlendFunctionParametersDirty) {
  6581. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6582. this._isBlendFunctionParametersDirty = false;
  6583. }
  6584. // Alpha equation
  6585. if (this._isBlendEquationParametersDirty) {
  6586. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6587. this._isBlendEquationParametersDirty = false;
  6588. }
  6589. // Constants
  6590. if (this._isBlendConstantsDirty) {
  6591. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6592. this._isBlendConstantsDirty = false;
  6593. }
  6594. };
  6595. return _AlphaState;
  6596. }());
  6597. Internals._AlphaState = _AlphaState;
  6598. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6599. })(BABYLON || (BABYLON = {}));
  6600. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6601. var BABYLON;
  6602. (function (BABYLON) {
  6603. var Internals;
  6604. (function (Internals) {
  6605. var _DepthCullingState = (function () {
  6606. /**
  6607. * Initializes the state.
  6608. */
  6609. function _DepthCullingState() {
  6610. this._isDepthTestDirty = false;
  6611. this._isDepthMaskDirty = false;
  6612. this._isDepthFuncDirty = false;
  6613. this._isCullFaceDirty = false;
  6614. this._isCullDirty = false;
  6615. this._isZOffsetDirty = false;
  6616. this.reset();
  6617. }
  6618. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6619. get: function () {
  6620. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6621. },
  6622. enumerable: true,
  6623. configurable: true
  6624. });
  6625. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6626. get: function () {
  6627. return this._zOffset;
  6628. },
  6629. set: function (value) {
  6630. if (this._zOffset === value) {
  6631. return;
  6632. }
  6633. this._zOffset = value;
  6634. this._isZOffsetDirty = true;
  6635. },
  6636. enumerable: true,
  6637. configurable: true
  6638. });
  6639. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6640. get: function () {
  6641. return this._cullFace;
  6642. },
  6643. set: function (value) {
  6644. if (this._cullFace === value) {
  6645. return;
  6646. }
  6647. this._cullFace = value;
  6648. this._isCullFaceDirty = true;
  6649. },
  6650. enumerable: true,
  6651. configurable: true
  6652. });
  6653. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6654. get: function () {
  6655. return this._cull;
  6656. },
  6657. set: function (value) {
  6658. if (this._cull === value) {
  6659. return;
  6660. }
  6661. this._cull = value;
  6662. this._isCullDirty = true;
  6663. },
  6664. enumerable: true,
  6665. configurable: true
  6666. });
  6667. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6668. get: function () {
  6669. return this._depthFunc;
  6670. },
  6671. set: function (value) {
  6672. if (this._depthFunc === value) {
  6673. return;
  6674. }
  6675. this._depthFunc = value;
  6676. this._isDepthFuncDirty = true;
  6677. },
  6678. enumerable: true,
  6679. configurable: true
  6680. });
  6681. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6682. get: function () {
  6683. return this._depthMask;
  6684. },
  6685. set: function (value) {
  6686. if (this._depthMask === value) {
  6687. return;
  6688. }
  6689. this._depthMask = value;
  6690. this._isDepthMaskDirty = true;
  6691. },
  6692. enumerable: true,
  6693. configurable: true
  6694. });
  6695. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6696. get: function () {
  6697. return this._depthTest;
  6698. },
  6699. set: function (value) {
  6700. if (this._depthTest === value) {
  6701. return;
  6702. }
  6703. this._depthTest = value;
  6704. this._isDepthTestDirty = true;
  6705. },
  6706. enumerable: true,
  6707. configurable: true
  6708. });
  6709. _DepthCullingState.prototype.reset = function () {
  6710. this._depthMask = true;
  6711. this._depthTest = true;
  6712. this._depthFunc = null;
  6713. this._cullFace = null;
  6714. this._cull = null;
  6715. this._zOffset = 0;
  6716. this._isDepthTestDirty = true;
  6717. this._isDepthMaskDirty = true;
  6718. this._isDepthFuncDirty = false;
  6719. this._isCullFaceDirty = false;
  6720. this._isCullDirty = false;
  6721. this._isZOffsetDirty = false;
  6722. };
  6723. _DepthCullingState.prototype.apply = function (gl) {
  6724. if (!this.isDirty) {
  6725. return;
  6726. }
  6727. // Cull
  6728. if (this._isCullDirty) {
  6729. if (this.cull) {
  6730. gl.enable(gl.CULL_FACE);
  6731. }
  6732. else {
  6733. gl.disable(gl.CULL_FACE);
  6734. }
  6735. this._isCullDirty = false;
  6736. }
  6737. // Cull face
  6738. if (this._isCullFaceDirty) {
  6739. gl.cullFace(this.cullFace);
  6740. this._isCullFaceDirty = false;
  6741. }
  6742. // Depth mask
  6743. if (this._isDepthMaskDirty) {
  6744. gl.depthMask(this.depthMask);
  6745. this._isDepthMaskDirty = false;
  6746. }
  6747. // Depth test
  6748. if (this._isDepthTestDirty) {
  6749. if (this.depthTest) {
  6750. gl.enable(gl.DEPTH_TEST);
  6751. }
  6752. else {
  6753. gl.disable(gl.DEPTH_TEST);
  6754. }
  6755. this._isDepthTestDirty = false;
  6756. }
  6757. // Depth func
  6758. if (this._isDepthFuncDirty) {
  6759. gl.depthFunc(this.depthFunc);
  6760. this._isDepthFuncDirty = false;
  6761. }
  6762. // zOffset
  6763. if (this._isZOffsetDirty) {
  6764. if (this.zOffset) {
  6765. gl.enable(gl.POLYGON_OFFSET_FILL);
  6766. gl.polygonOffset(this.zOffset, 0);
  6767. }
  6768. else {
  6769. gl.disable(gl.POLYGON_OFFSET_FILL);
  6770. }
  6771. this._isZOffsetDirty = false;
  6772. }
  6773. };
  6774. return _DepthCullingState;
  6775. }());
  6776. Internals._DepthCullingState = _DepthCullingState;
  6777. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6778. })(BABYLON || (BABYLON = {}));
  6779. //# sourceMappingURL=babylon.depthCullingState.js.map
  6780. var BABYLON;
  6781. (function (BABYLON) {
  6782. var Internals;
  6783. (function (Internals) {
  6784. var _StencilState = (function () {
  6785. function _StencilState() {
  6786. this._isStencilTestDirty = false;
  6787. this._isStencilMaskDirty = false;
  6788. this._isStencilFuncDirty = false;
  6789. this._isStencilOpDirty = false;
  6790. this.reset();
  6791. }
  6792. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6793. get: function () {
  6794. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6795. },
  6796. enumerable: true,
  6797. configurable: true
  6798. });
  6799. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6800. get: function () {
  6801. return this._stencilFunc;
  6802. },
  6803. set: function (value) {
  6804. if (this._stencilFunc === value) {
  6805. return;
  6806. }
  6807. this._stencilFunc = value;
  6808. this._isStencilFuncDirty = true;
  6809. },
  6810. enumerable: true,
  6811. configurable: true
  6812. });
  6813. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6814. get: function () {
  6815. return this._stencilFuncRef;
  6816. },
  6817. set: function (value) {
  6818. if (this._stencilFuncRef === value) {
  6819. return;
  6820. }
  6821. this._stencilFuncRef = value;
  6822. this._isStencilFuncDirty = true;
  6823. },
  6824. enumerable: true,
  6825. configurable: true
  6826. });
  6827. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6828. get: function () {
  6829. return this._stencilFuncMask;
  6830. },
  6831. set: function (value) {
  6832. if (this._stencilFuncMask === value) {
  6833. return;
  6834. }
  6835. this._stencilFuncMask = value;
  6836. this._isStencilFuncDirty = true;
  6837. },
  6838. enumerable: true,
  6839. configurable: true
  6840. });
  6841. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6842. get: function () {
  6843. return this._stencilOpStencilFail;
  6844. },
  6845. set: function (value) {
  6846. if (this._stencilOpStencilFail === value) {
  6847. return;
  6848. }
  6849. this._stencilOpStencilFail = value;
  6850. this._isStencilOpDirty = true;
  6851. },
  6852. enumerable: true,
  6853. configurable: true
  6854. });
  6855. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6856. get: function () {
  6857. return this._stencilOpDepthFail;
  6858. },
  6859. set: function (value) {
  6860. if (this._stencilOpDepthFail === value) {
  6861. return;
  6862. }
  6863. this._stencilOpDepthFail = value;
  6864. this._isStencilOpDirty = true;
  6865. },
  6866. enumerable: true,
  6867. configurable: true
  6868. });
  6869. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6870. get: function () {
  6871. return this._stencilOpStencilDepthPass;
  6872. },
  6873. set: function (value) {
  6874. if (this._stencilOpStencilDepthPass === value) {
  6875. return;
  6876. }
  6877. this._stencilOpStencilDepthPass = value;
  6878. this._isStencilOpDirty = true;
  6879. },
  6880. enumerable: true,
  6881. configurable: true
  6882. });
  6883. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6884. get: function () {
  6885. return this._stencilMask;
  6886. },
  6887. set: function (value) {
  6888. if (this._stencilMask === value) {
  6889. return;
  6890. }
  6891. this._stencilMask = value;
  6892. this._isStencilMaskDirty = true;
  6893. },
  6894. enumerable: true,
  6895. configurable: true
  6896. });
  6897. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6898. get: function () {
  6899. return this._stencilTest;
  6900. },
  6901. set: function (value) {
  6902. if (this._stencilTest === value) {
  6903. return;
  6904. }
  6905. this._stencilTest = value;
  6906. this._isStencilTestDirty = true;
  6907. },
  6908. enumerable: true,
  6909. configurable: true
  6910. });
  6911. _StencilState.prototype.reset = function () {
  6912. this._stencilTest = false;
  6913. this._stencilMask = 0xFF;
  6914. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6915. this._stencilFuncRef = 1;
  6916. this._stencilFuncMask = 0xFF;
  6917. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6918. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6919. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6920. this._isStencilTestDirty = true;
  6921. this._isStencilMaskDirty = true;
  6922. this._isStencilFuncDirty = true;
  6923. this._isStencilOpDirty = true;
  6924. };
  6925. _StencilState.prototype.apply = function (gl) {
  6926. if (!this.isDirty) {
  6927. return;
  6928. }
  6929. // Stencil test
  6930. if (this._isStencilTestDirty) {
  6931. if (this.stencilTest) {
  6932. gl.enable(gl.STENCIL_TEST);
  6933. }
  6934. else {
  6935. gl.disable(gl.STENCIL_TEST);
  6936. }
  6937. this._isStencilTestDirty = false;
  6938. }
  6939. // Stencil mask
  6940. if (this._isStencilMaskDirty) {
  6941. gl.stencilMask(this.stencilMask);
  6942. this._isStencilMaskDirty = false;
  6943. }
  6944. // Stencil func
  6945. if (this._isStencilFuncDirty) {
  6946. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6947. this._isStencilFuncDirty = false;
  6948. }
  6949. // Stencil op
  6950. if (this._isStencilOpDirty) {
  6951. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6952. this._isStencilOpDirty = false;
  6953. }
  6954. };
  6955. return _StencilState;
  6956. }());
  6957. Internals._StencilState = _StencilState;
  6958. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6959. })(BABYLON || (BABYLON = {}));
  6960. //# sourceMappingURL=babylon.stencilState.js.map
  6961. var BABYLON;
  6962. (function (BABYLON) {
  6963. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6964. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6965. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6966. gl.compileShader(shader);
  6967. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6968. throw new Error(gl.getShaderInfoLog(shader));
  6969. }
  6970. return shader;
  6971. };
  6972. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6973. var magFilter = gl.NEAREST;
  6974. var minFilter = gl.NEAREST;
  6975. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6976. magFilter = gl.LINEAR;
  6977. if (generateMipMaps) {
  6978. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6979. }
  6980. else {
  6981. minFilter = gl.LINEAR;
  6982. }
  6983. }
  6984. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6985. magFilter = gl.LINEAR;
  6986. if (generateMipMaps) {
  6987. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6988. }
  6989. else {
  6990. minFilter = gl.LINEAR;
  6991. }
  6992. }
  6993. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6994. magFilter = gl.NEAREST;
  6995. if (generateMipMaps) {
  6996. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6997. }
  6998. else {
  6999. minFilter = gl.NEAREST;
  7000. }
  7001. }
  7002. return {
  7003. min: minFilter,
  7004. mag: magFilter
  7005. };
  7006. };
  7007. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7008. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7009. var engine = scene.getEngine();
  7010. if (!engine) {
  7011. return;
  7012. }
  7013. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7014. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7015. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7016. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7017. texture._baseWidth = width;
  7018. texture._baseHeight = height;
  7019. texture._width = potWidth;
  7020. texture._height = potHeight;
  7021. texture.isReady = true;
  7022. processFunction(potWidth, potHeight);
  7023. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7024. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7025. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7026. if (!noMipmap && !isCompressed) {
  7027. gl.generateMipmap(gl.TEXTURE_2D);
  7028. }
  7029. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7030. engine.resetTextureCache();
  7031. scene._removePendingData(texture);
  7032. texture.onLoadedCallbacks.forEach(function (callback) {
  7033. callback();
  7034. });
  7035. texture.onLoadedCallbacks = [];
  7036. };
  7037. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7038. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7039. var img;
  7040. var onload = function () {
  7041. loadedImages[index] = img;
  7042. loadedImages._internalCount++;
  7043. scene._removePendingData(img);
  7044. if (loadedImages._internalCount === 6) {
  7045. onfinish(loadedImages);
  7046. }
  7047. };
  7048. var onerror = function () {
  7049. scene._removePendingData(img);
  7050. if (onErrorCallBack) {
  7051. onErrorCallBack();
  7052. }
  7053. };
  7054. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7055. scene._addPendingData(img);
  7056. };
  7057. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7058. if (onError === void 0) { onError = null; }
  7059. var loadedImages = [];
  7060. loadedImages._internalCount = 0;
  7061. for (var index = 0; index < 6; index++) {
  7062. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7063. }
  7064. };
  7065. var InstancingAttributeInfo = (function () {
  7066. function InstancingAttributeInfo() {
  7067. }
  7068. return InstancingAttributeInfo;
  7069. }());
  7070. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7071. var EngineCapabilities = (function () {
  7072. function EngineCapabilities() {
  7073. }
  7074. return EngineCapabilities;
  7075. }());
  7076. BABYLON.EngineCapabilities = EngineCapabilities;
  7077. /**
  7078. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7079. */
  7080. var Engine = (function () {
  7081. /**
  7082. * @constructor
  7083. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7084. * @param {boolean} [antialias] - enable antialias
  7085. * @param options - further options to be sent to the getContext function
  7086. */
  7087. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7088. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7089. var _this = this;
  7090. // Public members
  7091. this.isFullscreen = false;
  7092. this.isPointerLock = false;
  7093. this.cullBackFaces = true;
  7094. this.renderEvenInBackground = true;
  7095. this.preventCacheWipeBetweenFrames = false;
  7096. // To enable/disable IDB support and avoid XHR on .manifest
  7097. this.enableOfflineSupport = BABYLON.Database;
  7098. this.scenes = new Array();
  7099. // Observables
  7100. /**
  7101. * Observable event triggered each time the rendering canvas is resized
  7102. */
  7103. this.onResizeObservable = new BABYLON.Observable();
  7104. /**
  7105. * Observable event triggered each time the canvas lost focus
  7106. */
  7107. this.onCanvasBlurObservable = new BABYLON.Observable();
  7108. this._windowIsBackground = false;
  7109. this._webGLVersion = 1.0;
  7110. this._badOS = false;
  7111. this._drawCalls = new BABYLON.PerfCounter();
  7112. this._renderingQueueLaunched = false;
  7113. this._activeRenderLoops = [];
  7114. // FPS
  7115. this.fpsRange = 60;
  7116. this.previousFramesDuration = [];
  7117. this.fps = 60;
  7118. this.deltaTime = 0;
  7119. // States
  7120. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7121. this._stencilState = new BABYLON.Internals._StencilState();
  7122. this._alphaState = new BABYLON.Internals._AlphaState();
  7123. this._alphaMode = Engine.ALPHA_DISABLE;
  7124. // Cache
  7125. this._loadedTexturesCache = new Array();
  7126. this._maxTextureChannels = 16;
  7127. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7128. this._compiledEffects = {};
  7129. this._vertexAttribArraysEnabled = [];
  7130. this._uintIndicesCurrentlySet = false;
  7131. this._currentBoundBuffer = new Array();
  7132. this._currentBufferPointers = [];
  7133. this._currentInstanceLocations = new Array();
  7134. this._currentInstanceBuffers = new Array();
  7135. this._vaoRecordInProgress = false;
  7136. this._mustWipeVertexAttributes = false;
  7137. // Hardware supported Compressed Textures
  7138. this._texturesSupported = new Array();
  7139. this._onVRFullScreenTriggered = function () {
  7140. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7141. //get the old size before we change
  7142. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7143. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7144. //get the width and height, change the render size
  7145. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7146. var width, height;
  7147. _this.setHardwareScalingLevel(1);
  7148. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7149. }
  7150. else {
  7151. //When the specs are implemented, need to uncomment this.
  7152. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7153. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7154. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7155. _this._vrDisplayEnabled = undefined;
  7156. }
  7157. };
  7158. this._renderingCanvas = canvas;
  7159. Engine.Instances.push(this);
  7160. options = options || {};
  7161. if (antialias != null) {
  7162. options.antialias = antialias;
  7163. }
  7164. if (options.preserveDrawingBuffer === undefined) {
  7165. options.preserveDrawingBuffer = false;
  7166. }
  7167. if (options.audioEngine === undefined) {
  7168. options.audioEngine = true;
  7169. }
  7170. if (options.stencil === undefined) {
  7171. options.stencil = true;
  7172. }
  7173. // GL
  7174. if (!options.disableWebGL2Support) {
  7175. try {
  7176. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7177. if (this._gl) {
  7178. this._webGLVersion = 2.0;
  7179. }
  7180. }
  7181. catch (e) {
  7182. // Do nothing
  7183. }
  7184. }
  7185. if (!this._gl) {
  7186. if (!canvas) {
  7187. throw new Error("The provided canvas is null or undefined.");
  7188. }
  7189. try {
  7190. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7191. }
  7192. catch (e) {
  7193. throw new Error("WebGL not supported");
  7194. }
  7195. }
  7196. if (!this._gl) {
  7197. throw new Error("WebGL not supported");
  7198. }
  7199. this._onBlur = function () {
  7200. _this._windowIsBackground = true;
  7201. };
  7202. this._onFocus = function () {
  7203. _this._windowIsBackground = false;
  7204. };
  7205. this._onCanvasBlur = function () {
  7206. _this.onCanvasBlurObservable.notifyObservers(_this);
  7207. };
  7208. window.addEventListener("blur", this._onBlur);
  7209. window.addEventListener("focus", this._onFocus);
  7210. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7211. // Viewport
  7212. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7213. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7214. this.resize();
  7215. // Caps
  7216. this._isStencilEnable = options.stencil;
  7217. this._caps = new EngineCapabilities();
  7218. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7219. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7220. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7221. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7222. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7223. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7224. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7225. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7226. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7227. // Infos
  7228. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7229. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7230. if (rendererInfo != null) {
  7231. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7232. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7233. }
  7234. if (!this._glVendor) {
  7235. this._glVendor = "Unknown vendor";
  7236. }
  7237. if (!this._glRenderer) {
  7238. this._glRenderer = "Unknown renderer";
  7239. }
  7240. // Extensions
  7241. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7242. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7243. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7244. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7245. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7246. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7247. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7248. 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');
  7249. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7250. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7251. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7252. this._caps.highPrecisionShaderSupported = true;
  7253. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7254. // Checks if some of the format renders first to allow the use of webgl inspector.
  7255. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7256. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7257. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7258. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7259. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7260. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7261. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7262. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7263. // Vertex array object
  7264. if (this._webGLVersion > 1) {
  7265. this._caps.vertexArrayObject = true;
  7266. }
  7267. else {
  7268. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7269. if (vertexArrayObjectExtension != null) {
  7270. this._caps.vertexArrayObject = true;
  7271. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7272. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7273. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7274. }
  7275. else {
  7276. this._caps.vertexArrayObject = false;
  7277. }
  7278. }
  7279. // Instances count
  7280. if (this._webGLVersion > 1) {
  7281. this._caps.instancedArrays = true;
  7282. }
  7283. else {
  7284. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7285. if (instanceExtension != null) {
  7286. this._caps.instancedArrays = true;
  7287. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7288. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7289. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7290. }
  7291. else {
  7292. this._caps.instancedArrays = false;
  7293. }
  7294. }
  7295. // Intelligently add supported compressed formats in order to check for.
  7296. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7297. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7298. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7299. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7300. if (this._caps.astc)
  7301. this.texturesSupported.push('-astc.ktx');
  7302. if (this._caps.s3tc)
  7303. this.texturesSupported.push('-dxt.ktx');
  7304. if (this._caps.pvrtc)
  7305. this.texturesSupported.push('-pvrtc.ktx');
  7306. if (this._caps.etc2)
  7307. this.texturesSupported.push('-etc2.ktx');
  7308. if (this._caps.etc1)
  7309. this.texturesSupported.push('-etc1.ktx');
  7310. if (this._gl.getShaderPrecisionFormat) {
  7311. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7312. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7313. }
  7314. // Depth buffer
  7315. this.setDepthBuffer(true);
  7316. this.setDepthFunctionToLessOrEqual();
  7317. this.setDepthWrite(true);
  7318. // Fullscreen
  7319. this._onFullscreenChange = function () {
  7320. if (document.fullscreen !== undefined) {
  7321. _this.isFullscreen = document.fullscreen;
  7322. }
  7323. else if (document.mozFullScreen !== undefined) {
  7324. _this.isFullscreen = document.mozFullScreen;
  7325. }
  7326. else if (document.webkitIsFullScreen !== undefined) {
  7327. _this.isFullscreen = document.webkitIsFullScreen;
  7328. }
  7329. else if (document.msIsFullScreen !== undefined) {
  7330. _this.isFullscreen = document.msIsFullScreen;
  7331. }
  7332. // Pointer lock
  7333. if (_this.isFullscreen && _this._pointerLockRequested) {
  7334. canvas.requestPointerLock = canvas.requestPointerLock ||
  7335. canvas.msRequestPointerLock ||
  7336. canvas.mozRequestPointerLock ||
  7337. canvas.webkitRequestPointerLock;
  7338. if (canvas.requestPointerLock) {
  7339. canvas.requestPointerLock();
  7340. }
  7341. }
  7342. };
  7343. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7344. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7345. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7346. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7347. // Pointer lock
  7348. this._onPointerLockChange = function () {
  7349. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7350. document.webkitPointerLockElement === canvas ||
  7351. document.msPointerLockElement === canvas ||
  7352. document.pointerLockElement === canvas);
  7353. };
  7354. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7355. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7356. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7357. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7358. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7359. Engine.audioEngine = new BABYLON.AudioEngine();
  7360. }
  7361. //Load WebVR Devices
  7362. if (options.autoEnableWebVR) {
  7363. this.initWebVR();
  7364. }
  7365. //Detect if we are running on a faulty buggy OS.
  7366. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7367. //ua sniffing is the tool of the devil.
  7368. this._badOS = regexp.test(navigator.userAgent);
  7369. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7370. }
  7371. Object.defineProperty(Engine, "LastCreatedEngine", {
  7372. get: function () {
  7373. if (Engine.Instances.length === 0) {
  7374. return null;
  7375. }
  7376. return Engine.Instances[Engine.Instances.length - 1];
  7377. },
  7378. enumerable: true,
  7379. configurable: true
  7380. });
  7381. Object.defineProperty(Engine, "LastCreatedScene", {
  7382. get: function () {
  7383. var lastCreatedEngine = Engine.LastCreatedEngine;
  7384. if (!lastCreatedEngine) {
  7385. return null;
  7386. }
  7387. if (lastCreatedEngine.scenes.length === 0) {
  7388. return null;
  7389. }
  7390. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7391. },
  7392. enumerable: true,
  7393. configurable: true
  7394. });
  7395. /**
  7396. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7397. */
  7398. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7399. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7400. var engine = Engine.Instances[engineIndex];
  7401. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7402. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7403. }
  7404. }
  7405. };
  7406. Object.defineProperty(Engine, "NEVER", {
  7407. get: function () {
  7408. return Engine._NEVER;
  7409. },
  7410. enumerable: true,
  7411. configurable: true
  7412. });
  7413. Object.defineProperty(Engine, "ALWAYS", {
  7414. get: function () {
  7415. return Engine._ALWAYS;
  7416. },
  7417. enumerable: true,
  7418. configurable: true
  7419. });
  7420. Object.defineProperty(Engine, "LESS", {
  7421. get: function () {
  7422. return Engine._LESS;
  7423. },
  7424. enumerable: true,
  7425. configurable: true
  7426. });
  7427. Object.defineProperty(Engine, "EQUAL", {
  7428. get: function () {
  7429. return Engine._EQUAL;
  7430. },
  7431. enumerable: true,
  7432. configurable: true
  7433. });
  7434. Object.defineProperty(Engine, "LEQUAL", {
  7435. get: function () {
  7436. return Engine._LEQUAL;
  7437. },
  7438. enumerable: true,
  7439. configurable: true
  7440. });
  7441. Object.defineProperty(Engine, "GREATER", {
  7442. get: function () {
  7443. return Engine._GREATER;
  7444. },
  7445. enumerable: true,
  7446. configurable: true
  7447. });
  7448. Object.defineProperty(Engine, "GEQUAL", {
  7449. get: function () {
  7450. return Engine._GEQUAL;
  7451. },
  7452. enumerable: true,
  7453. configurable: true
  7454. });
  7455. Object.defineProperty(Engine, "NOTEQUAL", {
  7456. get: function () {
  7457. return Engine._NOTEQUAL;
  7458. },
  7459. enumerable: true,
  7460. configurable: true
  7461. });
  7462. Object.defineProperty(Engine, "KEEP", {
  7463. get: function () {
  7464. return Engine._KEEP;
  7465. },
  7466. enumerable: true,
  7467. configurable: true
  7468. });
  7469. Object.defineProperty(Engine, "REPLACE", {
  7470. get: function () {
  7471. return Engine._REPLACE;
  7472. },
  7473. enumerable: true,
  7474. configurable: true
  7475. });
  7476. Object.defineProperty(Engine, "INCR", {
  7477. get: function () {
  7478. return Engine._INCR;
  7479. },
  7480. enumerable: true,
  7481. configurable: true
  7482. });
  7483. Object.defineProperty(Engine, "DECR", {
  7484. get: function () {
  7485. return Engine._DECR;
  7486. },
  7487. enumerable: true,
  7488. configurable: true
  7489. });
  7490. Object.defineProperty(Engine, "INVERT", {
  7491. get: function () {
  7492. return Engine._INVERT;
  7493. },
  7494. enumerable: true,
  7495. configurable: true
  7496. });
  7497. Object.defineProperty(Engine, "INCR_WRAP", {
  7498. get: function () {
  7499. return Engine._INCR_WRAP;
  7500. },
  7501. enumerable: true,
  7502. configurable: true
  7503. });
  7504. Object.defineProperty(Engine, "DECR_WRAP", {
  7505. get: function () {
  7506. return Engine._DECR_WRAP;
  7507. },
  7508. enumerable: true,
  7509. configurable: true
  7510. });
  7511. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7512. get: function () {
  7513. return Engine._ALPHA_DISABLE;
  7514. },
  7515. enumerable: true,
  7516. configurable: true
  7517. });
  7518. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7519. get: function () {
  7520. return Engine._ALPHA_ONEONE;
  7521. },
  7522. enumerable: true,
  7523. configurable: true
  7524. });
  7525. Object.defineProperty(Engine, "ALPHA_ADD", {
  7526. get: function () {
  7527. return Engine._ALPHA_ADD;
  7528. },
  7529. enumerable: true,
  7530. configurable: true
  7531. });
  7532. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7533. get: function () {
  7534. return Engine._ALPHA_COMBINE;
  7535. },
  7536. enumerable: true,
  7537. configurable: true
  7538. });
  7539. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7540. get: function () {
  7541. return Engine._ALPHA_SUBTRACT;
  7542. },
  7543. enumerable: true,
  7544. configurable: true
  7545. });
  7546. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7547. get: function () {
  7548. return Engine._ALPHA_MULTIPLY;
  7549. },
  7550. enumerable: true,
  7551. configurable: true
  7552. });
  7553. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7554. get: function () {
  7555. return Engine._ALPHA_MAXIMIZED;
  7556. },
  7557. enumerable: true,
  7558. configurable: true
  7559. });
  7560. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7561. get: function () {
  7562. return Engine._ALPHA_PREMULTIPLIED;
  7563. },
  7564. enumerable: true,
  7565. configurable: true
  7566. });
  7567. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7568. get: function () {
  7569. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7570. },
  7571. enumerable: true,
  7572. configurable: true
  7573. });
  7574. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7575. get: function () {
  7576. return Engine._ALPHA_INTERPOLATE;
  7577. },
  7578. enumerable: true,
  7579. configurable: true
  7580. });
  7581. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7582. get: function () {
  7583. return Engine._DELAYLOADSTATE_NONE;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7589. get: function () {
  7590. return Engine._DELAYLOADSTATE_LOADED;
  7591. },
  7592. enumerable: true,
  7593. configurable: true
  7594. });
  7595. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7596. get: function () {
  7597. return Engine._DELAYLOADSTATE_LOADING;
  7598. },
  7599. enumerable: true,
  7600. configurable: true
  7601. });
  7602. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7603. get: function () {
  7604. return Engine._DELAYLOADSTATE_NOTLOADED;
  7605. },
  7606. enumerable: true,
  7607. configurable: true
  7608. });
  7609. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7610. get: function () {
  7611. return Engine._TEXTUREFORMAT_ALPHA;
  7612. },
  7613. enumerable: true,
  7614. configurable: true
  7615. });
  7616. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7617. get: function () {
  7618. return Engine._TEXTUREFORMAT_LUMINANCE;
  7619. },
  7620. enumerable: true,
  7621. configurable: true
  7622. });
  7623. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7624. get: function () {
  7625. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7626. },
  7627. enumerable: true,
  7628. configurable: true
  7629. });
  7630. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7631. get: function () {
  7632. return Engine._TEXTUREFORMAT_RGB;
  7633. },
  7634. enumerable: true,
  7635. configurable: true
  7636. });
  7637. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7638. get: function () {
  7639. return Engine._TEXTUREFORMAT_RGBA;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7645. get: function () {
  7646. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7647. },
  7648. enumerable: true,
  7649. configurable: true
  7650. });
  7651. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7652. get: function () {
  7653. return Engine._TEXTURETYPE_FLOAT;
  7654. },
  7655. enumerable: true,
  7656. configurable: true
  7657. });
  7658. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7659. get: function () {
  7660. return Engine._TEXTURETYPE_HALF_FLOAT;
  7661. },
  7662. enumerable: true,
  7663. configurable: true
  7664. });
  7665. Object.defineProperty(Engine, "Version", {
  7666. get: function () {
  7667. return "3.0-beta";
  7668. },
  7669. enumerable: true,
  7670. configurable: true
  7671. });
  7672. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7673. get: function () {
  7674. return this._texturesSupported;
  7675. },
  7676. enumerable: true,
  7677. configurable: true
  7678. });
  7679. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7680. get: function () {
  7681. return this._textureFormatInUse;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7687. // Empty texture
  7688. get: function () {
  7689. if (!this._emptyTexture) {
  7690. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7691. }
  7692. return this._emptyTexture;
  7693. },
  7694. enumerable: true,
  7695. configurable: true
  7696. });
  7697. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7698. get: function () {
  7699. if (!this._emptyCubeTexture) {
  7700. var faceData = new Uint8Array(4);
  7701. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7702. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7703. }
  7704. return this._emptyCubeTexture;
  7705. },
  7706. enumerable: true,
  7707. configurable: true
  7708. });
  7709. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7710. get: function () {
  7711. return this._webGLVersion;
  7712. },
  7713. enumerable: true,
  7714. configurable: true
  7715. });
  7716. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7717. /**
  7718. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7719. */
  7720. get: function () {
  7721. return this._isStencilEnable;
  7722. },
  7723. enumerable: true,
  7724. configurable: true
  7725. });
  7726. Engine.prototype._prepareWorkingCanvas = function () {
  7727. if (this._workingCanvas) {
  7728. return;
  7729. }
  7730. this._workingCanvas = document.createElement("canvas");
  7731. this._workingContext = this._workingCanvas.getContext("2d");
  7732. };
  7733. Engine.prototype.resetTextureCache = function () {
  7734. for (var index = 0; index < this._maxTextureChannels; index++) {
  7735. this._activeTexturesCache[index] = null;
  7736. }
  7737. };
  7738. Engine.prototype.getGlInfo = function () {
  7739. return {
  7740. vendor: this._glVendor,
  7741. renderer: this._glRenderer,
  7742. version: this._glVersion
  7743. };
  7744. };
  7745. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7746. if (useScreen === void 0) { useScreen = false; }
  7747. var viewport = camera.viewport;
  7748. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7749. };
  7750. Engine.prototype.getRenderWidth = function (useScreen) {
  7751. if (useScreen === void 0) { useScreen = false; }
  7752. if (!useScreen && this._currentRenderTarget) {
  7753. return this._currentRenderTarget._width;
  7754. }
  7755. return this._renderingCanvas.width;
  7756. };
  7757. Engine.prototype.getRenderHeight = function (useScreen) {
  7758. if (useScreen === void 0) { useScreen = false; }
  7759. if (!useScreen && this._currentRenderTarget) {
  7760. return this._currentRenderTarget._height;
  7761. }
  7762. return this._renderingCanvas.height;
  7763. };
  7764. Engine.prototype.getRenderingCanvas = function () {
  7765. return this._renderingCanvas;
  7766. };
  7767. Engine.prototype.getRenderingCanvasClientRect = function () {
  7768. return this._renderingCanvas.getBoundingClientRect();
  7769. };
  7770. Engine.prototype.setHardwareScalingLevel = function (level) {
  7771. this._hardwareScalingLevel = level;
  7772. this.resize();
  7773. };
  7774. Engine.prototype.getHardwareScalingLevel = function () {
  7775. return this._hardwareScalingLevel;
  7776. };
  7777. Engine.prototype.getLoadedTexturesCache = function () {
  7778. return this._loadedTexturesCache;
  7779. };
  7780. Engine.prototype.getCaps = function () {
  7781. return this._caps;
  7782. };
  7783. Object.defineProperty(Engine.prototype, "drawCalls", {
  7784. get: function () {
  7785. return this._drawCalls.current;
  7786. },
  7787. enumerable: true,
  7788. configurable: true
  7789. });
  7790. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7791. get: function () {
  7792. return this._drawCalls;
  7793. },
  7794. enumerable: true,
  7795. configurable: true
  7796. });
  7797. Engine.prototype.getDepthFunction = function () {
  7798. return this._depthCullingState.depthFunc;
  7799. };
  7800. Engine.prototype.setDepthFunction = function (depthFunc) {
  7801. this._depthCullingState.depthFunc = depthFunc;
  7802. };
  7803. Engine.prototype.setDepthFunctionToGreater = function () {
  7804. this._depthCullingState.depthFunc = this._gl.GREATER;
  7805. };
  7806. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7807. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7808. };
  7809. Engine.prototype.setDepthFunctionToLess = function () {
  7810. this._depthCullingState.depthFunc = this._gl.LESS;
  7811. };
  7812. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7813. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7814. };
  7815. Engine.prototype.getStencilBuffer = function () {
  7816. return this._stencilState.stencilTest;
  7817. };
  7818. Engine.prototype.setStencilBuffer = function (enable) {
  7819. this._stencilState.stencilTest = enable;
  7820. };
  7821. Engine.prototype.getStencilMask = function () {
  7822. return this._stencilState.stencilMask;
  7823. };
  7824. Engine.prototype.setStencilMask = function (mask) {
  7825. this._stencilState.stencilMask = mask;
  7826. };
  7827. Engine.prototype.getStencilFunction = function () {
  7828. return this._stencilState.stencilFunc;
  7829. };
  7830. Engine.prototype.getStencilFunctionReference = function () {
  7831. return this._stencilState.stencilFuncRef;
  7832. };
  7833. Engine.prototype.getStencilFunctionMask = function () {
  7834. return this._stencilState.stencilFuncMask;
  7835. };
  7836. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7837. this._stencilState.stencilFunc = stencilFunc;
  7838. };
  7839. Engine.prototype.setStencilFunctionReference = function (reference) {
  7840. this._stencilState.stencilFuncRef = reference;
  7841. };
  7842. Engine.prototype.setStencilFunctionMask = function (mask) {
  7843. this._stencilState.stencilFuncMask = mask;
  7844. };
  7845. Engine.prototype.getStencilOperationFail = function () {
  7846. return this._stencilState.stencilOpStencilFail;
  7847. };
  7848. Engine.prototype.getStencilOperationDepthFail = function () {
  7849. return this._stencilState.stencilOpDepthFail;
  7850. };
  7851. Engine.prototype.getStencilOperationPass = function () {
  7852. return this._stencilState.stencilOpStencilDepthPass;
  7853. };
  7854. Engine.prototype.setStencilOperationFail = function (operation) {
  7855. this._stencilState.stencilOpStencilFail = operation;
  7856. };
  7857. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7858. this._stencilState.stencilOpDepthFail = operation;
  7859. };
  7860. Engine.prototype.setStencilOperationPass = function (operation) {
  7861. this._stencilState.stencilOpStencilDepthPass = operation;
  7862. };
  7863. Engine.prototype.setDitheringState = function (value) {
  7864. if (value) {
  7865. this._gl.enable(this._gl.DITHER);
  7866. }
  7867. else {
  7868. this._gl.disable(this._gl.DITHER);
  7869. }
  7870. };
  7871. /**
  7872. * stop executing a render loop function and remove it from the execution array
  7873. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7874. */
  7875. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7876. if (!renderFunction) {
  7877. this._activeRenderLoops = [];
  7878. return;
  7879. }
  7880. var index = this._activeRenderLoops.indexOf(renderFunction);
  7881. if (index >= 0) {
  7882. this._activeRenderLoops.splice(index, 1);
  7883. }
  7884. };
  7885. Engine.prototype._renderLoop = function () {
  7886. var shouldRender = true;
  7887. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7888. shouldRender = false;
  7889. }
  7890. if (shouldRender) {
  7891. // Start new frame
  7892. this.beginFrame();
  7893. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7894. var renderFunction = this._activeRenderLoops[index];
  7895. renderFunction();
  7896. }
  7897. // Present
  7898. this.endFrame();
  7899. }
  7900. if (this._activeRenderLoops.length > 0) {
  7901. // Register new frame
  7902. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7903. }
  7904. else {
  7905. this._renderingQueueLaunched = false;
  7906. }
  7907. };
  7908. /**
  7909. * Register and execute a render loop. The engine can have more than one render function.
  7910. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7911. * @example
  7912. * engine.runRenderLoop(function () {
  7913. * scene.render()
  7914. * })
  7915. */
  7916. Engine.prototype.runRenderLoop = function (renderFunction) {
  7917. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7918. return;
  7919. }
  7920. this._activeRenderLoops.push(renderFunction);
  7921. if (!this._renderingQueueLaunched) {
  7922. this._renderingQueueLaunched = true;
  7923. this._bindedRenderFunction = this._renderLoop.bind(this);
  7924. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7925. }
  7926. };
  7927. /**
  7928. * Toggle full screen mode.
  7929. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7930. * @param {any} options - an options object to be sent to the requestFullscreen function
  7931. */
  7932. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7933. if (this.isFullscreen) {
  7934. BABYLON.Tools.ExitFullscreen();
  7935. }
  7936. else {
  7937. this._pointerLockRequested = requestPointerLock;
  7938. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7939. }
  7940. };
  7941. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7942. if (stencil === void 0) { stencil = false; }
  7943. this.applyStates();
  7944. var mode = 0;
  7945. if (backBuffer && color) {
  7946. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7947. mode |= this._gl.COLOR_BUFFER_BIT;
  7948. }
  7949. if (depth) {
  7950. this._gl.clearDepth(1.0);
  7951. mode |= this._gl.DEPTH_BUFFER_BIT;
  7952. }
  7953. if (stencil) {
  7954. this._gl.clearStencil(0);
  7955. mode |= this._gl.STENCIL_BUFFER_BIT;
  7956. }
  7957. this._gl.clear(mode);
  7958. };
  7959. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7960. var gl = this._gl;
  7961. // Save state
  7962. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7963. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7964. // Change state
  7965. gl.enable(gl.SCISSOR_TEST);
  7966. gl.scissor(x, y, width, height);
  7967. // Clear
  7968. this.clear(clearColor, true, true, true);
  7969. // Restore state
  7970. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7971. if (curScissor === true) {
  7972. gl.enable(gl.SCISSOR_TEST);
  7973. }
  7974. else {
  7975. gl.disable(gl.SCISSOR_TEST);
  7976. }
  7977. };
  7978. /**
  7979. * Set the WebGL's viewport
  7980. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7981. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7982. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7983. */
  7984. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7985. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7986. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7987. var x = viewport.x || 0;
  7988. var y = viewport.y || 0;
  7989. this._cachedViewport = viewport;
  7990. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7991. };
  7992. /**
  7993. * Directly set the WebGL Viewport
  7994. * The x, y, width & height are directly passed to the WebGL call
  7995. * @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.
  7996. */
  7997. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7998. var currentViewport = this._cachedViewport;
  7999. this._cachedViewport = null;
  8000. this._gl.viewport(x, y, width, height);
  8001. return currentViewport;
  8002. };
  8003. Engine.prototype.beginFrame = function () {
  8004. this._measureFps();
  8005. };
  8006. Engine.prototype.endFrame = function () {
  8007. //force a flush in case we are using a bad OS.
  8008. if (this._badOS) {
  8009. this.flushFramebuffer();
  8010. }
  8011. //submit frame to the vr device, if enabled
  8012. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8013. this._vrDisplayEnabled.submitFrame();
  8014. }
  8015. };
  8016. /**
  8017. * resize the view according to the canvas' size.
  8018. * @example
  8019. * window.addEventListener("resize", function () {
  8020. * engine.resize();
  8021. * });
  8022. */
  8023. Engine.prototype.resize = function () {
  8024. // We're not resizing the size of the canvas while in VR mode & presenting
  8025. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8026. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8027. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8028. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8029. }
  8030. };
  8031. /**
  8032. * force a specific size of the canvas
  8033. * @param {number} width - the new canvas' width
  8034. * @param {number} height - the new canvas' height
  8035. */
  8036. Engine.prototype.setSize = function (width, height) {
  8037. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8038. return;
  8039. }
  8040. this._renderingCanvas.width = width;
  8041. this._renderingCanvas.height = height;
  8042. for (var index = 0; index < this.scenes.length; index++) {
  8043. var scene = this.scenes[index];
  8044. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8045. var cam = scene.cameras[camIndex];
  8046. cam._currentRenderId = 0;
  8047. }
  8048. }
  8049. if (this.onResizeObservable.hasObservers) {
  8050. this.onResizeObservable.notifyObservers(this);
  8051. }
  8052. };
  8053. //WebVR functions
  8054. Engine.prototype.isVRDevicePresent = function (callback) {
  8055. this.getVRDevice(null, function (device) {
  8056. callback(device !== null);
  8057. });
  8058. };
  8059. Engine.prototype.getVRDevice = function (name, callback) {
  8060. if (!this.vrDisplaysPromise) {
  8061. callback(null);
  8062. return;
  8063. }
  8064. this.vrDisplaysPromise.then(function (devices) {
  8065. if (devices.length > 0) {
  8066. if (name) {
  8067. var found = devices.some(function (device) {
  8068. if (device.displayName === name) {
  8069. callback(device);
  8070. return true;
  8071. }
  8072. else {
  8073. return false;
  8074. }
  8075. });
  8076. if (!found) {
  8077. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8078. callback(devices[0]);
  8079. }
  8080. }
  8081. else {
  8082. //choose the first one
  8083. callback(devices[0]);
  8084. }
  8085. }
  8086. else {
  8087. BABYLON.Tools.Error("No WebVR devices found!");
  8088. callback(null);
  8089. }
  8090. });
  8091. };
  8092. Engine.prototype.initWebVR = function () {
  8093. if (!this.vrDisplaysPromise) {
  8094. this._getVRDisplays();
  8095. }
  8096. };
  8097. Engine.prototype.enableVR = function (vrDevice) {
  8098. this._vrDisplayEnabled = vrDevice;
  8099. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8100. };
  8101. Engine.prototype.disableVR = function () {
  8102. if (this._vrDisplayEnabled) {
  8103. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8104. }
  8105. };
  8106. Engine.prototype._getVRDisplays = function () {
  8107. var _this = this;
  8108. var getWebVRDevices = function (devices) {
  8109. var size = devices.length;
  8110. var i = 0;
  8111. _this._vrDisplays = devices.filter(function (device) {
  8112. return devices[i] instanceof VRDisplay;
  8113. });
  8114. return _this._vrDisplays;
  8115. };
  8116. //using a key due to typescript
  8117. if (navigator.getVRDisplays) {
  8118. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8119. }
  8120. };
  8121. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8122. this._currentRenderTarget = texture;
  8123. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8124. var gl = this._gl;
  8125. if (texture.isCube) {
  8126. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8127. }
  8128. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8129. this.wipeCaches();
  8130. };
  8131. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8132. if (this._currentFramebuffer !== framebuffer) {
  8133. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8134. this._currentFramebuffer = framebuffer;
  8135. }
  8136. };
  8137. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8138. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8139. this._currentRenderTarget = null;
  8140. // If MSAA, we need to bitblt back to main texture
  8141. var gl = this._gl;
  8142. if (texture._MSAAFramebuffer) {
  8143. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8144. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8145. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8146. }
  8147. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8148. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8149. gl.generateMipmap(gl.TEXTURE_2D);
  8150. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8151. }
  8152. if (onBeforeUnbind) {
  8153. if (texture._MSAAFramebuffer) {
  8154. // Bind the correct framebuffer
  8155. this.bindUnboundFramebuffer(texture._framebuffer);
  8156. }
  8157. onBeforeUnbind();
  8158. }
  8159. this.bindUnboundFramebuffer(null);
  8160. };
  8161. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8162. if (texture.generateMipMaps) {
  8163. var gl = this._gl;
  8164. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8165. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8166. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8167. }
  8168. };
  8169. Engine.prototype.flushFramebuffer = function () {
  8170. this._gl.flush();
  8171. };
  8172. Engine.prototype.restoreDefaultFramebuffer = function () {
  8173. this._currentRenderTarget = null;
  8174. this.bindUnboundFramebuffer(null);
  8175. this.setViewport(this._cachedViewport);
  8176. this.wipeCaches();
  8177. };
  8178. // UBOs
  8179. Engine.prototype.createUniformBuffer = function (elements) {
  8180. var ubo = this._gl.createBuffer();
  8181. this.bindUniformBuffer(ubo);
  8182. if (elements instanceof Float32Array) {
  8183. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8184. }
  8185. else {
  8186. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8187. }
  8188. this.bindUniformBuffer(null);
  8189. ubo.references = 1;
  8190. return ubo;
  8191. };
  8192. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8193. var ubo = this._gl.createBuffer();
  8194. this.bindUniformBuffer(ubo);
  8195. if (elements instanceof Float32Array) {
  8196. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8197. }
  8198. else {
  8199. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8200. }
  8201. this.bindUniformBuffer(null);
  8202. ubo.references = 1;
  8203. return ubo;
  8204. };
  8205. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8206. this.bindUniformBuffer(uniformBuffer);
  8207. if (offset === undefined) {
  8208. offset = 0;
  8209. }
  8210. if (count === undefined) {
  8211. if (elements instanceof Float32Array) {
  8212. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8213. }
  8214. else {
  8215. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8216. }
  8217. }
  8218. else {
  8219. if (elements instanceof Float32Array) {
  8220. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8221. }
  8222. else {
  8223. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8224. }
  8225. }
  8226. this.bindUniformBuffer(null);
  8227. };
  8228. // VBOs
  8229. Engine.prototype._resetVertexBufferBinding = function () {
  8230. this.bindArrayBuffer(null);
  8231. this._cachedVertexBuffers = null;
  8232. };
  8233. Engine.prototype.createVertexBuffer = function (vertices) {
  8234. var vbo = this._gl.createBuffer();
  8235. this.bindArrayBuffer(vbo);
  8236. if (vertices instanceof Float32Array) {
  8237. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8238. }
  8239. else {
  8240. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8241. }
  8242. this._resetVertexBufferBinding();
  8243. vbo.references = 1;
  8244. return vbo;
  8245. };
  8246. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8247. var vbo = this._gl.createBuffer();
  8248. this.bindArrayBuffer(vbo);
  8249. if (vertices instanceof Float32Array) {
  8250. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8251. }
  8252. else {
  8253. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8254. }
  8255. this._resetVertexBufferBinding();
  8256. vbo.references = 1;
  8257. return vbo;
  8258. };
  8259. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8260. this.bindArrayBuffer(vertexBuffer);
  8261. if (offset === undefined) {
  8262. offset = 0;
  8263. }
  8264. if (count === undefined) {
  8265. if (vertices instanceof Float32Array) {
  8266. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8267. }
  8268. else {
  8269. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8270. }
  8271. }
  8272. else {
  8273. if (vertices instanceof Float32Array) {
  8274. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8275. }
  8276. else {
  8277. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8278. }
  8279. }
  8280. this._resetVertexBufferBinding();
  8281. };
  8282. Engine.prototype._resetIndexBufferBinding = function () {
  8283. this.bindIndexBuffer(null);
  8284. this._cachedIndexBuffer = null;
  8285. };
  8286. Engine.prototype.createIndexBuffer = function (indices) {
  8287. var vbo = this._gl.createBuffer();
  8288. this.bindIndexBuffer(vbo);
  8289. // Check for 32 bits indices
  8290. var arrayBuffer;
  8291. var need32Bits = false;
  8292. if (indices instanceof Uint16Array) {
  8293. arrayBuffer = indices;
  8294. }
  8295. else {
  8296. //check 32 bit support
  8297. if (this._caps.uintIndices) {
  8298. if (indices instanceof Uint32Array) {
  8299. arrayBuffer = indices;
  8300. need32Bits = true;
  8301. }
  8302. else {
  8303. //number[] or Int32Array, check if 32 bit is necessary
  8304. for (var index = 0; index < indices.length; index++) {
  8305. if (indices[index] > 65535) {
  8306. need32Bits = true;
  8307. break;
  8308. }
  8309. }
  8310. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8311. }
  8312. }
  8313. else {
  8314. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8315. arrayBuffer = new Uint16Array(indices);
  8316. }
  8317. }
  8318. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8319. this._resetIndexBufferBinding();
  8320. vbo.references = 1;
  8321. vbo.is32Bits = need32Bits;
  8322. return vbo;
  8323. };
  8324. Engine.prototype.bindArrayBuffer = function (buffer) {
  8325. if (!this._vaoRecordInProgress) {
  8326. this._unBindVertexArrayObject();
  8327. }
  8328. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8329. };
  8330. Engine.prototype.bindUniformBuffer = function (buffer) {
  8331. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8332. };
  8333. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8334. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8335. };
  8336. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8337. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8338. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8339. };
  8340. ;
  8341. Engine.prototype.bindIndexBuffer = function (buffer) {
  8342. if (!this._vaoRecordInProgress) {
  8343. this._unBindVertexArrayObject();
  8344. }
  8345. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8346. };
  8347. Engine.prototype.bindBuffer = function (buffer, target) {
  8348. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8349. this._gl.bindBuffer(target, buffer);
  8350. this._currentBoundBuffer[target] = buffer;
  8351. }
  8352. };
  8353. Engine.prototype.updateArrayBuffer = function (data) {
  8354. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8355. };
  8356. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8357. var pointer = this._currentBufferPointers[indx];
  8358. var changed = false;
  8359. if (!pointer) {
  8360. changed = true;
  8361. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8362. }
  8363. else {
  8364. if (pointer.buffer !== buffer) {
  8365. pointer.buffer = buffer;
  8366. changed = true;
  8367. }
  8368. if (pointer.size !== size) {
  8369. pointer.size = size;
  8370. changed = true;
  8371. }
  8372. if (pointer.type !== type) {
  8373. pointer.type = type;
  8374. changed = true;
  8375. }
  8376. if (pointer.normalized !== normalized) {
  8377. pointer.normalized = normalized;
  8378. changed = true;
  8379. }
  8380. if (pointer.stride !== stride) {
  8381. pointer.stride = stride;
  8382. changed = true;
  8383. }
  8384. if (pointer.offset !== offset) {
  8385. pointer.offset = offset;
  8386. changed = true;
  8387. }
  8388. }
  8389. if (changed || this._vaoRecordInProgress) {
  8390. this.bindArrayBuffer(buffer);
  8391. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8392. }
  8393. };
  8394. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8395. if (indexBuffer == null) {
  8396. return;
  8397. }
  8398. if (this._cachedIndexBuffer !== indexBuffer) {
  8399. this._cachedIndexBuffer = indexBuffer;
  8400. this.bindIndexBuffer(indexBuffer);
  8401. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8402. }
  8403. };
  8404. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8405. var attributes = effect.getAttributesNames();
  8406. if (!this._vaoRecordInProgress) {
  8407. this._unBindVertexArrayObject();
  8408. }
  8409. this.unbindAllAttributes();
  8410. for (var index = 0; index < attributes.length; index++) {
  8411. var order = effect.getAttributeLocation(index);
  8412. if (order >= 0) {
  8413. var vertexBuffer = vertexBuffers[attributes[index]];
  8414. if (!vertexBuffer) {
  8415. continue;
  8416. }
  8417. this._gl.enableVertexAttribArray(order);
  8418. if (!this._vaoRecordInProgress) {
  8419. this._vertexAttribArraysEnabled[order] = true;
  8420. }
  8421. var buffer = vertexBuffer.getBuffer();
  8422. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8423. if (vertexBuffer.getIsInstanced()) {
  8424. this._gl.vertexAttribDivisor(order, 1);
  8425. if (!this._vaoRecordInProgress) {
  8426. this._currentInstanceLocations.push(order);
  8427. this._currentInstanceBuffers.push(buffer);
  8428. }
  8429. }
  8430. }
  8431. }
  8432. };
  8433. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8434. var vao = this._gl.createVertexArray();
  8435. this._vaoRecordInProgress = true;
  8436. this._gl.bindVertexArray(vao);
  8437. this._mustWipeVertexAttributes = true;
  8438. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8439. this.bindIndexBuffer(indexBuffer);
  8440. this._vaoRecordInProgress = false;
  8441. this._gl.bindVertexArray(null);
  8442. return vao;
  8443. };
  8444. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8445. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8446. this._cachedVertexArrayObject = vertexArrayObject;
  8447. this._gl.bindVertexArray(vertexArrayObject);
  8448. this._cachedVertexBuffers = null;
  8449. this._cachedIndexBuffer = null;
  8450. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8451. this._mustWipeVertexAttributes = true;
  8452. }
  8453. };
  8454. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8455. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8456. this._cachedVertexBuffers = vertexBuffer;
  8457. this._cachedEffectForVertexBuffers = effect;
  8458. var attributesCount = effect.getAttributesCount();
  8459. this._unBindVertexArrayObject();
  8460. this.unbindAllAttributes();
  8461. var offset = 0;
  8462. for (var index = 0; index < attributesCount; index++) {
  8463. if (index < vertexDeclaration.length) {
  8464. var order = effect.getAttributeLocation(index);
  8465. if (order >= 0) {
  8466. this._gl.enableVertexAttribArray(order);
  8467. this._vertexAttribArraysEnabled[order] = true;
  8468. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8469. }
  8470. offset += vertexDeclaration[index] * 4;
  8471. }
  8472. }
  8473. }
  8474. this._bindIndexBufferWithCache(indexBuffer);
  8475. };
  8476. Engine.prototype._unBindVertexArrayObject = function () {
  8477. if (!this._cachedVertexArrayObject) {
  8478. return;
  8479. }
  8480. this._cachedVertexArrayObject = null;
  8481. this._gl.bindVertexArray(null);
  8482. };
  8483. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8484. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8485. this._cachedVertexBuffers = vertexBuffers;
  8486. this._cachedEffectForVertexBuffers = effect;
  8487. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8488. }
  8489. this._bindIndexBufferWithCache(indexBuffer);
  8490. };
  8491. Engine.prototype.unbindInstanceAttributes = function () {
  8492. var boundBuffer;
  8493. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8494. var instancesBuffer = this._currentInstanceBuffers[i];
  8495. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8496. boundBuffer = instancesBuffer;
  8497. this.bindArrayBuffer(instancesBuffer);
  8498. }
  8499. var offsetLocation = this._currentInstanceLocations[i];
  8500. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8501. }
  8502. this._currentInstanceBuffers.length = 0;
  8503. this._currentInstanceLocations.length = 0;
  8504. };
  8505. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8506. this._gl.deleteVertexArray(vao);
  8507. };
  8508. Engine.prototype._releaseBuffer = function (buffer) {
  8509. buffer.references--;
  8510. if (buffer.references === 0) {
  8511. this._gl.deleteBuffer(buffer);
  8512. return true;
  8513. }
  8514. return false;
  8515. };
  8516. Engine.prototype.createInstancesBuffer = function (capacity) {
  8517. var buffer = this._gl.createBuffer();
  8518. buffer.capacity = capacity;
  8519. this.bindArrayBuffer(buffer);
  8520. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8521. return buffer;
  8522. };
  8523. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8524. this._gl.deleteBuffer(buffer);
  8525. };
  8526. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8527. this.bindArrayBuffer(instancesBuffer);
  8528. if (data) {
  8529. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8530. }
  8531. if (offsetLocations[0].index !== undefined) {
  8532. var stride = 0;
  8533. for (var i = 0; i < offsetLocations.length; i++) {
  8534. var ai = offsetLocations[i];
  8535. stride += ai.attributeSize * 4;
  8536. }
  8537. for (var i = 0; i < offsetLocations.length; i++) {
  8538. var ai = offsetLocations[i];
  8539. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8540. this._gl.enableVertexAttribArray(ai.index);
  8541. this._vertexAttribArraysEnabled[ai.index] = true;
  8542. }
  8543. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8544. this._gl.vertexAttribDivisor(ai.index, 1);
  8545. this._currentInstanceLocations.push(ai.index);
  8546. this._currentInstanceBuffers.push(instancesBuffer);
  8547. }
  8548. }
  8549. else {
  8550. for (var index = 0; index < 4; index++) {
  8551. var offsetLocation = offsetLocations[index];
  8552. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8553. this._gl.enableVertexAttribArray(offsetLocation);
  8554. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8555. }
  8556. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8557. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8558. this._currentInstanceLocations.push(offsetLocation);
  8559. this._currentInstanceBuffers.push(instancesBuffer);
  8560. }
  8561. }
  8562. };
  8563. Engine.prototype.applyStates = function () {
  8564. this._depthCullingState.apply(this._gl);
  8565. this._stencilState.apply(this._gl);
  8566. this._alphaState.apply(this._gl);
  8567. };
  8568. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8569. // Apply states
  8570. this.applyStates();
  8571. this._drawCalls.addCount(1, false);
  8572. // Render
  8573. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8574. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8575. if (instancesCount) {
  8576. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8577. return;
  8578. }
  8579. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8580. };
  8581. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8582. // Apply states
  8583. this.applyStates();
  8584. this._drawCalls.addCount(1, false);
  8585. if (instancesCount) {
  8586. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8587. return;
  8588. }
  8589. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8590. };
  8591. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8592. // Apply states
  8593. this.applyStates();
  8594. this._drawCalls.addCount(1, false);
  8595. if (instancesCount) {
  8596. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8597. return;
  8598. }
  8599. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8600. };
  8601. // Shaders
  8602. Engine.prototype._releaseEffect = function (effect) {
  8603. if (this._compiledEffects[effect._key]) {
  8604. delete this._compiledEffects[effect._key];
  8605. if (effect.getProgram()) {
  8606. this._gl.deleteProgram(effect.getProgram());
  8607. }
  8608. }
  8609. };
  8610. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8611. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8612. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8613. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8614. if (this._compiledEffects[name]) {
  8615. return this._compiledEffects[name];
  8616. }
  8617. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8618. effect._key = name;
  8619. this._compiledEffects[name] = effect;
  8620. return effect;
  8621. };
  8622. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8623. if (uniformsNames === void 0) { uniformsNames = []; }
  8624. if (samplers === void 0) { samplers = []; }
  8625. if (defines === void 0) { defines = ""; }
  8626. return this.createEffect({
  8627. vertex: "particles",
  8628. fragmentElement: fragmentName
  8629. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8630. };
  8631. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8632. context = context || this._gl;
  8633. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8634. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8635. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8636. var shaderProgram = context.createProgram();
  8637. context.attachShader(shaderProgram, vertexShader);
  8638. context.attachShader(shaderProgram, fragmentShader);
  8639. context.linkProgram(shaderProgram);
  8640. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8641. if (!linked) {
  8642. var error = context.getProgramInfoLog(shaderProgram);
  8643. if (error) {
  8644. throw new Error(error);
  8645. }
  8646. }
  8647. context.deleteShader(vertexShader);
  8648. context.deleteShader(fragmentShader);
  8649. return shaderProgram;
  8650. };
  8651. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8652. var results = [];
  8653. for (var index = 0; index < uniformsNames.length; index++) {
  8654. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8655. }
  8656. return results;
  8657. };
  8658. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8659. var results = [];
  8660. for (var index = 0; index < attributesNames.length; index++) {
  8661. try {
  8662. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8663. }
  8664. catch (e) {
  8665. results.push(-1);
  8666. }
  8667. }
  8668. return results;
  8669. };
  8670. Engine.prototype.enableEffect = function (effect) {
  8671. // Use program
  8672. this.setProgram(effect.getProgram());
  8673. this._currentEffect = effect;
  8674. if (effect.onBind) {
  8675. effect.onBind(effect);
  8676. }
  8677. };
  8678. Engine.prototype.setIntArray = function (uniform, array) {
  8679. if (!uniform)
  8680. return;
  8681. this._gl.uniform1iv(uniform, array);
  8682. };
  8683. Engine.prototype.setIntArray2 = function (uniform, array) {
  8684. if (!uniform || array.length % 2 !== 0)
  8685. return;
  8686. this._gl.uniform2iv(uniform, array);
  8687. };
  8688. Engine.prototype.setIntArray3 = function (uniform, array) {
  8689. if (!uniform || array.length % 3 !== 0)
  8690. return;
  8691. this._gl.uniform3iv(uniform, array);
  8692. };
  8693. Engine.prototype.setIntArray4 = function (uniform, array) {
  8694. if (!uniform || array.length % 4 !== 0)
  8695. return;
  8696. this._gl.uniform4iv(uniform, array);
  8697. };
  8698. Engine.prototype.setFloatArray = function (uniform, array) {
  8699. if (!uniform)
  8700. return;
  8701. this._gl.uniform1fv(uniform, array);
  8702. };
  8703. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8704. if (!uniform || array.length % 2 !== 0)
  8705. return;
  8706. this._gl.uniform2fv(uniform, array);
  8707. };
  8708. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8709. if (!uniform || array.length % 3 !== 0)
  8710. return;
  8711. this._gl.uniform3fv(uniform, array);
  8712. };
  8713. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8714. if (!uniform || array.length % 4 !== 0)
  8715. return;
  8716. this._gl.uniform4fv(uniform, array);
  8717. };
  8718. Engine.prototype.setArray = function (uniform, array) {
  8719. if (!uniform)
  8720. return;
  8721. this._gl.uniform1fv(uniform, array);
  8722. };
  8723. Engine.prototype.setArray2 = function (uniform, array) {
  8724. if (!uniform || array.length % 2 !== 0)
  8725. return;
  8726. this._gl.uniform2fv(uniform, array);
  8727. };
  8728. Engine.prototype.setArray3 = function (uniform, array) {
  8729. if (!uniform || array.length % 3 !== 0)
  8730. return;
  8731. this._gl.uniform3fv(uniform, array);
  8732. };
  8733. Engine.prototype.setArray4 = function (uniform, array) {
  8734. if (!uniform || array.length % 4 !== 0)
  8735. return;
  8736. this._gl.uniform4fv(uniform, array);
  8737. };
  8738. Engine.prototype.setMatrices = function (uniform, matrices) {
  8739. if (!uniform)
  8740. return;
  8741. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8742. };
  8743. Engine.prototype.setMatrix = function (uniform, matrix) {
  8744. if (!uniform)
  8745. return;
  8746. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8747. };
  8748. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8749. if (!uniform)
  8750. return;
  8751. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8752. };
  8753. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8754. if (!uniform)
  8755. return;
  8756. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8757. };
  8758. Engine.prototype.setFloat = function (uniform, value) {
  8759. if (!uniform)
  8760. return;
  8761. this._gl.uniform1f(uniform, value);
  8762. };
  8763. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8764. if (!uniform)
  8765. return;
  8766. this._gl.uniform2f(uniform, x, y);
  8767. };
  8768. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8769. if (!uniform)
  8770. return;
  8771. this._gl.uniform3f(uniform, x, y, z);
  8772. };
  8773. Engine.prototype.setBool = function (uniform, bool) {
  8774. if (!uniform)
  8775. return;
  8776. this._gl.uniform1i(uniform, bool);
  8777. };
  8778. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8779. if (!uniform)
  8780. return;
  8781. this._gl.uniform4f(uniform, x, y, z, w);
  8782. };
  8783. Engine.prototype.setColor3 = function (uniform, color3) {
  8784. if (!uniform)
  8785. return;
  8786. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8787. };
  8788. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8789. if (!uniform)
  8790. return;
  8791. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8792. };
  8793. // States
  8794. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8795. if (zOffset === void 0) { zOffset = 0; }
  8796. if (reverseSide === void 0) { reverseSide = false; }
  8797. // Culling
  8798. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8799. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8800. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8801. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8802. if (culling) {
  8803. this._depthCullingState.cullFace = cullFace;
  8804. this._depthCullingState.cull = true;
  8805. }
  8806. else {
  8807. this._depthCullingState.cull = false;
  8808. }
  8809. }
  8810. // Z offset
  8811. this._depthCullingState.zOffset = zOffset;
  8812. };
  8813. Engine.prototype.setDepthBuffer = function (enable) {
  8814. this._depthCullingState.depthTest = enable;
  8815. };
  8816. Engine.prototype.getDepthWrite = function () {
  8817. return this._depthCullingState.depthMask;
  8818. };
  8819. Engine.prototype.setDepthWrite = function (enable) {
  8820. this._depthCullingState.depthMask = enable;
  8821. };
  8822. Engine.prototype.setColorWrite = function (enable) {
  8823. this._gl.colorMask(enable, enable, enable, enable);
  8824. };
  8825. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8826. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8827. };
  8828. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8829. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8830. if (this._alphaMode === mode) {
  8831. return;
  8832. }
  8833. switch (mode) {
  8834. case Engine.ALPHA_DISABLE:
  8835. this._alphaState.alphaBlend = false;
  8836. break;
  8837. case Engine.ALPHA_PREMULTIPLIED:
  8838. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8839. this._alphaState.alphaBlend = true;
  8840. break;
  8841. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8842. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8843. this._alphaState.alphaBlend = true;
  8844. break;
  8845. case Engine.ALPHA_COMBINE:
  8846. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8847. this._alphaState.alphaBlend = true;
  8848. break;
  8849. case Engine.ALPHA_ONEONE:
  8850. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8851. this._alphaState.alphaBlend = true;
  8852. break;
  8853. case Engine.ALPHA_ADD:
  8854. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8855. this._alphaState.alphaBlend = true;
  8856. break;
  8857. case Engine.ALPHA_SUBTRACT:
  8858. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8859. this._alphaState.alphaBlend = true;
  8860. break;
  8861. case Engine.ALPHA_MULTIPLY:
  8862. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8863. this._alphaState.alphaBlend = true;
  8864. break;
  8865. case Engine.ALPHA_MAXIMIZED:
  8866. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8867. this._alphaState.alphaBlend = true;
  8868. break;
  8869. case Engine.ALPHA_INTERPOLATE:
  8870. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  8871. this._alphaState.alphaBlend = true;
  8872. break;
  8873. }
  8874. if (!noDepthWriteChange) {
  8875. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8876. }
  8877. this._alphaMode = mode;
  8878. };
  8879. Engine.prototype.getAlphaMode = function () {
  8880. return this._alphaMode;
  8881. };
  8882. Engine.prototype.setAlphaTesting = function (enable) {
  8883. this._alphaTest = enable;
  8884. };
  8885. Engine.prototype.getAlphaTesting = function () {
  8886. return !!this._alphaTest;
  8887. };
  8888. // Textures
  8889. Engine.prototype.wipeCaches = function (bruteForce) {
  8890. if (this.preventCacheWipeBetweenFrames) {
  8891. return;
  8892. }
  8893. this.resetTextureCache();
  8894. this._currentEffect = null;
  8895. // 6/8/2017: deltakosh: Should not be required anymore.
  8896. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  8897. if (bruteForce) {
  8898. this._stencilState.reset();
  8899. this._depthCullingState.reset();
  8900. this.setDepthFunctionToLessOrEqual();
  8901. this._alphaState.reset();
  8902. }
  8903. this._cachedVertexBuffers = null;
  8904. this._cachedIndexBuffer = null;
  8905. this._cachedEffectForVertexBuffers = null;
  8906. this._unBindVertexArrayObject();
  8907. this.bindIndexBuffer(null);
  8908. this.bindArrayBuffer(null);
  8909. };
  8910. /**
  8911. * Set the compressed texture format to use, based on the formats you have, and the formats
  8912. * supported by the hardware / browser.
  8913. *
  8914. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8915. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8916. * to API arguments needed to compressed textures. This puts the burden on the container
  8917. * generator to house the arcane code for determining these for current & future formats.
  8918. *
  8919. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8920. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8921. *
  8922. * Note: The result of this call is not taken into account when a texture is base64.
  8923. *
  8924. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8925. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8926. *
  8927. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  8928. * @returns The extension selected.
  8929. */
  8930. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8931. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8932. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8933. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8934. return this._textureFormatInUse = this._texturesSupported[i];
  8935. }
  8936. }
  8937. }
  8938. // actively set format to nothing, to allow this to be called more than once
  8939. // and possibly fail the 2nd time
  8940. return this._textureFormatInUse = null;
  8941. };
  8942. /**
  8943. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  8944. * @param {string} urlArg- This contains one of the following:
  8945. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  8946. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  8947. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  8948. *
  8949. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  8950. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  8951. * @param {Scene} scene- Needed for loading to the correct scene.
  8952. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  8953. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  8954. * @param {callback} onError- Optional callback to be called upon failure.
  8955. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  8956. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  8957. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  8958. *
  8959. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  8960. */
  8961. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  8962. var _this = this;
  8963. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8964. if (onLoad === void 0) { onLoad = null; }
  8965. if (onError === void 0) { onError = null; }
  8966. if (buffer === void 0) { buffer = null; }
  8967. var texture = fallBack ? fallBack : this._gl.createTexture();
  8968. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  8969. var fromData = url.substr(0, 5) === "data:";
  8970. var isBase64 = fromData && url.indexOf("base64") !== -1;
  8971. // establish the file extension, if possible
  8972. var lastDot = url.lastIndexOf('.');
  8973. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  8974. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8975. if (isDDS) {
  8976. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  8977. }
  8978. var isTGA = (extension === ".tga");
  8979. // determine if a ktx file should be substituted
  8980. var isKTX = false;
  8981. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  8982. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8983. isKTX = true;
  8984. }
  8985. scene._addPendingData(texture);
  8986. texture.url = url;
  8987. texture.noMipmap = noMipmap;
  8988. texture.references = 1;
  8989. texture.samplingMode = samplingMode;
  8990. texture.onLoadedCallbacks = [];
  8991. if (onLoad) {
  8992. texture.onLoadedCallbacks.push(onLoad);
  8993. }
  8994. if (!fallBack)
  8995. this._loadedTexturesCache.push(texture);
  8996. var onerror = function () {
  8997. scene._removePendingData(texture);
  8998. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  8999. if (isKTX) {
  9000. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9001. }
  9002. else if (onError) {
  9003. onError();
  9004. }
  9005. };
  9006. var callback;
  9007. // processing for non-image formats
  9008. if (isKTX || isTGA || isDDS) {
  9009. if (isKTX) {
  9010. callback = function (data) {
  9011. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9012. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9013. ktx.uploadLevels(_this._gl, !noMipmap);
  9014. }, samplingMode);
  9015. };
  9016. }
  9017. else if (isTGA) {
  9018. callback = function (arrayBuffer) {
  9019. var data = new Uint8Array(arrayBuffer);
  9020. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9021. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9022. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9023. }, samplingMode);
  9024. };
  9025. }
  9026. else if (isDDS) {
  9027. callback = function (data) {
  9028. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9029. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9030. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9031. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9032. }, samplingMode);
  9033. };
  9034. }
  9035. if (!buffer) {
  9036. BABYLON.Tools.LoadFile(url, function (data) {
  9037. callback(data);
  9038. }, null, scene.database, true, onerror);
  9039. }
  9040. else {
  9041. callback(buffer);
  9042. }
  9043. // image format processing
  9044. }
  9045. else {
  9046. var onload = function (img) {
  9047. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9048. var isPot = (img.width === potWidth && img.height === potHeight);
  9049. if (!isPot) {
  9050. _this._prepareWorkingCanvas();
  9051. _this._workingCanvas.width = potWidth;
  9052. _this._workingCanvas.height = potHeight;
  9053. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9054. _this._workingContext.imageSmoothingEnabled = false;
  9055. _this._workingContext.mozImageSmoothingEnabled = false;
  9056. _this._workingContext.oImageSmoothingEnabled = false;
  9057. _this._workingContext.webkitImageSmoothingEnabled = false;
  9058. _this._workingContext.msImageSmoothingEnabled = false;
  9059. }
  9060. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9061. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9062. _this._workingContext.imageSmoothingEnabled = true;
  9063. _this._workingContext.mozImageSmoothingEnabled = true;
  9064. _this._workingContext.oImageSmoothingEnabled = true;
  9065. _this._workingContext.webkitImageSmoothingEnabled = true;
  9066. _this._workingContext.msImageSmoothingEnabled = true;
  9067. }
  9068. }
  9069. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9070. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9071. }, samplingMode);
  9072. };
  9073. if (!fromData || isBase64)
  9074. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9075. else if (buffer instanceof Array || typeof buffer === "string")
  9076. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9077. else
  9078. onload(buffer);
  9079. }
  9080. return texture;
  9081. };
  9082. Engine.prototype._getInternalFormat = function (format) {
  9083. var internalFormat = this._gl.RGBA;
  9084. switch (format) {
  9085. case Engine.TEXTUREFORMAT_ALPHA:
  9086. internalFormat = this._gl.ALPHA;
  9087. break;
  9088. case Engine.TEXTUREFORMAT_LUMINANCE:
  9089. internalFormat = this._gl.LUMINANCE;
  9090. break;
  9091. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9092. internalFormat = this._gl.LUMINANCE_ALPHA;
  9093. break;
  9094. case Engine.TEXTUREFORMAT_RGB:
  9095. internalFormat = this._gl.RGB;
  9096. break;
  9097. case Engine.TEXTUREFORMAT_RGBA:
  9098. internalFormat = this._gl.RGBA;
  9099. break;
  9100. }
  9101. return internalFormat;
  9102. };
  9103. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9104. if (compression === void 0) { compression = null; }
  9105. var internalFormat = this._getInternalFormat(format);
  9106. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9107. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9108. if (texture._width % 4 !== 0) {
  9109. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9110. }
  9111. if (compression) {
  9112. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9113. }
  9114. else {
  9115. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9116. }
  9117. if (texture.generateMipMaps) {
  9118. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9119. }
  9120. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9121. this.resetTextureCache();
  9122. texture.isReady = true;
  9123. };
  9124. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9125. if (compression === void 0) { compression = null; }
  9126. var texture = this._gl.createTexture();
  9127. texture._baseWidth = width;
  9128. texture._baseHeight = height;
  9129. texture._width = width;
  9130. texture._height = height;
  9131. texture.references = 1;
  9132. this.updateRawTexture(texture, data, format, invertY, compression);
  9133. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9134. // Filters
  9135. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9136. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9137. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9138. if (generateMipMaps) {
  9139. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9140. }
  9141. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9142. texture.samplingMode = samplingMode;
  9143. this._loadedTexturesCache.push(texture);
  9144. return texture;
  9145. };
  9146. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9147. var texture = this._gl.createTexture();
  9148. texture._baseWidth = width;
  9149. texture._baseHeight = height;
  9150. if (generateMipMaps) {
  9151. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9152. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9153. }
  9154. this.resetTextureCache();
  9155. texture._width = width;
  9156. texture._height = height;
  9157. texture.isReady = false;
  9158. texture.generateMipMaps = generateMipMaps;
  9159. texture.references = 1;
  9160. texture.samplingMode = samplingMode;
  9161. this.updateTextureSamplingMode(samplingMode, texture);
  9162. this._loadedTexturesCache.push(texture);
  9163. return texture;
  9164. };
  9165. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9166. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9167. if (texture.isCube) {
  9168. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9169. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9170. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9171. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9172. }
  9173. else {
  9174. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9175. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9176. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9177. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9178. }
  9179. texture.samplingMode = samplingMode;
  9180. };
  9181. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9182. if (premulAlpha === void 0) { premulAlpha = false; }
  9183. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9184. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9185. if (premulAlpha) {
  9186. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9187. }
  9188. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9189. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9190. if (texture.generateMipMaps) {
  9191. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9192. }
  9193. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9194. if (premulAlpha) {
  9195. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9196. }
  9197. this.resetTextureCache();
  9198. texture.isReady = true;
  9199. };
  9200. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9201. if (texture._isDisabled) {
  9202. return;
  9203. }
  9204. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9205. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9206. try {
  9207. // Testing video texture support
  9208. if (this._videoTextureSupported === undefined) {
  9209. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9210. if (this._gl.getError() !== 0) {
  9211. this._videoTextureSupported = false;
  9212. }
  9213. else {
  9214. this._videoTextureSupported = true;
  9215. }
  9216. }
  9217. // Copy video through the current working canvas if video texture is not supported
  9218. if (!this._videoTextureSupported) {
  9219. if (!texture._workingCanvas) {
  9220. texture._workingCanvas = document.createElement("canvas");
  9221. texture._workingContext = texture._workingCanvas.getContext("2d");
  9222. texture._workingCanvas.width = texture._width;
  9223. texture._workingCanvas.height = texture._height;
  9224. }
  9225. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9226. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9227. }
  9228. else {
  9229. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9230. }
  9231. if (texture.generateMipMaps) {
  9232. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9233. }
  9234. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9235. this.resetTextureCache();
  9236. texture.isReady = true;
  9237. }
  9238. catch (ex) {
  9239. // Something unexpected
  9240. // Let's disable the texture
  9241. texture._isDisabled = true;
  9242. }
  9243. };
  9244. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9245. // old version had a "generateMipMaps" arg instead of options.
  9246. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9247. // in the same way, generateDepthBuffer is defaulted to true
  9248. var generateMipMaps = false;
  9249. var generateDepthBuffer = true;
  9250. var generateStencilBuffer = false;
  9251. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9252. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9253. if (options !== undefined) {
  9254. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9255. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9256. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9257. type = options.type === undefined ? type : options.type;
  9258. if (options.samplingMode !== undefined) {
  9259. samplingMode = options.samplingMode;
  9260. }
  9261. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9262. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9263. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9264. }
  9265. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9266. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9267. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9268. }
  9269. }
  9270. var gl = this._gl;
  9271. var texture = gl.createTexture();
  9272. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9273. var width = size.width || size;
  9274. var height = size.height || size;
  9275. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9276. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9277. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9278. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9279. }
  9280. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9281. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9284. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9285. // Create the framebuffer
  9286. var framebuffer = gl.createFramebuffer();
  9287. this.bindUnboundFramebuffer(framebuffer);
  9288. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9289. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9290. if (generateMipMaps) {
  9291. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9292. }
  9293. // Unbind
  9294. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9295. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9296. this.bindUnboundFramebuffer(null);
  9297. texture._framebuffer = framebuffer;
  9298. texture._baseWidth = width;
  9299. texture._baseHeight = height;
  9300. texture._width = width;
  9301. texture._height = height;
  9302. texture.isReady = true;
  9303. texture.samples = 1;
  9304. texture.generateMipMaps = generateMipMaps;
  9305. texture.references = 1;
  9306. texture.samplingMode = samplingMode;
  9307. texture.type = type;
  9308. texture._generateDepthBuffer = generateDepthBuffer;
  9309. texture._generateStencilBuffer = generateStencilBuffer;
  9310. this.resetTextureCache();
  9311. this._loadedTexturesCache.push(texture);
  9312. return texture;
  9313. };
  9314. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9315. var generateMipMaps = false;
  9316. var generateDepthBuffer = true;
  9317. var generateStencilBuffer = false;
  9318. var generateDepthTexture = false;
  9319. var textureCount = 1;
  9320. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9321. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9322. var types = [], samplingModes = [];
  9323. if (options !== undefined) {
  9324. generateMipMaps = options.generateMipMaps;
  9325. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9326. generateStencilBuffer = options.generateStencilBuffer;
  9327. generateDepthTexture = options.generateDepthTexture;
  9328. textureCount = options.textureCount || 1;
  9329. if (options.types) {
  9330. types = options.types;
  9331. }
  9332. if (options.samplingModes) {
  9333. samplingModes = options.samplingModes;
  9334. }
  9335. }
  9336. var gl = this._gl;
  9337. // Create the framebuffer
  9338. var framebuffer = gl.createFramebuffer();
  9339. this.bindUnboundFramebuffer(framebuffer);
  9340. var colorRenderbuffer = gl.createRenderbuffer();
  9341. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9342. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, width, height);
  9343. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  9344. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9345. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.RENDERBUFFER, colorRenderbuffer);
  9346. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, colorRenderbuffer);
  9347. var width = size.width || size;
  9348. var height = size.height || size;
  9349. var textures = [];
  9350. var attachments = [];
  9351. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9352. for (var i = 0; i < textureCount; i++) {
  9353. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9354. var type = types[i] || defaultType;
  9355. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9356. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9357. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9358. }
  9359. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9360. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9361. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9362. }
  9363. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9364. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9365. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9366. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9367. }
  9368. var texture = gl.createTexture();
  9369. var attachment = gl["COLOR_ATTACHMENT" + i];
  9370. textures.push(texture);
  9371. attachments.push(attachment);
  9372. gl.activeTexture(gl["TEXTURE" + i]);
  9373. gl.bindTexture(gl.TEXTURE_2D, texture);
  9374. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9376. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9377. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9378. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9379. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9380. if (generateMipMaps) {
  9381. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9382. }
  9383. // Unbind
  9384. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9385. texture._framebuffer = framebuffer;
  9386. texture._depthStencilBuffer = depthStencilBuffer;
  9387. texture._baseWidth = width;
  9388. texture._baseHeight = height;
  9389. texture._width = width;
  9390. texture._height = height;
  9391. texture.isReady = true;
  9392. texture.samples = 1;
  9393. texture.generateMipMaps = generateMipMaps;
  9394. texture.references = 1;
  9395. texture.samplingMode = samplingMode;
  9396. texture.type = type;
  9397. texture._generateDepthBuffer = generateDepthBuffer;
  9398. texture._generateStencilBuffer = generateStencilBuffer;
  9399. this._loadedTexturesCache.push(texture);
  9400. }
  9401. if (generateDepthTexture) {
  9402. // Depth texture
  9403. var depthTexture = gl.createTexture();
  9404. gl.activeTexture(gl.TEXTURE0);
  9405. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9406. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9407. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9408. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9409. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9410. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9411. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9412. depthTexture._framebuffer = framebuffer;
  9413. depthTexture._baseWidth = width;
  9414. depthTexture._baseHeight = height;
  9415. depthTexture._width = width;
  9416. depthTexture._height = height;
  9417. depthTexture.isReady = true;
  9418. depthTexture.samples = 1;
  9419. depthTexture.generateMipMaps = generateMipMaps;
  9420. depthTexture.references = 1;
  9421. depthTexture.samplingMode = gl.NEAREST;
  9422. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9423. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9424. textures.push(depthTexture);
  9425. this._loadedTexturesCache.push(depthTexture);
  9426. }
  9427. gl.drawBuffers(attachments);
  9428. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9429. this.bindUnboundFramebuffer(null);
  9430. this.resetTextureCache();
  9431. return textures;
  9432. };
  9433. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9434. if (samples === void 0) { samples = 1; }
  9435. var depthStencilBuffer = null;
  9436. var gl = this._gl;
  9437. // Create the depth/stencil buffer
  9438. if (generateStencilBuffer) {
  9439. depthStencilBuffer = gl.createRenderbuffer();
  9440. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9441. if (samples > 1) {
  9442. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9443. }
  9444. else {
  9445. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9446. }
  9447. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9448. }
  9449. else if (generateDepthBuffer) {
  9450. depthStencilBuffer = gl.createRenderbuffer();
  9451. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9452. if (samples > 1) {
  9453. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9454. }
  9455. else {
  9456. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9457. }
  9458. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9459. }
  9460. return depthStencilBuffer;
  9461. };
  9462. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9463. if (this.webGLVersion < 2) {
  9464. return 1;
  9465. }
  9466. if (texture.samples === samples) {
  9467. return samples;
  9468. }
  9469. var gl = this._gl;
  9470. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9471. // Dispose previous render buffers
  9472. if (texture._depthStencilBuffer) {
  9473. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9474. }
  9475. if (texture._MSAAFramebuffer) {
  9476. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9477. }
  9478. if (texture._MSAARenderBuffer) {
  9479. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9480. }
  9481. if (samples > 1) {
  9482. texture._MSAAFramebuffer = gl.createFramebuffer();
  9483. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9484. var colorRenderbuffer = gl.createRenderbuffer();
  9485. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9486. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9487. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9488. texture._MSAARenderBuffer = colorRenderbuffer;
  9489. }
  9490. else {
  9491. this.bindUnboundFramebuffer(texture._framebuffer);
  9492. }
  9493. texture.samples = samples;
  9494. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9495. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9496. this.bindUnboundFramebuffer(null);
  9497. return samples;
  9498. };
  9499. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9500. var gl = this._gl;
  9501. var texture = gl.createTexture();
  9502. var generateMipMaps = true;
  9503. var generateDepthBuffer = true;
  9504. var generateStencilBuffer = false;
  9505. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9506. if (options !== undefined) {
  9507. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9508. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9509. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9510. if (options.samplingMode !== undefined) {
  9511. samplingMode = options.samplingMode;
  9512. }
  9513. }
  9514. texture.isCube = true;
  9515. texture.references = 1;
  9516. texture.generateMipMaps = generateMipMaps;
  9517. texture.references = 1;
  9518. texture.samples = 1;
  9519. texture.samplingMode = samplingMode;
  9520. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9521. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9522. for (var face = 0; face < 6; face++) {
  9523. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9524. }
  9525. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9526. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9527. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9528. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9529. // Create the framebuffer
  9530. var framebuffer = gl.createFramebuffer();
  9531. this.bindUnboundFramebuffer(framebuffer);
  9532. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9533. // Mipmaps
  9534. if (texture.generateMipMaps) {
  9535. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9536. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9537. }
  9538. // Unbind
  9539. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9540. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9541. this.bindUnboundFramebuffer(null);
  9542. texture._framebuffer = framebuffer;
  9543. texture._width = size;
  9544. texture._height = size;
  9545. texture.isReady = true;
  9546. this.resetTextureCache();
  9547. this._loadedTexturesCache.push(texture);
  9548. return texture;
  9549. };
  9550. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9551. var _this = this;
  9552. if (onLoad === void 0) { onLoad = null; }
  9553. if (onError === void 0) { onError = null; }
  9554. var gl = this._gl;
  9555. var texture = gl.createTexture();
  9556. texture.isCube = true;
  9557. texture.url = rootUrl;
  9558. texture.references = 1;
  9559. texture.onLoadedCallbacks = [];
  9560. var isKTX = false;
  9561. var lastDot = rootUrl.lastIndexOf('.');
  9562. var extension = rootUrl.substring(lastDot).toLowerCase();
  9563. if (this._textureFormatInUse) {
  9564. extension = this._textureFormatInUse;
  9565. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9566. isKTX = true;
  9567. }
  9568. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9569. if (isDDS) {
  9570. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9571. }
  9572. if (isKTX) {
  9573. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9574. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9575. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9576. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9577. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9578. ktx.uploadLevels(_this._gl, !noMipmap);
  9579. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9580. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9581. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9582. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9583. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9584. _this.resetTextureCache();
  9585. texture._width = ktx.pixelWidth;
  9586. texture._height = ktx.pixelHeight;
  9587. texture.isReady = true;
  9588. }, null, null, true, onError);
  9589. }
  9590. else if (isDDS) {
  9591. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9592. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9593. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9594. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9595. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9596. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9597. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9598. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9599. }
  9600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9604. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9605. _this.resetTextureCache();
  9606. texture._width = info.width;
  9607. texture._height = info.height;
  9608. texture.isReady = true;
  9609. }, null, null, true, onError);
  9610. }
  9611. else {
  9612. cascadeLoad(rootUrl, scene, function (imgs) {
  9613. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9614. var height = width;
  9615. _this._prepareWorkingCanvas();
  9616. _this._workingCanvas.width = width;
  9617. _this._workingCanvas.height = height;
  9618. var faces = [
  9619. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9620. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9621. ];
  9622. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9623. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9624. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9625. for (var index = 0; index < faces.length; index++) {
  9626. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9627. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9628. }
  9629. if (!noMipmap) {
  9630. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9631. }
  9632. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9633. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9634. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9635. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9636. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9637. _this.resetTextureCache();
  9638. texture._width = width;
  9639. texture._height = height;
  9640. texture.isReady = true;
  9641. texture.onLoadedCallbacks.forEach(function (callback) {
  9642. callback();
  9643. });
  9644. if (onLoad) {
  9645. onLoad();
  9646. }
  9647. }, files, onError);
  9648. }
  9649. this._loadedTexturesCache.push(texture);
  9650. return texture;
  9651. };
  9652. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9653. texture._width = width;
  9654. texture._height = height;
  9655. texture._size = width * height;
  9656. texture._baseWidth = width;
  9657. texture._baseHeight = height;
  9658. };
  9659. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9660. if (compression === void 0) { compression = null; }
  9661. if (level === void 0) { level = 0; }
  9662. var gl = this._gl;
  9663. var textureType = this._getWebGLTextureType(type);
  9664. var internalFormat = this._getInternalFormat(format);
  9665. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9666. var needConversion = false;
  9667. if (internalFormat === gl.RGB) {
  9668. internalFormat = gl.RGBA;
  9669. needConversion = true;
  9670. }
  9671. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9672. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9673. if (texture._width % 4 !== 0) {
  9674. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9675. }
  9676. var facesIndex = [
  9677. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9678. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9679. ];
  9680. // Data are known to be in +X +Y +Z -X -Y -Z
  9681. for (var index = 0; index < facesIndex.length; index++) {
  9682. var faceData = data[index];
  9683. if (compression) {
  9684. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9685. }
  9686. else {
  9687. if (needConversion) {
  9688. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9689. }
  9690. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9691. }
  9692. }
  9693. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9694. if (isPot && texture.generateMipMaps && level === 0) {
  9695. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9696. }
  9697. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9698. this.resetTextureCache();
  9699. texture.isReady = true;
  9700. };
  9701. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9702. if (compression === void 0) { compression = null; }
  9703. var gl = this._gl;
  9704. var texture = gl.createTexture();
  9705. texture.isCube = true;
  9706. texture.references = 1;
  9707. var textureType = this._getWebGLTextureType(type);
  9708. var internalFormat = this._getInternalFormat(format);
  9709. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9710. var needConversion = false;
  9711. if (internalFormat === gl.RGB) {
  9712. internalFormat = gl.RGBA;
  9713. needConversion = true;
  9714. }
  9715. var width = size;
  9716. var height = width;
  9717. texture._width = width;
  9718. texture._height = height;
  9719. // Double check on POT to generate Mips.
  9720. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9721. if (!isPot) {
  9722. generateMipMaps = false;
  9723. }
  9724. texture.generateMipMaps = generateMipMaps;
  9725. // Upload data if needed. The texture won t be ready until then.
  9726. if (data) {
  9727. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9728. }
  9729. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9730. // Filters
  9731. if (data && generateMipMaps) {
  9732. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9733. }
  9734. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9736. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9737. }
  9738. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9739. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9740. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9741. }
  9742. else {
  9743. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9744. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9745. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9746. }
  9747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9749. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9750. this._loadedTexturesCache.push(texture);
  9751. return texture;
  9752. };
  9753. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9754. var _this = this;
  9755. if (onLoad === void 0) { onLoad = null; }
  9756. if (onError === void 0) { onError = null; }
  9757. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9758. if (invertY === void 0) { invertY = false; }
  9759. var gl = this._gl;
  9760. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9761. scene._addPendingData(texture);
  9762. texture.url = url;
  9763. var onerror = function () {
  9764. scene._removePendingData(texture);
  9765. if (onError) {
  9766. onError();
  9767. }
  9768. };
  9769. var internalCallback = function (data) {
  9770. var rgbeDataArrays = callback(data);
  9771. var facesIndex = [
  9772. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9773. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9774. ];
  9775. var width = texture._width;
  9776. var height = texture._height;
  9777. if (mipmmapGenerator) {
  9778. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9779. // I ll remove ASAP.
  9780. var textureType = _this._getWebGLTextureType(type);
  9781. var internalFormat = _this._getInternalFormat(format);
  9782. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9783. var needConversion = false;
  9784. if (internalFormat === gl.RGB) {
  9785. internalFormat = gl.RGBA;
  9786. needConversion = true;
  9787. }
  9788. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9789. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9790. var arrayTemp = [];
  9791. // Data are known to be in +X +Y +Z -X -Y -Z
  9792. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9793. arrayTemp.push(rgbeDataArrays[0]); // +X
  9794. arrayTemp.push(rgbeDataArrays[3]); // -X
  9795. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9796. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9797. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9798. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9799. var mipData = mipmmapGenerator(arrayTemp);
  9800. // mipData is order in +X -X +Y -Y +Z -Z
  9801. var mipFaces = [0, 2, 4, 1, 3, 5];
  9802. for (var level = 0; level < mipData.length; level++) {
  9803. var mipSize = width >> level;
  9804. for (var mipIndex in mipFaces) {
  9805. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9806. if (needConversion) {
  9807. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9808. }
  9809. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9810. }
  9811. }
  9812. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9813. }
  9814. else {
  9815. texture.generateMipMaps = !noMipmap;
  9816. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9817. }
  9818. texture.isReady = true;
  9819. _this.resetTextureCache();
  9820. scene._removePendingData(texture);
  9821. if (onLoad) {
  9822. onLoad();
  9823. }
  9824. };
  9825. BABYLON.Tools.LoadFile(url, function (data) {
  9826. internalCallback(data);
  9827. }, onerror, scene.database, true);
  9828. return texture;
  9829. };
  9830. ;
  9831. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9832. // Create new RGBA data container.
  9833. var rgbaData;
  9834. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9835. rgbaData = new Float32Array(width * height * 4);
  9836. }
  9837. else {
  9838. rgbaData = new Uint32Array(width * height * 4);
  9839. }
  9840. // Convert each pixel.
  9841. for (var x = 0; x < width; x++) {
  9842. for (var y = 0; y < height; y++) {
  9843. var index = (y * width + x) * 3;
  9844. var newIndex = (y * width + x) * 4;
  9845. // Map Old Value to new value.
  9846. rgbaData[newIndex + 0] = rgbData[index + 0];
  9847. rgbaData[newIndex + 1] = rgbData[index + 1];
  9848. rgbaData[newIndex + 2] = rgbData[index + 2];
  9849. // Add fully opaque alpha channel.
  9850. rgbaData[newIndex + 3] = 1;
  9851. }
  9852. }
  9853. return rgbaData;
  9854. };
  9855. Engine.prototype._releaseTexture = function (texture) {
  9856. var gl = this._gl;
  9857. if (texture._framebuffer) {
  9858. gl.deleteFramebuffer(texture._framebuffer);
  9859. }
  9860. if (texture._depthStencilBuffer) {
  9861. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9862. }
  9863. if (texture._MSAAFramebuffer) {
  9864. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9865. }
  9866. if (texture._MSAARenderBuffer) {
  9867. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9868. }
  9869. gl.deleteTexture(texture);
  9870. // Unbind channels
  9871. this.unbindAllTextures();
  9872. var index = this._loadedTexturesCache.indexOf(texture);
  9873. if (index !== -1) {
  9874. this._loadedTexturesCache.splice(index, 1);
  9875. }
  9876. };
  9877. Engine.prototype.setProgram = function (program) {
  9878. if (this._currentProgram !== program) {
  9879. this._gl.useProgram(program);
  9880. this._currentProgram = program;
  9881. }
  9882. };
  9883. Engine.prototype.bindSamplers = function (effect) {
  9884. this.setProgram(effect.getProgram());
  9885. var samplers = effect.getSamplers();
  9886. for (var index = 0; index < samplers.length; index++) {
  9887. var uniform = effect.getUniform(samplers[index]);
  9888. this._gl.uniform1i(uniform, index);
  9889. }
  9890. this._currentEffect = null;
  9891. };
  9892. Engine.prototype.activateTexture = function (texture) {
  9893. if (this._activeTexture !== texture) {
  9894. this._gl.activeTexture(texture);
  9895. this._activeTexture = texture;
  9896. }
  9897. };
  9898. Engine.prototype._bindTextureDirectly = function (target, texture) {
  9899. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  9900. this._gl.bindTexture(target, texture);
  9901. this._activeTexturesCache[this._activeTexture] = texture;
  9902. }
  9903. };
  9904. Engine.prototype._bindTexture = function (channel, texture) {
  9905. if (channel < 0) {
  9906. return;
  9907. }
  9908. this.activateTexture(this._gl.TEXTURE0 + channel);
  9909. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9910. };
  9911. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9912. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  9913. };
  9914. Engine.prototype.unbindAllTextures = function () {
  9915. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  9916. this.activateTexture(this._gl["TEXTURE" + channel]);
  9917. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9918. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9919. }
  9920. };
  9921. Engine.prototype.setTexture = function (channel, uniform, texture) {
  9922. if (channel < 0) {
  9923. return;
  9924. }
  9925. this._gl.uniform1i(uniform, channel);
  9926. this._setTexture(channel, texture);
  9927. };
  9928. Engine.prototype._setTexture = function (channel, texture) {
  9929. // Not ready?
  9930. if (!texture) {
  9931. if (this._activeTexturesCache[channel] != null) {
  9932. this.activateTexture(this._gl["TEXTURE" + channel]);
  9933. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9934. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9935. }
  9936. return;
  9937. }
  9938. // Video
  9939. var alreadyActivated = false;
  9940. if (texture.video) {
  9941. this.activateTexture(this._gl["TEXTURE" + channel]);
  9942. alreadyActivated = true;
  9943. texture.update();
  9944. }
  9945. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  9946. texture.delayLoad();
  9947. return;
  9948. }
  9949. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  9950. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  9951. if (this._activeTexturesCache[channel] === internalTexture) {
  9952. return;
  9953. }
  9954. if (!alreadyActivated) {
  9955. this.activateTexture(this._gl["TEXTURE" + channel]);
  9956. }
  9957. if (internalTexture.isCube) {
  9958. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  9959. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  9960. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  9961. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  9962. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  9963. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  9964. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  9965. }
  9966. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  9967. }
  9968. else {
  9969. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  9970. if (internalTexture._cachedWrapU !== texture.wrapU) {
  9971. internalTexture._cachedWrapU = texture.wrapU;
  9972. switch (texture.wrapU) {
  9973. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9974. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  9975. break;
  9976. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9977. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  9978. break;
  9979. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9980. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  9981. break;
  9982. }
  9983. }
  9984. if (internalTexture._cachedWrapV !== texture.wrapV) {
  9985. internalTexture._cachedWrapV = texture.wrapV;
  9986. switch (texture.wrapV) {
  9987. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9988. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  9989. break;
  9990. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9991. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  9992. break;
  9993. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9994. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  9995. break;
  9996. }
  9997. }
  9998. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  9999. }
  10000. };
  10001. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10002. if (channel < 0) {
  10003. return;
  10004. }
  10005. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10006. this._textureUnits = new Int32Array(textures.length);
  10007. }
  10008. for (var i = 0; i < textures.length; i++) {
  10009. this._textureUnits[i] = channel + i;
  10010. }
  10011. this._gl.uniform1iv(uniform, this._textureUnits);
  10012. for (var index = 0; index < textures.length; index++) {
  10013. this._setTexture(channel + index, textures[index]);
  10014. }
  10015. };
  10016. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10017. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10018. var value = texture.anisotropicFilteringLevel;
  10019. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10020. value = 1;
  10021. }
  10022. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10023. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10024. texture._cachedAnisotropicFilteringLevel = value;
  10025. }
  10026. };
  10027. Engine.prototype.readPixels = function (x, y, width, height) {
  10028. var data = new Uint8Array(height * width * 4);
  10029. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10030. return data;
  10031. };
  10032. /**
  10033. * Add an externaly attached data from its key.
  10034. * This method call will fail and return false, if such key already exists.
  10035. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10036. * @param key the unique key that identifies the data
  10037. * @param data the data object to associate to the key for this Engine instance
  10038. * @return true if no such key were already present and the data was added successfully, false otherwise
  10039. */
  10040. Engine.prototype.addExternalData = function (key, data) {
  10041. if (!this._externalData) {
  10042. this._externalData = new BABYLON.StringDictionary();
  10043. }
  10044. return this._externalData.add(key, data);
  10045. };
  10046. /**
  10047. * Get an externaly attached data from its key
  10048. * @param key the unique key that identifies the data
  10049. * @return the associated data, if present (can be null), or undefined if not present
  10050. */
  10051. Engine.prototype.getExternalData = function (key) {
  10052. if (!this._externalData) {
  10053. this._externalData = new BABYLON.StringDictionary();
  10054. }
  10055. return this._externalData.get(key);
  10056. };
  10057. /**
  10058. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10059. * @param key the unique key that identifies the data
  10060. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10061. * @return the associated data, can be null if the factory returned null.
  10062. */
  10063. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10064. if (!this._externalData) {
  10065. this._externalData = new BABYLON.StringDictionary();
  10066. }
  10067. return this._externalData.getOrAddWithFactory(key, factory);
  10068. };
  10069. /**
  10070. * Remove an externaly attached data from the Engine instance
  10071. * @param key the unique key that identifies the data
  10072. * @return true if the data was successfully removed, false if it doesn't exist
  10073. */
  10074. Engine.prototype.removeExternalData = function (key) {
  10075. if (!this._externalData) {
  10076. this._externalData = new BABYLON.StringDictionary();
  10077. }
  10078. return this._externalData.remove(key);
  10079. };
  10080. Engine.prototype.releaseInternalTexture = function (texture) {
  10081. if (!texture) {
  10082. return;
  10083. }
  10084. texture.references--;
  10085. // Final reference ?
  10086. if (texture.references === 0) {
  10087. var texturesCache = this.getLoadedTexturesCache();
  10088. var index = texturesCache.indexOf(texture);
  10089. if (index > -1) {
  10090. texturesCache.splice(index, 1);
  10091. }
  10092. this._releaseTexture(texture);
  10093. }
  10094. };
  10095. Engine.prototype.unbindAllAttributes = function () {
  10096. if (this._mustWipeVertexAttributes) {
  10097. this._mustWipeVertexAttributes = false;
  10098. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10099. this._gl.disableVertexAttribArray(i);
  10100. this._vertexAttribArraysEnabled[i] = false;
  10101. this._currentBufferPointers[i] = null;
  10102. }
  10103. return;
  10104. }
  10105. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10106. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10107. continue;
  10108. }
  10109. this._gl.disableVertexAttribArray(i);
  10110. this._vertexAttribArraysEnabled[i] = false;
  10111. this._currentBufferPointers[i] = null;
  10112. }
  10113. };
  10114. Engine.prototype.releaseEffects = function () {
  10115. for (var name in this._compiledEffects) {
  10116. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10117. }
  10118. this._compiledEffects = {};
  10119. };
  10120. // Dispose
  10121. Engine.prototype.dispose = function () {
  10122. this.hideLoadingUI();
  10123. this.stopRenderLoop();
  10124. // Empty texture
  10125. if (this._emptyTexture) {
  10126. this._releaseTexture(this._emptyTexture);
  10127. this._emptyTexture = null;
  10128. }
  10129. if (this._emptyCubeTexture) {
  10130. this._releaseTexture(this._emptyCubeTexture);
  10131. this._emptyCubeTexture = null;
  10132. }
  10133. // Release scenes
  10134. while (this.scenes.length) {
  10135. this.scenes[0].dispose();
  10136. }
  10137. // Release audio engine
  10138. if (Engine.audioEngine) {
  10139. Engine.audioEngine.dispose();
  10140. }
  10141. // Release effects
  10142. this.releaseEffects();
  10143. // Unbind
  10144. this.unbindAllAttributes();
  10145. this._gl = null;
  10146. //WebVR
  10147. this.disableVR();
  10148. // Events
  10149. window.removeEventListener("blur", this._onBlur);
  10150. window.removeEventListener("focus", this._onFocus);
  10151. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10152. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10153. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10154. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10155. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10156. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10157. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10158. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10159. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10160. // Remove from Instances
  10161. var index = Engine.Instances.indexOf(this);
  10162. if (index >= 0) {
  10163. Engine.Instances.splice(index, 1);
  10164. }
  10165. };
  10166. // Loading screen
  10167. Engine.prototype.displayLoadingUI = function () {
  10168. var loadingScreen = this.loadingScreen;
  10169. if (loadingScreen) {
  10170. loadingScreen.displayLoadingUI();
  10171. }
  10172. };
  10173. Engine.prototype.hideLoadingUI = function () {
  10174. var loadingScreen = this.loadingScreen;
  10175. if (loadingScreen) {
  10176. loadingScreen.hideLoadingUI();
  10177. }
  10178. };
  10179. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10180. get: function () {
  10181. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10182. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10183. return this._loadingScreen;
  10184. },
  10185. set: function (loadingScreen) {
  10186. this._loadingScreen = loadingScreen;
  10187. },
  10188. enumerable: true,
  10189. configurable: true
  10190. });
  10191. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10192. set: function (text) {
  10193. this.loadingScreen.loadingUIText = text;
  10194. },
  10195. enumerable: true,
  10196. configurable: true
  10197. });
  10198. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10199. set: function (color) {
  10200. this.loadingScreen.loadingUIBackgroundColor = color;
  10201. },
  10202. enumerable: true,
  10203. configurable: true
  10204. });
  10205. Engine.prototype.attachContextLostEvent = function (callback) {
  10206. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10207. };
  10208. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10209. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10210. };
  10211. Engine.prototype.getVertexShaderSource = function (program) {
  10212. var shaders = this._gl.getAttachedShaders(program);
  10213. return this._gl.getShaderSource(shaders[0]);
  10214. };
  10215. Engine.prototype.getFragmentShaderSource = function (program) {
  10216. var shaders = this._gl.getAttachedShaders(program);
  10217. return this._gl.getShaderSource(shaders[1]);
  10218. };
  10219. // FPS
  10220. Engine.prototype.getFps = function () {
  10221. return this.fps;
  10222. };
  10223. Engine.prototype.getDeltaTime = function () {
  10224. return this.deltaTime;
  10225. };
  10226. Engine.prototype._measureFps = function () {
  10227. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10228. var length = this.previousFramesDuration.length;
  10229. if (length >= 2) {
  10230. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10231. }
  10232. if (length >= this.fpsRange) {
  10233. if (length > this.fpsRange) {
  10234. this.previousFramesDuration.splice(0, 1);
  10235. length = this.previousFramesDuration.length;
  10236. }
  10237. var sum = 0;
  10238. for (var id = 0; id < length - 1; id++) {
  10239. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10240. }
  10241. this.fps = 1000.0 / (sum / (length - 1));
  10242. }
  10243. };
  10244. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10245. if (this._webGLVersion > 1) {
  10246. return this._caps.colorBufferFloat;
  10247. }
  10248. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10249. };
  10250. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10251. if (this._webGLVersion > 1) {
  10252. return this._caps.colorBufferFloat;
  10253. }
  10254. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10255. };
  10256. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10257. Engine.prototype._canRenderToFramebuffer = function (type) {
  10258. var gl = this._gl;
  10259. //clear existing errors
  10260. while (gl.getError() !== gl.NO_ERROR) { }
  10261. var successful = true;
  10262. var texture = gl.createTexture();
  10263. gl.bindTexture(gl.TEXTURE_2D, texture);
  10264. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10267. var fb = gl.createFramebuffer();
  10268. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10269. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10270. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10271. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10272. successful = successful && (gl.getError() === gl.NO_ERROR);
  10273. //try render by clearing frame buffer's color buffer
  10274. if (successful) {
  10275. gl.clear(gl.COLOR_BUFFER_BIT);
  10276. successful = successful && (gl.getError() === gl.NO_ERROR);
  10277. }
  10278. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10279. if (successful) {
  10280. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10281. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10282. var readFormat = gl.RGBA;
  10283. var readType = gl.UNSIGNED_BYTE;
  10284. var buffer = new Uint8Array(4);
  10285. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10286. successful = successful && (gl.getError() === gl.NO_ERROR);
  10287. }
  10288. //clean up
  10289. gl.deleteTexture(texture);
  10290. gl.deleteFramebuffer(fb);
  10291. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10292. //clear accumulated errors
  10293. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10294. return successful;
  10295. };
  10296. Engine.prototype._getWebGLTextureType = function (type) {
  10297. if (type === Engine.TEXTURETYPE_FLOAT) {
  10298. return this._gl.FLOAT;
  10299. }
  10300. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10301. // Add Half Float Constant.
  10302. return Engine.HALF_FLOAT_OES;
  10303. }
  10304. return this._gl.UNSIGNED_BYTE;
  10305. };
  10306. ;
  10307. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10308. if (this._webGLVersion === 1) {
  10309. return this._gl.RGBA;
  10310. }
  10311. if (type === Engine.TEXTURETYPE_FLOAT) {
  10312. return Engine.RGBA32F;
  10313. }
  10314. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10315. return Engine.RGBA16F;
  10316. }
  10317. return this._gl.RGBA;
  10318. };
  10319. ;
  10320. // Statics
  10321. Engine.isSupported = function () {
  10322. try {
  10323. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10324. if (navigator.isCocoonJS) {
  10325. return true;
  10326. }
  10327. var tempcanvas = document.createElement("canvas");
  10328. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10329. return gl != null && !!window.WebGLRenderingContext;
  10330. }
  10331. catch (e) {
  10332. return false;
  10333. }
  10334. };
  10335. return Engine;
  10336. }());
  10337. Engine.Instances = new Array();
  10338. // Const statics
  10339. Engine._ALPHA_DISABLE = 0;
  10340. Engine._ALPHA_ADD = 1;
  10341. Engine._ALPHA_COMBINE = 2;
  10342. Engine._ALPHA_SUBTRACT = 3;
  10343. Engine._ALPHA_MULTIPLY = 4;
  10344. Engine._ALPHA_MAXIMIZED = 5;
  10345. Engine._ALPHA_ONEONE = 6;
  10346. Engine._ALPHA_PREMULTIPLIED = 7;
  10347. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10348. Engine._ALPHA_INTERPOLATE = 9;
  10349. Engine._DELAYLOADSTATE_NONE = 0;
  10350. Engine._DELAYLOADSTATE_LOADED = 1;
  10351. Engine._DELAYLOADSTATE_LOADING = 2;
  10352. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10353. Engine._TEXTUREFORMAT_ALPHA = 0;
  10354. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10355. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10356. Engine._TEXTUREFORMAT_RGB = 4;
  10357. Engine._TEXTUREFORMAT_RGBA = 5;
  10358. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10359. Engine._TEXTURETYPE_FLOAT = 1;
  10360. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10361. // Depht or Stencil test Constants.
  10362. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10363. 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.
  10364. 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.
  10365. 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.
  10366. 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.
  10367. 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.
  10368. 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.
  10369. 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.
  10370. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10371. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10372. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10373. // Stencil Actions Constants.
  10374. Engine._KEEP = 0x1E00;
  10375. Engine._REPLACE = 0x1E01;
  10376. Engine._INCR = 0x1E02;
  10377. Engine._DECR = 0x1E03;
  10378. Engine._INVERT = 0x150A;
  10379. Engine._INCR_WRAP = 0x8507;
  10380. Engine._DECR_WRAP = 0x8508;
  10381. // Updatable statics so stick with vars here
  10382. Engine.CollisionsEpsilon = 0.001;
  10383. Engine.CodeRepository = "src/";
  10384. Engine.ShadersRepository = "src/Shaders/";
  10385. BABYLON.Engine = Engine;
  10386. })(BABYLON || (BABYLON = {}));
  10387. //# sourceMappingURL=babylon.engine.js.map
  10388. /// <reference path="Tools\babylon.decorators.ts" />
  10389. var BABYLON;
  10390. (function (BABYLON) {
  10391. /**
  10392. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10393. */
  10394. var Node = (function () {
  10395. /**
  10396. * @constructor
  10397. * @param {string} name - the name and id to be given to this node
  10398. * @param {BABYLON.Scene} the scene this node will be added to
  10399. */
  10400. function Node(name, scene) {
  10401. this.state = "";
  10402. this.metadata = null;
  10403. this.doNotSerialize = false;
  10404. this.animations = new Array();
  10405. this._ranges = {};
  10406. this._childrenFlag = -1;
  10407. this._isEnabled = true;
  10408. this._isReady = true;
  10409. this._currentRenderId = -1;
  10410. this._parentRenderId = -1;
  10411. /**
  10412. * An event triggered when the mesh is disposed.
  10413. * @type {BABYLON.Observable}
  10414. */
  10415. this.onDisposeObservable = new BABYLON.Observable();
  10416. this.name = name;
  10417. this.id = name;
  10418. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10419. this._initCache();
  10420. }
  10421. Object.defineProperty(Node.prototype, "parent", {
  10422. get: function () {
  10423. return this._parentNode;
  10424. },
  10425. set: function (parent) {
  10426. if (this._parentNode === parent) {
  10427. return;
  10428. }
  10429. if (this._parentNode) {
  10430. var index = this._parentNode._children.indexOf(this);
  10431. if (index !== -1) {
  10432. this._parentNode._children.splice(index, 1);
  10433. }
  10434. }
  10435. this._parentNode = parent;
  10436. if (this._parentNode) {
  10437. if (!this._parentNode._children) {
  10438. this._parentNode._children = new Array();
  10439. }
  10440. this._parentNode._children.push(this);
  10441. }
  10442. },
  10443. enumerable: true,
  10444. configurable: true
  10445. });
  10446. Node.prototype.getClassName = function () {
  10447. return "Node";
  10448. };
  10449. Object.defineProperty(Node.prototype, "onDispose", {
  10450. set: function (callback) {
  10451. if (this._onDisposeObserver) {
  10452. this.onDisposeObservable.remove(this._onDisposeObserver);
  10453. }
  10454. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10455. },
  10456. enumerable: true,
  10457. configurable: true
  10458. });
  10459. Node.prototype.getScene = function () {
  10460. return this._scene;
  10461. };
  10462. Node.prototype.getEngine = function () {
  10463. return this._scene.getEngine();
  10464. };
  10465. // override it in derived class
  10466. Node.prototype.getWorldMatrix = function () {
  10467. return BABYLON.Matrix.Identity();
  10468. };
  10469. // override it in derived class if you add new variables to the cache
  10470. // and call the parent class method
  10471. Node.prototype._initCache = function () {
  10472. this._cache = {};
  10473. this._cache.parent = undefined;
  10474. };
  10475. Node.prototype.updateCache = function (force) {
  10476. if (!force && this.isSynchronized())
  10477. return;
  10478. this._cache.parent = this.parent;
  10479. this._updateCache();
  10480. };
  10481. // override it in derived class if you add new variables to the cache
  10482. // and call the parent class method if !ignoreParentClass
  10483. Node.prototype._updateCache = function (ignoreParentClass) {
  10484. };
  10485. // override it in derived class if you add new variables to the cache
  10486. Node.prototype._isSynchronized = function () {
  10487. return true;
  10488. };
  10489. Node.prototype._markSyncedWithParent = function () {
  10490. this._parentRenderId = this.parent._currentRenderId;
  10491. };
  10492. Node.prototype.isSynchronizedWithParent = function () {
  10493. if (!this.parent) {
  10494. return true;
  10495. }
  10496. if (this._parentRenderId !== this.parent._currentRenderId) {
  10497. return false;
  10498. }
  10499. return this.parent.isSynchronized();
  10500. };
  10501. Node.prototype.isSynchronized = function (updateCache) {
  10502. var check = this.hasNewParent();
  10503. check = check || !this.isSynchronizedWithParent();
  10504. check = check || !this._isSynchronized();
  10505. if (updateCache)
  10506. this.updateCache(true);
  10507. return !check;
  10508. };
  10509. Node.prototype.hasNewParent = function (update) {
  10510. if (this._cache.parent === this.parent)
  10511. return false;
  10512. if (update)
  10513. this._cache.parent = this.parent;
  10514. return true;
  10515. };
  10516. /**
  10517. * Is this node ready to be used/rendered
  10518. * @return {boolean} is it ready
  10519. */
  10520. Node.prototype.isReady = function () {
  10521. return this._isReady;
  10522. };
  10523. /**
  10524. * Is this node enabled.
  10525. * If the node has a parent and is enabled, the parent will be inspected as well.
  10526. * @return {boolean} whether this node (and its parent) is enabled.
  10527. * @see setEnabled
  10528. */
  10529. Node.prototype.isEnabled = function () {
  10530. if (!this._isEnabled) {
  10531. return false;
  10532. }
  10533. if (this.parent) {
  10534. return this.parent.isEnabled();
  10535. }
  10536. return true;
  10537. };
  10538. /**
  10539. * Set the enabled state of this node.
  10540. * @param {boolean} value - the new enabled state
  10541. * @see isEnabled
  10542. */
  10543. Node.prototype.setEnabled = function (value) {
  10544. this._isEnabled = value;
  10545. };
  10546. /**
  10547. * Is this node a descendant of the given node.
  10548. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10549. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10550. * @see parent
  10551. */
  10552. Node.prototype.isDescendantOf = function (ancestor) {
  10553. if (this.parent) {
  10554. if (this.parent === ancestor) {
  10555. return true;
  10556. }
  10557. return this.parent.isDescendantOf(ancestor);
  10558. }
  10559. return false;
  10560. };
  10561. /**
  10562. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10563. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10564. * @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.
  10565. * @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.
  10566. */
  10567. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10568. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10569. if (!this._children) {
  10570. return;
  10571. }
  10572. for (var index = 0; index < this._children.length; index++) {
  10573. var item = this._children[index];
  10574. if (!predicate || predicate(item)) {
  10575. results.push(item);
  10576. }
  10577. if (!directDescendantsOnly) {
  10578. item._getDescendants(results, false, predicate);
  10579. }
  10580. }
  10581. };
  10582. /**
  10583. * Will return all nodes that have this node as ascendant.
  10584. * @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.
  10585. * @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.
  10586. * @return {BABYLON.Node[]} all children nodes of all types.
  10587. */
  10588. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10589. var results = [];
  10590. this._getDescendants(results, directDescendantsOnly, predicate);
  10591. return results;
  10592. };
  10593. /**
  10594. * Get all child-meshes of this node.
  10595. */
  10596. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10597. var results = [];
  10598. this._getDescendants(results, directDecendantsOnly, function (node) {
  10599. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10600. });
  10601. return results;
  10602. };
  10603. /**
  10604. * Get all direct children of this node.
  10605. */
  10606. Node.prototype.getChildren = function (predicate) {
  10607. return this.getDescendants(true, predicate);
  10608. };
  10609. Node.prototype._setReady = function (state) {
  10610. if (state === this._isReady) {
  10611. return;
  10612. }
  10613. if (!state) {
  10614. this._isReady = false;
  10615. return;
  10616. }
  10617. this._isReady = true;
  10618. if (this.onReady) {
  10619. this.onReady(this);
  10620. }
  10621. };
  10622. Node.prototype.getAnimationByName = function (name) {
  10623. for (var i = 0; i < this.animations.length; i++) {
  10624. var animation = this.animations[i];
  10625. if (animation.name === name) {
  10626. return animation;
  10627. }
  10628. }
  10629. return null;
  10630. };
  10631. Node.prototype.createAnimationRange = function (name, from, to) {
  10632. // check name not already in use
  10633. if (!this._ranges[name]) {
  10634. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10635. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10636. if (this.animations[i]) {
  10637. this.animations[i].createRange(name, from, to);
  10638. }
  10639. }
  10640. }
  10641. };
  10642. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10643. if (deleteFrames === void 0) { deleteFrames = true; }
  10644. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10645. if (this.animations[i]) {
  10646. this.animations[i].deleteRange(name, deleteFrames);
  10647. }
  10648. }
  10649. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10650. };
  10651. Node.prototype.getAnimationRange = function (name) {
  10652. return this._ranges[name];
  10653. };
  10654. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10655. var range = this.getAnimationRange(name);
  10656. if (!range) {
  10657. return null;
  10658. }
  10659. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10660. };
  10661. Node.prototype.serializeAnimationRanges = function () {
  10662. var serializationRanges = [];
  10663. for (var name in this._ranges) {
  10664. var range = {};
  10665. range.name = name;
  10666. range.from = this._ranges[name].from;
  10667. range.to = this._ranges[name].to;
  10668. serializationRanges.push(range);
  10669. }
  10670. return serializationRanges;
  10671. };
  10672. Node.prototype.dispose = function () {
  10673. this.parent = null;
  10674. // Callback
  10675. this.onDisposeObservable.notifyObservers(this);
  10676. this.onDisposeObservable.clear();
  10677. };
  10678. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10679. if (parsedNode.ranges) {
  10680. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10681. var data = parsedNode.ranges[index];
  10682. node.createAnimationRange(data.name, data.from, data.to);
  10683. }
  10684. }
  10685. };
  10686. return Node;
  10687. }());
  10688. __decorate([
  10689. BABYLON.serialize()
  10690. ], Node.prototype, "name", void 0);
  10691. __decorate([
  10692. BABYLON.serialize()
  10693. ], Node.prototype, "id", void 0);
  10694. __decorate([
  10695. BABYLON.serialize()
  10696. ], Node.prototype, "uniqueId", void 0);
  10697. __decorate([
  10698. BABYLON.serialize()
  10699. ], Node.prototype, "state", void 0);
  10700. __decorate([
  10701. BABYLON.serialize()
  10702. ], Node.prototype, "metadata", void 0);
  10703. BABYLON.Node = Node;
  10704. })(BABYLON || (BABYLON = {}));
  10705. //# sourceMappingURL=babylon.node.js.map
  10706. var BABYLON;
  10707. (function (BABYLON) {
  10708. var BoundingSphere = (function () {
  10709. function BoundingSphere(minimum, maximum) {
  10710. this.minimum = minimum;
  10711. this.maximum = maximum;
  10712. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10713. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10714. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10715. this.radius = distance * 0.5;
  10716. this.centerWorld = BABYLON.Vector3.Zero();
  10717. this._update(BABYLON.Matrix.Identity());
  10718. }
  10719. // Methods
  10720. BoundingSphere.prototype._update = function (world) {
  10721. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10722. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10723. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10724. };
  10725. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10726. for (var i = 0; i < 6; i++) {
  10727. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10728. return false;
  10729. }
  10730. return true;
  10731. };
  10732. BoundingSphere.prototype.intersectsPoint = function (point) {
  10733. var x = this.centerWorld.x - point.x;
  10734. var y = this.centerWorld.y - point.y;
  10735. var z = this.centerWorld.z - point.z;
  10736. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10737. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10738. return false;
  10739. return true;
  10740. };
  10741. // Statics
  10742. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10743. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10744. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10745. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10746. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10747. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10748. return false;
  10749. return true;
  10750. };
  10751. return BoundingSphere;
  10752. }());
  10753. BABYLON.BoundingSphere = BoundingSphere;
  10754. })(BABYLON || (BABYLON = {}));
  10755. //# sourceMappingURL=babylon.boundingSphere.js.map
  10756. var BABYLON;
  10757. (function (BABYLON) {
  10758. var BoundingBox = (function () {
  10759. function BoundingBox(minimum, maximum) {
  10760. this.minimum = minimum;
  10761. this.maximum = maximum;
  10762. this.vectors = new Array();
  10763. this.vectorsWorld = new Array();
  10764. // Bounding vectors
  10765. this.vectors.push(this.minimum.clone());
  10766. this.vectors.push(this.maximum.clone());
  10767. this.vectors.push(this.minimum.clone());
  10768. this.vectors[2].x = this.maximum.x;
  10769. this.vectors.push(this.minimum.clone());
  10770. this.vectors[3].y = this.maximum.y;
  10771. this.vectors.push(this.minimum.clone());
  10772. this.vectors[4].z = this.maximum.z;
  10773. this.vectors.push(this.maximum.clone());
  10774. this.vectors[5].z = this.minimum.z;
  10775. this.vectors.push(this.maximum.clone());
  10776. this.vectors[6].x = this.minimum.x;
  10777. this.vectors.push(this.maximum.clone());
  10778. this.vectors[7].y = this.minimum.y;
  10779. // OBB
  10780. this.center = this.maximum.add(this.minimum).scale(0.5);
  10781. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10782. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10783. // World
  10784. for (var index = 0; index < this.vectors.length; index++) {
  10785. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10786. }
  10787. this.minimumWorld = BABYLON.Vector3.Zero();
  10788. this.maximumWorld = BABYLON.Vector3.Zero();
  10789. this.centerWorld = BABYLON.Vector3.Zero();
  10790. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10791. this._update(BABYLON.Matrix.Identity());
  10792. }
  10793. // Methods
  10794. BoundingBox.prototype.getWorldMatrix = function () {
  10795. return this._worldMatrix;
  10796. };
  10797. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10798. this._worldMatrix.copyFrom(matrix);
  10799. return this;
  10800. };
  10801. BoundingBox.prototype._update = function (world) {
  10802. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10803. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10804. for (var index = 0; index < this.vectors.length; index++) {
  10805. var v = this.vectorsWorld[index];
  10806. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10807. if (v.x < this.minimumWorld.x)
  10808. this.minimumWorld.x = v.x;
  10809. if (v.y < this.minimumWorld.y)
  10810. this.minimumWorld.y = v.y;
  10811. if (v.z < this.minimumWorld.z)
  10812. this.minimumWorld.z = v.z;
  10813. if (v.x > this.maximumWorld.x)
  10814. this.maximumWorld.x = v.x;
  10815. if (v.y > this.maximumWorld.y)
  10816. this.maximumWorld.y = v.y;
  10817. if (v.z > this.maximumWorld.z)
  10818. this.maximumWorld.z = v.z;
  10819. }
  10820. // Extend
  10821. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10822. this.extendSizeWorld.scaleInPlace(0.5);
  10823. // OBB
  10824. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10825. this.centerWorld.scaleInPlace(0.5);
  10826. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10827. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10828. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10829. this._worldMatrix = world;
  10830. };
  10831. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10832. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10833. };
  10834. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10835. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10836. };
  10837. BoundingBox.prototype.intersectsPoint = function (point) {
  10838. var delta = -BABYLON.Epsilon;
  10839. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10840. return false;
  10841. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10842. return false;
  10843. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10844. return false;
  10845. return true;
  10846. };
  10847. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10848. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10849. };
  10850. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10851. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10852. return false;
  10853. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10854. return false;
  10855. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10856. return false;
  10857. return true;
  10858. };
  10859. // Statics
  10860. BoundingBox.Intersects = function (box0, box1) {
  10861. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10862. return false;
  10863. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10864. return false;
  10865. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10866. return false;
  10867. return true;
  10868. };
  10869. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10870. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10871. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10872. return (num <= (sphereRadius * sphereRadius));
  10873. };
  10874. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10875. for (var p = 0; p < 6; p++) {
  10876. for (var i = 0; i < 8; i++) {
  10877. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10878. return false;
  10879. }
  10880. }
  10881. }
  10882. return true;
  10883. };
  10884. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10885. for (var p = 0; p < 6; p++) {
  10886. var inCount = 8;
  10887. for (var i = 0; i < 8; i++) {
  10888. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10889. --inCount;
  10890. }
  10891. else {
  10892. break;
  10893. }
  10894. }
  10895. if (inCount === 0)
  10896. return false;
  10897. }
  10898. return true;
  10899. };
  10900. return BoundingBox;
  10901. }());
  10902. BABYLON.BoundingBox = BoundingBox;
  10903. })(BABYLON || (BABYLON = {}));
  10904. //# sourceMappingURL=babylon.boundingBox.js.map
  10905. var BABYLON;
  10906. (function (BABYLON) {
  10907. var computeBoxExtents = function (axis, box) {
  10908. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  10909. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  10910. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  10911. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  10912. var r = r0 + r1 + r2;
  10913. return {
  10914. min: p - r,
  10915. max: p + r
  10916. };
  10917. };
  10918. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  10919. var axisOverlap = function (axis, box0, box1) {
  10920. var result0 = computeBoxExtents(axis, box0);
  10921. var result1 = computeBoxExtents(axis, box1);
  10922. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  10923. };
  10924. var BoundingInfo = (function () {
  10925. function BoundingInfo(minimum, maximum) {
  10926. this.minimum = minimum;
  10927. this.maximum = maximum;
  10928. this._isLocked = false;
  10929. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10930. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10931. }
  10932. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10933. get: function () {
  10934. return this._isLocked;
  10935. },
  10936. set: function (value) {
  10937. this._isLocked = value;
  10938. },
  10939. enumerable: true,
  10940. configurable: true
  10941. });
  10942. // Methods
  10943. BoundingInfo.prototype.update = function (world) {
  10944. if (this._isLocked) {
  10945. return;
  10946. }
  10947. this.boundingBox._update(world);
  10948. this.boundingSphere._update(world);
  10949. };
  10950. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10951. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10952. return false;
  10953. return this.boundingBox.isInFrustum(frustumPlanes);
  10954. };
  10955. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10956. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10957. };
  10958. BoundingInfo.prototype._checkCollision = function (collider) {
  10959. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10960. };
  10961. BoundingInfo.prototype.intersectsPoint = function (point) {
  10962. if (!this.boundingSphere.centerWorld) {
  10963. return false;
  10964. }
  10965. if (!this.boundingSphere.intersectsPoint(point)) {
  10966. return false;
  10967. }
  10968. if (!this.boundingBox.intersectsPoint(point)) {
  10969. return false;
  10970. }
  10971. return true;
  10972. };
  10973. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10974. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10975. return false;
  10976. }
  10977. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10978. return false;
  10979. }
  10980. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10981. return false;
  10982. }
  10983. if (!precise) {
  10984. return true;
  10985. }
  10986. var box0 = this.boundingBox;
  10987. var box1 = boundingInfo.boundingBox;
  10988. if (!axisOverlap(box0.directions[0], box0, box1))
  10989. return false;
  10990. if (!axisOverlap(box0.directions[1], box0, box1))
  10991. return false;
  10992. if (!axisOverlap(box0.directions[2], box0, box1))
  10993. return false;
  10994. if (!axisOverlap(box1.directions[0], box0, box1))
  10995. return false;
  10996. if (!axisOverlap(box1.directions[1], box0, box1))
  10997. return false;
  10998. if (!axisOverlap(box1.directions[2], box0, box1))
  10999. return false;
  11000. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11001. return false;
  11002. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11003. return false;
  11004. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11005. return false;
  11006. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11007. return false;
  11008. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11009. return false;
  11010. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11011. return false;
  11012. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11013. return false;
  11014. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11015. return false;
  11016. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11017. return false;
  11018. return true;
  11019. };
  11020. return BoundingInfo;
  11021. }());
  11022. BABYLON.BoundingInfo = BoundingInfo;
  11023. })(BABYLON || (BABYLON = {}));
  11024. //# sourceMappingURL=babylon.boundingInfo.js.map
  11025. var BABYLON;
  11026. (function (BABYLON) {
  11027. var AbstractMesh = (function (_super) {
  11028. __extends(AbstractMesh, _super);
  11029. // Constructor
  11030. function AbstractMesh(name, scene) {
  11031. var _this = _super.call(this, name, scene) || this;
  11032. _this._facetNb = 0; // facet number
  11033. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11034. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11035. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11036. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11037. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11038. _this._subDiv = {
  11039. max: 1,
  11040. X: 1,
  11041. Y: 1,
  11042. Z: 1
  11043. };
  11044. // Events
  11045. /**
  11046. * An event triggered when this mesh collides with another one
  11047. * @type {BABYLON.Observable}
  11048. */
  11049. _this.onCollideObservable = new BABYLON.Observable();
  11050. /**
  11051. * An event triggered when the collision's position changes
  11052. * @type {BABYLON.Observable}
  11053. */
  11054. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11055. /**
  11056. * An event triggered after the world matrix is updated
  11057. * @type {BABYLON.Observable}
  11058. */
  11059. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11060. // Properties
  11061. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11062. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11063. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11064. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  11065. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11066. _this.visibility = 1.0;
  11067. _this.alphaIndex = Number.MAX_VALUE;
  11068. _this.infiniteDistance = false;
  11069. _this.isVisible = true;
  11070. _this.isPickable = true;
  11071. _this.showBoundingBox = false;
  11072. _this.showSubMeshesBoundingBox = false;
  11073. _this.isBlocker = false;
  11074. _this.renderingGroupId = 0;
  11075. _this._receiveShadows = false;
  11076. _this.renderOutline = false;
  11077. _this.outlineColor = BABYLON.Color3.Red();
  11078. _this.outlineWidth = 0.02;
  11079. _this.renderOverlay = false;
  11080. _this.overlayColor = BABYLON.Color3.Red();
  11081. _this.overlayAlpha = 0.5;
  11082. _this._hasVertexAlpha = false;
  11083. _this._useVertexColors = true;
  11084. _this._computeBonesUsingShaders = true;
  11085. _this._numBoneInfluencers = 4;
  11086. _this._applyFog = true;
  11087. _this.scalingDeterminant = 1;
  11088. _this.useOctreeForRenderingSelection = true;
  11089. _this.useOctreeForPicking = true;
  11090. _this.useOctreeForCollisions = true;
  11091. _this.layerMask = 0x0FFFFFFF;
  11092. /**
  11093. * True if the mesh must be rendered in any case.
  11094. */
  11095. _this.alwaysSelectAsActiveMesh = false;
  11096. // Collisions
  11097. _this._checkCollisions = false;
  11098. _this._collisionMask = -1;
  11099. _this._collisionGroup = -1;
  11100. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11101. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11102. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11103. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11104. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11105. // Edges
  11106. _this.edgesWidth = 1;
  11107. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11108. // Cache
  11109. _this._localWorld = BABYLON.Matrix.Zero();
  11110. _this._worldMatrix = BABYLON.Matrix.Zero();
  11111. _this._absolutePosition = BABYLON.Vector3.Zero();
  11112. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11113. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11114. _this._isDirty = false;
  11115. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11116. _this._isDisposed = false;
  11117. _this._renderId = 0;
  11118. _this._intersectionsInProgress = new Array();
  11119. _this._isWorldMatrixFrozen = false;
  11120. _this._unIndexed = false;
  11121. _this._lightSources = new Array();
  11122. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11123. if (collidedMesh === void 0) { collidedMesh = null; }
  11124. //TODO move this to the collision coordinator!
  11125. if (_this.getScene().workerCollisions)
  11126. newPosition.multiplyInPlace(_this._collider.radius);
  11127. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11128. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11129. _this.position.addInPlace(_this._diffPositionForCollisions);
  11130. }
  11131. if (collidedMesh) {
  11132. _this.onCollideObservable.notifyObservers(collidedMesh);
  11133. }
  11134. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11135. };
  11136. _this.getScene().addMesh(_this);
  11137. _this._resyncLightSources();
  11138. return _this;
  11139. }
  11140. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11141. get: function () {
  11142. return AbstractMesh._BILLBOARDMODE_NONE;
  11143. },
  11144. enumerable: true,
  11145. configurable: true
  11146. });
  11147. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11148. get: function () {
  11149. return AbstractMesh._BILLBOARDMODE_X;
  11150. },
  11151. enumerable: true,
  11152. configurable: true
  11153. });
  11154. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11155. get: function () {
  11156. return AbstractMesh._BILLBOARDMODE_Y;
  11157. },
  11158. enumerable: true,
  11159. configurable: true
  11160. });
  11161. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11162. get: function () {
  11163. return AbstractMesh._BILLBOARDMODE_Z;
  11164. },
  11165. enumerable: true,
  11166. configurable: true
  11167. });
  11168. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11169. get: function () {
  11170. return AbstractMesh._BILLBOARDMODE_ALL;
  11171. },
  11172. enumerable: true,
  11173. configurable: true
  11174. });
  11175. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11176. /**
  11177. * Read-only : the number of facets in the mesh
  11178. */
  11179. get: function () {
  11180. return this._facetNb;
  11181. },
  11182. enumerable: true,
  11183. configurable: true
  11184. });
  11185. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11186. /**
  11187. * The number (integer) of subdivisions per axis in the partioning space
  11188. */
  11189. get: function () {
  11190. return this._partitioningSubdivisions;
  11191. },
  11192. set: function (nb) {
  11193. this._partitioningSubdivisions = nb;
  11194. },
  11195. enumerable: true,
  11196. configurable: true
  11197. });
  11198. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11199. /**
  11200. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11201. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11202. */
  11203. get: function () {
  11204. return this._partitioningBBoxRatio;
  11205. },
  11206. set: function (ratio) {
  11207. this._partitioningBBoxRatio = ratio;
  11208. },
  11209. enumerable: true,
  11210. configurable: true
  11211. });
  11212. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11213. /**
  11214. * Read-only boolean : is the feature facetData enabled ?
  11215. */
  11216. get: function () {
  11217. return this._facetDataEnabled;
  11218. },
  11219. enumerable: true,
  11220. configurable: true
  11221. });
  11222. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11223. set: function (callback) {
  11224. if (this._onCollideObserver) {
  11225. this.onCollideObservable.remove(this._onCollideObserver);
  11226. }
  11227. this._onCollideObserver = this.onCollideObservable.add(callback);
  11228. },
  11229. enumerable: true,
  11230. configurable: true
  11231. });
  11232. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11233. set: function (callback) {
  11234. if (this._onCollisionPositionChangeObserver) {
  11235. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11236. }
  11237. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11238. },
  11239. enumerable: true,
  11240. configurable: true
  11241. });
  11242. Object.defineProperty(AbstractMesh.prototype, "material", {
  11243. get: function () {
  11244. return this._material;
  11245. },
  11246. set: function (value) {
  11247. if (this._material === value) {
  11248. return;
  11249. }
  11250. this._material = value;
  11251. if (!this.subMeshes) {
  11252. return;
  11253. }
  11254. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11255. var subMesh = _a[_i];
  11256. subMesh.setEffect(null);
  11257. }
  11258. },
  11259. enumerable: true,
  11260. configurable: true
  11261. });
  11262. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11263. get: function () {
  11264. return this._receiveShadows;
  11265. },
  11266. set: function (value) {
  11267. if (this._receiveShadows === value) {
  11268. return;
  11269. }
  11270. this._receiveShadows = value;
  11271. this._markSubMeshesAsLightDirty();
  11272. },
  11273. enumerable: true,
  11274. configurable: true
  11275. });
  11276. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11277. get: function () {
  11278. return this._hasVertexAlpha;
  11279. },
  11280. set: function (value) {
  11281. if (this._hasVertexAlpha === value) {
  11282. return;
  11283. }
  11284. this._hasVertexAlpha = value;
  11285. this._markSubMeshesAsAttributesDirty();
  11286. },
  11287. enumerable: true,
  11288. configurable: true
  11289. });
  11290. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11291. get: function () {
  11292. return this._useVertexColors;
  11293. },
  11294. set: function (value) {
  11295. if (this._useVertexColors === value) {
  11296. return;
  11297. }
  11298. this._useVertexColors = value;
  11299. this._markSubMeshesAsAttributesDirty();
  11300. },
  11301. enumerable: true,
  11302. configurable: true
  11303. });
  11304. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11305. get: function () {
  11306. return this._computeBonesUsingShaders;
  11307. },
  11308. set: function (value) {
  11309. if (this._computeBonesUsingShaders === value) {
  11310. return;
  11311. }
  11312. this._computeBonesUsingShaders = value;
  11313. this._markSubMeshesAsAttributesDirty();
  11314. },
  11315. enumerable: true,
  11316. configurable: true
  11317. });
  11318. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11319. get: function () {
  11320. return this._numBoneInfluencers;
  11321. },
  11322. set: function (value) {
  11323. if (this._numBoneInfluencers === value) {
  11324. return;
  11325. }
  11326. this._numBoneInfluencers = value;
  11327. this._markSubMeshesAsAttributesDirty();
  11328. },
  11329. enumerable: true,
  11330. configurable: true
  11331. });
  11332. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11333. get: function () {
  11334. return this._applyFog;
  11335. },
  11336. set: function (value) {
  11337. if (this._applyFog === value) {
  11338. return;
  11339. }
  11340. this._applyFog = value;
  11341. this._markSubMeshesAsMiscDirty();
  11342. },
  11343. enumerable: true,
  11344. configurable: true
  11345. });
  11346. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11347. get: function () {
  11348. return this._collisionMask;
  11349. },
  11350. set: function (mask) {
  11351. this._collisionMask = !isNaN(mask) ? mask : -1;
  11352. },
  11353. enumerable: true,
  11354. configurable: true
  11355. });
  11356. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11357. get: function () {
  11358. return this._collisionGroup;
  11359. },
  11360. set: function (mask) {
  11361. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11362. },
  11363. enumerable: true,
  11364. configurable: true
  11365. });
  11366. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11367. get: function () {
  11368. return null;
  11369. },
  11370. enumerable: true,
  11371. configurable: true
  11372. });
  11373. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11374. get: function () {
  11375. return this._skeleton;
  11376. },
  11377. set: function (value) {
  11378. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11379. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11380. }
  11381. if (value && value.needInitialSkinMatrix) {
  11382. value._registerMeshWithPoseMatrix(this);
  11383. }
  11384. this._skeleton = value;
  11385. if (!this._skeleton) {
  11386. this._bonesTransformMatrices = null;
  11387. }
  11388. this._markSubMeshesAsAttributesDirty();
  11389. },
  11390. enumerable: true,
  11391. configurable: true
  11392. });
  11393. /**
  11394. * Returns the string "AbstractMesh"
  11395. */
  11396. AbstractMesh.prototype.getClassName = function () {
  11397. return "AbstractMesh";
  11398. };
  11399. /**
  11400. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11401. */
  11402. AbstractMesh.prototype.toString = function (fullDetails) {
  11403. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11404. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11405. if (this._skeleton) {
  11406. ret += ", skeleton: " + this._skeleton.name;
  11407. }
  11408. if (fullDetails) {
  11409. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11410. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11411. }
  11412. return ret;
  11413. };
  11414. AbstractMesh.prototype._resyncLightSources = function () {
  11415. this._lightSources.length = 0;
  11416. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11417. var light = _a[_i];
  11418. if (!light.isEnabled()) {
  11419. continue;
  11420. }
  11421. if (light.canAffectMesh(this)) {
  11422. this._lightSources.push(light);
  11423. }
  11424. }
  11425. this._markSubMeshesAsLightDirty();
  11426. };
  11427. AbstractMesh.prototype._resyncLighSource = function (light) {
  11428. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11429. var index = this._lightSources.indexOf(light);
  11430. if (index === -1) {
  11431. if (!isIn) {
  11432. return;
  11433. }
  11434. this._lightSources.push(light);
  11435. }
  11436. else {
  11437. if (isIn) {
  11438. return;
  11439. }
  11440. this._lightSources.splice(index, 1);
  11441. }
  11442. this._markSubMeshesAsLightDirty();
  11443. };
  11444. AbstractMesh.prototype._removeLightSource = function (light) {
  11445. var index = this._lightSources.indexOf(light);
  11446. if (index === -1) {
  11447. return;
  11448. }
  11449. this._lightSources.splice(index, 1);
  11450. };
  11451. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11452. if (!this.subMeshes) {
  11453. return;
  11454. }
  11455. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11456. var subMesh = _a[_i];
  11457. if (subMesh._materialDefines) {
  11458. func(subMesh._materialDefines);
  11459. }
  11460. }
  11461. };
  11462. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11463. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11464. };
  11465. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11466. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11467. };
  11468. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11469. if (!this.subMeshes) {
  11470. return;
  11471. }
  11472. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11473. var subMesh = _a[_i];
  11474. var material = subMesh.getMaterial();
  11475. if (material) {
  11476. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11477. }
  11478. }
  11479. };
  11480. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11481. /**
  11482. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11483. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11484. * Default : (0.0, 0.0, 0.0)
  11485. */
  11486. get: function () {
  11487. return this._rotation;
  11488. },
  11489. set: function (newRotation) {
  11490. this._rotation = newRotation;
  11491. },
  11492. enumerable: true,
  11493. configurable: true
  11494. });
  11495. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11496. /**
  11497. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11498. * Default : (1.0, 1.0, 1.0)
  11499. */
  11500. get: function () {
  11501. return this._scaling;
  11502. },
  11503. set: function (newScaling) {
  11504. this._scaling = newScaling;
  11505. if (this.physicsImpostor) {
  11506. this.physicsImpostor.forceUpdate();
  11507. }
  11508. },
  11509. enumerable: true,
  11510. configurable: true
  11511. });
  11512. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11513. /**
  11514. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11515. * It's null by default.
  11516. * 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)
  11517. */
  11518. get: function () {
  11519. return this._rotationQuaternion;
  11520. },
  11521. set: function (quaternion) {
  11522. this._rotationQuaternion = quaternion;
  11523. //reset the rotation vector.
  11524. if (quaternion && this.rotation.length()) {
  11525. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11526. }
  11527. },
  11528. enumerable: true,
  11529. configurable: true
  11530. });
  11531. // Methods
  11532. /**
  11533. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11534. * Returns the AbstractMesh.
  11535. */
  11536. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11537. this._poseMatrix.copyFrom(matrix);
  11538. return this;
  11539. };
  11540. /**
  11541. * Returns the mesh Pose matrix.
  11542. * Returned object : Matrix
  11543. */
  11544. AbstractMesh.prototype.getPoseMatrix = function () {
  11545. return this._poseMatrix;
  11546. };
  11547. /**
  11548. * Disables the mesh edger rendering mode.
  11549. * Returns the AbstractMesh.
  11550. */
  11551. AbstractMesh.prototype.disableEdgesRendering = function () {
  11552. if (this._edgesRenderer !== undefined) {
  11553. this._edgesRenderer.dispose();
  11554. this._edgesRenderer = undefined;
  11555. }
  11556. return this;
  11557. };
  11558. /**
  11559. * Enables the edge rendering mode on the mesh.
  11560. * This mode makes the mesh edges visible.
  11561. * Returns the AbstractMesh.
  11562. */
  11563. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11564. if (epsilon === void 0) { epsilon = 0.95; }
  11565. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11566. this.disableEdgesRendering();
  11567. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11568. return this;
  11569. };
  11570. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11571. /**
  11572. * Returns true if the mesh is blocked. Used by the class Mesh.
  11573. * Returns the boolean `false` by default.
  11574. */
  11575. get: function () {
  11576. return false;
  11577. },
  11578. enumerable: true,
  11579. configurable: true
  11580. });
  11581. /**
  11582. * Returns the mesh itself by default, used by the class Mesh.
  11583. * Returned type : AbstractMesh
  11584. */
  11585. AbstractMesh.prototype.getLOD = function (camera) {
  11586. return this;
  11587. };
  11588. /**
  11589. * Returns 0 by default, used by the class Mesh.
  11590. * Returns an integer.
  11591. */
  11592. AbstractMesh.prototype.getTotalVertices = function () {
  11593. return 0;
  11594. };
  11595. /**
  11596. * Returns null by default, used by the class Mesh.
  11597. * Returned type : integer array
  11598. */
  11599. AbstractMesh.prototype.getIndices = function () {
  11600. return null;
  11601. };
  11602. /**
  11603. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11604. * Returned type : float array or Float32Array
  11605. */
  11606. AbstractMesh.prototype.getVerticesData = function (kind) {
  11607. return null;
  11608. };
  11609. /**
  11610. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11611. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11612. * The `data` are either a numeric array either a Float32Array.
  11613. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11614. * 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).
  11615. * Note that a new underlying VertexBuffer object is created each call.
  11616. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11617. *
  11618. * Possible `kind` values :
  11619. * - BABYLON.VertexBuffer.PositionKind
  11620. * - BABYLON.VertexBuffer.UVKind
  11621. * - BABYLON.VertexBuffer.UV2Kind
  11622. * - BABYLON.VertexBuffer.UV3Kind
  11623. * - BABYLON.VertexBuffer.UV4Kind
  11624. * - BABYLON.VertexBuffer.UV5Kind
  11625. * - BABYLON.VertexBuffer.UV6Kind
  11626. * - BABYLON.VertexBuffer.ColorKind
  11627. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11628. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11629. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11630. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11631. *
  11632. * Returns the Mesh.
  11633. */
  11634. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11635. return null;
  11636. };
  11637. /**
  11638. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11639. * If the mesh has no geometry, it is simply returned as it is.
  11640. * The `data` are either a numeric array either a Float32Array.
  11641. * No new underlying VertexBuffer object is created.
  11642. * 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.
  11643. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11644. *
  11645. * Possible `kind` values :
  11646. * - BABYLON.VertexBuffer.PositionKind
  11647. * - BABYLON.VertexBuffer.UVKind
  11648. * - BABYLON.VertexBuffer.UV2Kind
  11649. * - BABYLON.VertexBuffer.UV3Kind
  11650. * - BABYLON.VertexBuffer.UV4Kind
  11651. * - BABYLON.VertexBuffer.UV5Kind
  11652. * - BABYLON.VertexBuffer.UV6Kind
  11653. * - BABYLON.VertexBuffer.ColorKind
  11654. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11655. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11656. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11657. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11658. *
  11659. * Returns the Mesh.
  11660. */
  11661. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11662. return null;
  11663. };
  11664. /**
  11665. * Sets the mesh indices.
  11666. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11667. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11668. * This method creates a new index buffer each call.
  11669. * Returns the Mesh.
  11670. */
  11671. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11672. return null;
  11673. };
  11674. /** Returns false by default, used by the class Mesh.
  11675. * Returns a boolean
  11676. */
  11677. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11678. return false;
  11679. };
  11680. /**
  11681. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11682. * Returns a BoundingInfo
  11683. */
  11684. AbstractMesh.prototype.getBoundingInfo = function () {
  11685. if (this._masterMesh) {
  11686. return this._masterMesh.getBoundingInfo();
  11687. }
  11688. if (!this._boundingInfo) {
  11689. this._updateBoundingInfo();
  11690. }
  11691. return this._boundingInfo;
  11692. };
  11693. /**
  11694. * Sets a mesh new object BoundingInfo.
  11695. * Returns the AbstractMesh.
  11696. */
  11697. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11698. this._boundingInfo = boundingInfo;
  11699. return this;
  11700. };
  11701. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11702. get: function () {
  11703. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. AbstractMesh.prototype._preActivate = function () {
  11709. };
  11710. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11711. };
  11712. AbstractMesh.prototype._activate = function (renderId) {
  11713. this._renderId = renderId;
  11714. };
  11715. /**
  11716. * Returns the last update of the World matrix
  11717. * Returns a Matrix.
  11718. */
  11719. AbstractMesh.prototype.getWorldMatrix = function () {
  11720. if (this._masterMesh) {
  11721. return this._masterMesh.getWorldMatrix();
  11722. }
  11723. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11724. this.computeWorldMatrix();
  11725. }
  11726. return this._worldMatrix;
  11727. };
  11728. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11729. /**
  11730. * Returns directly the last state of the mesh World matrix.
  11731. * A Matrix is returned.
  11732. */
  11733. get: function () {
  11734. return this._worldMatrix;
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11740. /**
  11741. * Returns the current mesh absolute position.
  11742. * Retuns a Vector3.
  11743. */
  11744. get: function () {
  11745. return this._absolutePosition;
  11746. },
  11747. enumerable: true,
  11748. configurable: true
  11749. });
  11750. /**
  11751. * Prevents the World matrix to be computed any longer.
  11752. * Returns the AbstractMesh.
  11753. */
  11754. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11755. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11756. this.computeWorldMatrix(true);
  11757. this._isWorldMatrixFrozen = true;
  11758. return this;
  11759. };
  11760. /**
  11761. * Allows back the World matrix computation.
  11762. * Returns the AbstractMesh.
  11763. */
  11764. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11765. this._isWorldMatrixFrozen = false;
  11766. this.computeWorldMatrix(true);
  11767. return this;
  11768. };
  11769. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11770. /**
  11771. * True if the World matrix has been frozen.
  11772. * Returns a boolean.
  11773. */
  11774. get: function () {
  11775. return this._isWorldMatrixFrozen;
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. /**
  11781. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11782. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11783. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11784. * The passed axis is also normalized.
  11785. * Returns the AbstractMesh.
  11786. */
  11787. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11788. axis.normalize();
  11789. if (!this.rotationQuaternion) {
  11790. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11791. this.rotation = BABYLON.Vector3.Zero();
  11792. }
  11793. var rotationQuaternion;
  11794. if (!space || space === BABYLON.Space.LOCAL) {
  11795. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11796. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11797. }
  11798. else {
  11799. if (this.parent) {
  11800. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11801. invertParentWorldMatrix.invert();
  11802. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11803. }
  11804. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11805. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11806. }
  11807. return this;
  11808. };
  11809. /**
  11810. * Translates the mesh along the axis vector for the passed distance in the given space.
  11811. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11812. * Returns the AbstractMesh.
  11813. */
  11814. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11815. var displacementVector = axis.scale(distance);
  11816. if (!space || space === BABYLON.Space.LOCAL) {
  11817. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11818. this.setPositionWithLocalVector(tempV3);
  11819. }
  11820. else {
  11821. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11822. }
  11823. return this;
  11824. };
  11825. /**
  11826. * Adds a rotation step to the mesh current rotation.
  11827. * x, y, z are Euler angles expressed in radians.
  11828. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11829. * This means this rotation is made in the mesh local space only.
  11830. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11831. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11832. * ```javascript
  11833. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11834. * ```
  11835. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11836. * 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.
  11837. * Returns the AbstractMesh.
  11838. */
  11839. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11840. var rotationQuaternion;
  11841. if (this.rotationQuaternion) {
  11842. rotationQuaternion = this.rotationQuaternion;
  11843. }
  11844. else {
  11845. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11846. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11847. }
  11848. var accumulation = BABYLON.Tmp.Quaternion[0];
  11849. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11850. rotationQuaternion.multiplyInPlace(accumulation);
  11851. if (!this.rotationQuaternion) {
  11852. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11853. }
  11854. return this;
  11855. };
  11856. /**
  11857. * Retuns the mesh absolute position in the World.
  11858. * Returns a Vector3.
  11859. */
  11860. AbstractMesh.prototype.getAbsolutePosition = function () {
  11861. this.computeWorldMatrix();
  11862. return this._absolutePosition;
  11863. };
  11864. /**
  11865. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11866. * Returns the AbstractMesh.
  11867. */
  11868. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11869. if (!absolutePosition) {
  11870. return;
  11871. }
  11872. var absolutePositionX;
  11873. var absolutePositionY;
  11874. var absolutePositionZ;
  11875. if (absolutePosition.x === undefined) {
  11876. if (arguments.length < 3) {
  11877. return;
  11878. }
  11879. absolutePositionX = arguments[0];
  11880. absolutePositionY = arguments[1];
  11881. absolutePositionZ = arguments[2];
  11882. }
  11883. else {
  11884. absolutePositionX = absolutePosition.x;
  11885. absolutePositionY = absolutePosition.y;
  11886. absolutePositionZ = absolutePosition.z;
  11887. }
  11888. if (this.parent) {
  11889. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11890. invertParentWorldMatrix.invert();
  11891. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11892. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11893. }
  11894. else {
  11895. this.position.x = absolutePositionX;
  11896. this.position.y = absolutePositionY;
  11897. this.position.z = absolutePositionZ;
  11898. }
  11899. return this;
  11900. };
  11901. // ================================== Point of View Movement =================================
  11902. /**
  11903. * Perform relative position change from the point of view of behind the front of the mesh.
  11904. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11905. * Supports definition of mesh facing forward or backward.
  11906. * @param {number} amountRight
  11907. * @param {number} amountUp
  11908. * @param {number} amountForward
  11909. *
  11910. * Returns the AbstractMesh.
  11911. */
  11912. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  11913. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  11914. return this;
  11915. };
  11916. /**
  11917. * Calculate relative position change from the point of view of behind the front of the mesh.
  11918. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11919. * Supports definition of mesh facing forward or backward.
  11920. * @param {number} amountRight
  11921. * @param {number} amountUp
  11922. * @param {number} amountForward
  11923. *
  11924. * Returns a new Vector3.
  11925. */
  11926. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  11927. var rotMatrix = new BABYLON.Matrix();
  11928. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11929. rotQuaternion.toRotationMatrix(rotMatrix);
  11930. var translationDelta = BABYLON.Vector3.Zero();
  11931. var defForwardMult = this.definedFacingForward ? -1 : 1;
  11932. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  11933. return translationDelta;
  11934. };
  11935. // ================================== Point of View Rotation =================================
  11936. /**
  11937. * Perform relative rotation change from the point of view of behind the front of the mesh.
  11938. * Supports definition of mesh facing forward or backward.
  11939. * @param {number} flipBack
  11940. * @param {number} twirlClockwise
  11941. * @param {number} tiltRight
  11942. *
  11943. * Returns the AbstractMesh.
  11944. */
  11945. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11946. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  11947. return this;
  11948. };
  11949. /**
  11950. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  11951. * Supports definition of mesh facing forward or backward.
  11952. * @param {number} flipBack
  11953. * @param {number} twirlClockwise
  11954. * @param {number} tiltRight
  11955. *
  11956. * Returns a new Vector3.
  11957. */
  11958. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11959. var defForwardMult = this.definedFacingForward ? 1 : -1;
  11960. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  11961. };
  11962. /**
  11963. * Sets a new pivot matrix to the mesh.
  11964. * Returns the AbstractMesh.
  11965. */
  11966. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  11967. this._pivotMatrix = matrix;
  11968. this._cache.pivotMatrixUpdated = true;
  11969. return this;
  11970. };
  11971. /**
  11972. * Returns the mesh pivot matrix.
  11973. * Default : Identity.
  11974. * A Matrix is returned.
  11975. */
  11976. AbstractMesh.prototype.getPivotMatrix = function () {
  11977. return this._pivotMatrix;
  11978. };
  11979. AbstractMesh.prototype._isSynchronized = function () {
  11980. if (this._isDirty) {
  11981. return false;
  11982. }
  11983. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  11984. return false;
  11985. if (this._cache.pivotMatrixUpdated) {
  11986. return false;
  11987. }
  11988. if (this.infiniteDistance) {
  11989. return false;
  11990. }
  11991. if (!this._cache.position.equals(this.position))
  11992. return false;
  11993. if (this.rotationQuaternion) {
  11994. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  11995. return false;
  11996. }
  11997. if (!this._cache.rotation.equals(this.rotation))
  11998. return false;
  11999. if (!this._cache.scaling.equals(this.scaling))
  12000. return false;
  12001. return true;
  12002. };
  12003. AbstractMesh.prototype._initCache = function () {
  12004. _super.prototype._initCache.call(this);
  12005. this._cache.localMatrixUpdated = false;
  12006. this._cache.position = BABYLON.Vector3.Zero();
  12007. this._cache.scaling = BABYLON.Vector3.Zero();
  12008. this._cache.rotation = BABYLON.Vector3.Zero();
  12009. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12010. this._cache.billboardMode = -1;
  12011. };
  12012. AbstractMesh.prototype.markAsDirty = function (property) {
  12013. if (property === "rotation") {
  12014. this.rotationQuaternion = null;
  12015. }
  12016. this._currentRenderId = Number.MAX_VALUE;
  12017. this._isDirty = true;
  12018. return this;
  12019. };
  12020. /**
  12021. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12022. * Returns the AbstractMesh.
  12023. */
  12024. AbstractMesh.prototype._updateBoundingInfo = function () {
  12025. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12026. this._boundingInfo.update(this.worldMatrixFromCache);
  12027. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12028. return this;
  12029. };
  12030. /**
  12031. * Update a mesh's children BoundingInfo objects only.
  12032. * Returns the AbstractMesh.
  12033. */
  12034. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12035. if (!this.subMeshes) {
  12036. return;
  12037. }
  12038. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12039. var subMesh = this.subMeshes[subIndex];
  12040. if (!subMesh.IsGlobal) {
  12041. subMesh.updateBoundingInfo(matrix);
  12042. }
  12043. }
  12044. return this;
  12045. };
  12046. /**
  12047. * Computes the mesh World matrix and returns it.
  12048. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12049. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12050. * If the parameter `force`is set to `true`, the actual computation is done.
  12051. * Returns the mesh World Matrix.
  12052. */
  12053. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12054. if (this._isWorldMatrixFrozen) {
  12055. return this._worldMatrix;
  12056. }
  12057. if (!force && this.isSynchronized(true)) {
  12058. this._currentRenderId = this.getScene().getRenderId();
  12059. return this._worldMatrix;
  12060. }
  12061. this._cache.position.copyFrom(this.position);
  12062. this._cache.scaling.copyFrom(this.scaling);
  12063. this._cache.pivotMatrixUpdated = false;
  12064. this._cache.billboardMode = this.billboardMode;
  12065. this._currentRenderId = this.getScene().getRenderId();
  12066. this._isDirty = false;
  12067. // Scaling
  12068. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12069. // Rotation
  12070. //rotate, if quaternion is set and rotation was used
  12071. if (this.rotationQuaternion) {
  12072. var len = this.rotation.length();
  12073. if (len) {
  12074. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12075. this.rotation.copyFromFloats(0, 0, 0);
  12076. }
  12077. }
  12078. if (this.rotationQuaternion) {
  12079. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12080. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12081. }
  12082. else {
  12083. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12084. this._cache.rotation.copyFrom(this.rotation);
  12085. }
  12086. // Translation
  12087. if (this.infiniteDistance && !this.parent) {
  12088. var camera = this.getScene().activeCamera;
  12089. if (camera) {
  12090. var cameraWorldMatrix = camera.getWorldMatrix();
  12091. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12092. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12093. }
  12094. }
  12095. else {
  12096. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12097. }
  12098. // Composing transformations
  12099. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12100. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12101. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12102. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12103. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12104. // Need to decompose each rotation here
  12105. var currentPosition = BABYLON.Tmp.Vector3[3];
  12106. if (this.parent && this.parent.getWorldMatrix) {
  12107. if (this._meshToBoneReferal) {
  12108. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12109. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12110. }
  12111. else {
  12112. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12113. }
  12114. }
  12115. else {
  12116. currentPosition.copyFrom(this.position);
  12117. }
  12118. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12119. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12120. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12121. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12122. }
  12123. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12124. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12125. }
  12126. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12127. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12128. }
  12129. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12130. }
  12131. else {
  12132. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12133. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12134. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12135. }
  12136. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12137. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12138. }
  12139. // Local world
  12140. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12141. // Parent
  12142. if (this.parent && this.parent.getWorldMatrix) {
  12143. this._markSyncedWithParent();
  12144. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12145. if (this._meshToBoneReferal) {
  12146. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12147. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12148. }
  12149. else {
  12150. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12151. }
  12152. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12153. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12154. this._worldMatrix.copyFrom(this._localWorld);
  12155. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12156. }
  12157. else {
  12158. if (this._meshToBoneReferal) {
  12159. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12160. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12161. }
  12162. else {
  12163. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12164. }
  12165. }
  12166. }
  12167. else {
  12168. this._worldMatrix.copyFrom(this._localWorld);
  12169. }
  12170. // Bounding info
  12171. this._updateBoundingInfo();
  12172. // Absolute position
  12173. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12174. // Callbacks
  12175. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12176. if (!this._poseMatrix) {
  12177. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12178. }
  12179. return this._worldMatrix;
  12180. };
  12181. /**
  12182. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12183. * @param func: callback function to add
  12184. *
  12185. * Returns the AbstractMesh.
  12186. */
  12187. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12188. this.onAfterWorldMatrixUpdateObservable.add(func);
  12189. return this;
  12190. };
  12191. /**
  12192. * Removes a registered callback function.
  12193. * Returns the AbstractMesh.
  12194. */
  12195. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12196. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12197. return this;
  12198. };
  12199. /**
  12200. * Sets the mesh position in its local space.
  12201. * Returns the AbstractMesh.
  12202. */
  12203. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12204. this.computeWorldMatrix();
  12205. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12206. return this;
  12207. };
  12208. /**
  12209. * Returns the mesh position in the local space from the current World matrix values.
  12210. * Returns a new Vector3.
  12211. */
  12212. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12213. this.computeWorldMatrix();
  12214. var invLocalWorldMatrix = this._localWorld.clone();
  12215. invLocalWorldMatrix.invert();
  12216. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12217. };
  12218. /**
  12219. * Translates the mesh along the passed Vector3 in its local space.
  12220. * Returns the AbstractMesh.
  12221. */
  12222. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12223. this.computeWorldMatrix(true);
  12224. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12225. return this;
  12226. };
  12227. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12228. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12229. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12230. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12231. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12232. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12233. /// <returns>Mesh oriented towards targetMesh</returns>
  12234. if (yawCor === void 0) { yawCor = 0; }
  12235. if (pitchCor === void 0) { pitchCor = 0; }
  12236. if (rollCor === void 0) { rollCor = 0; }
  12237. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12238. var dv = AbstractMesh._lookAtVectorCache;
  12239. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12240. targetPoint.subtractToRef(pos, dv);
  12241. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12242. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12243. var pitch = Math.atan2(dv.y, len);
  12244. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12245. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12246. return this;
  12247. };
  12248. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12249. this._meshToBoneReferal = affectedMesh;
  12250. this.parent = bone;
  12251. if (bone.getWorldMatrix().determinant() < 0) {
  12252. this.scalingDeterminant *= -1;
  12253. }
  12254. return this;
  12255. };
  12256. AbstractMesh.prototype.detachFromBone = function () {
  12257. if (this.parent.getWorldMatrix().determinant() < 0) {
  12258. this.scalingDeterminant *= -1;
  12259. }
  12260. this._meshToBoneReferal = null;
  12261. this.parent = null;
  12262. return this;
  12263. };
  12264. /**
  12265. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12266. * A mesh is in the frustum if its bounding box intersects the frustum.
  12267. * Boolean returned.
  12268. */
  12269. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12270. return this._boundingInfo.isInFrustum(frustumPlanes);
  12271. };
  12272. /**
  12273. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12274. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12275. * Boolean returned.
  12276. */
  12277. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12278. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12279. ;
  12280. };
  12281. /**
  12282. * True if the mesh intersects another mesh or a SolidParticle object.
  12283. * 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)
  12284. * Returns a boolean.
  12285. */
  12286. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12287. if (!this._boundingInfo || !mesh._boundingInfo) {
  12288. return false;
  12289. }
  12290. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12291. };
  12292. /**
  12293. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12294. * Returns a boolean.
  12295. */
  12296. AbstractMesh.prototype.intersectsPoint = function (point) {
  12297. if (!this._boundingInfo) {
  12298. return false;
  12299. }
  12300. return this._boundingInfo.intersectsPoint(point);
  12301. };
  12302. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12303. return this.physicsImpostor;
  12304. };
  12305. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12306. if (!camera) {
  12307. camera = this.getScene().activeCamera;
  12308. }
  12309. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12310. };
  12311. /**
  12312. * Returns the distance from the mesh to the active camera.
  12313. * Returns a float.
  12314. */
  12315. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12316. if (!camera) {
  12317. camera = this.getScene().activeCamera;
  12318. }
  12319. return this.absolutePosition.subtract(camera.position).length();
  12320. };
  12321. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12322. if (!this.physicsImpostor) {
  12323. return;
  12324. }
  12325. this.physicsImpostor.applyImpulse(force, contactPoint);
  12326. return this;
  12327. };
  12328. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12329. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12330. return;
  12331. }
  12332. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12333. mainPivot: pivot1,
  12334. connectedPivot: pivot2,
  12335. nativeParams: options
  12336. });
  12337. return this;
  12338. };
  12339. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12340. // Collisions
  12341. /**
  12342. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12343. * Default `false`.
  12344. */
  12345. get: function () {
  12346. return this._checkCollisions;
  12347. },
  12348. set: function (collisionEnabled) {
  12349. this._checkCollisions = collisionEnabled;
  12350. if (this.getScene().workerCollisions) {
  12351. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12352. }
  12353. },
  12354. enumerable: true,
  12355. configurable: true
  12356. });
  12357. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12358. var globalPosition = this.getAbsolutePosition();
  12359. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12360. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12361. if (!this._collider) {
  12362. this._collider = new BABYLON.Collider();
  12363. }
  12364. this._collider.radius = this.ellipsoid;
  12365. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12366. return this;
  12367. };
  12368. // Submeshes octree
  12369. /**
  12370. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12371. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12372. * Returns an Octree of submeshes.
  12373. */
  12374. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12375. if (maxCapacity === void 0) { maxCapacity = 64; }
  12376. if (maxDepth === void 0) { maxDepth = 2; }
  12377. if (!this._submeshesOctree) {
  12378. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12379. }
  12380. this.computeWorldMatrix(true);
  12381. // Update octree
  12382. var bbox = this.getBoundingInfo().boundingBox;
  12383. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12384. return this._submeshesOctree;
  12385. };
  12386. // Collisions
  12387. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12388. this._generatePointsArray();
  12389. // Transformation
  12390. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12391. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12392. subMesh._lastColliderWorldVertices = [];
  12393. subMesh._trianglePlanes = [];
  12394. var start = subMesh.verticesStart;
  12395. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12396. for (var i = start; i < end; i++) {
  12397. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12398. }
  12399. }
  12400. // Collide
  12401. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12402. if (collider.collisionFound) {
  12403. collider.collidedMesh = this;
  12404. }
  12405. return this;
  12406. };
  12407. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12408. var subMeshes;
  12409. var len;
  12410. // Octrees
  12411. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12412. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12413. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12414. len = intersections.length;
  12415. subMeshes = intersections.data;
  12416. }
  12417. else {
  12418. subMeshes = this.subMeshes;
  12419. len = subMeshes.length;
  12420. }
  12421. for (var index = 0; index < len; index++) {
  12422. var subMesh = subMeshes[index];
  12423. // Bounding test
  12424. if (len > 1 && !subMesh._checkCollision(collider))
  12425. continue;
  12426. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12427. }
  12428. return this;
  12429. };
  12430. AbstractMesh.prototype._checkCollision = function (collider) {
  12431. // Bounding box test
  12432. if (!this._boundingInfo._checkCollision(collider))
  12433. return this;
  12434. // Transformation matrix
  12435. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12436. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12437. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12438. return this;
  12439. };
  12440. // Picking
  12441. AbstractMesh.prototype._generatePointsArray = function () {
  12442. return false;
  12443. };
  12444. /**
  12445. * Checks if the passed Ray intersects with the mesh.
  12446. * Returns an object PickingInfo.
  12447. */
  12448. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12449. var pickingInfo = new BABYLON.PickingInfo();
  12450. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12451. return pickingInfo;
  12452. }
  12453. if (!this._generatePointsArray()) {
  12454. return pickingInfo;
  12455. }
  12456. var intersectInfo = null;
  12457. // Octrees
  12458. var subMeshes;
  12459. var len;
  12460. if (this._submeshesOctree && this.useOctreeForPicking) {
  12461. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12462. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12463. len = intersections.length;
  12464. subMeshes = intersections.data;
  12465. }
  12466. else {
  12467. subMeshes = this.subMeshes;
  12468. len = subMeshes.length;
  12469. }
  12470. for (var index = 0; index < len; index++) {
  12471. var subMesh = subMeshes[index];
  12472. // Bounding test
  12473. if (len > 1 && !subMesh.canIntersects(ray))
  12474. continue;
  12475. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12476. if (currentIntersectInfo) {
  12477. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12478. intersectInfo = currentIntersectInfo;
  12479. intersectInfo.subMeshId = index;
  12480. if (fastCheck) {
  12481. break;
  12482. }
  12483. }
  12484. }
  12485. }
  12486. if (intersectInfo) {
  12487. // Get picked point
  12488. var world = this.getWorldMatrix();
  12489. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12490. var direction = ray.direction.clone();
  12491. direction = direction.scale(intersectInfo.distance);
  12492. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12493. var pickedPoint = worldOrigin.add(worldDirection);
  12494. // Return result
  12495. pickingInfo.hit = true;
  12496. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12497. pickingInfo.pickedPoint = pickedPoint;
  12498. pickingInfo.pickedMesh = this;
  12499. pickingInfo.bu = intersectInfo.bu;
  12500. pickingInfo.bv = intersectInfo.bv;
  12501. pickingInfo.faceId = intersectInfo.faceId;
  12502. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12503. return pickingInfo;
  12504. }
  12505. return pickingInfo;
  12506. };
  12507. /**
  12508. * Clones the mesh, used by the class Mesh.
  12509. * Just returns `null` for an AbstractMesh.
  12510. */
  12511. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12512. return null;
  12513. };
  12514. /**
  12515. * Disposes all the mesh submeshes.
  12516. * Returns the AbstractMesh.
  12517. */
  12518. AbstractMesh.prototype.releaseSubMeshes = function () {
  12519. if (this.subMeshes) {
  12520. while (this.subMeshes.length) {
  12521. this.subMeshes[0].dispose();
  12522. }
  12523. }
  12524. else {
  12525. this.subMeshes = new Array();
  12526. }
  12527. return this;
  12528. };
  12529. /**
  12530. * Disposes the AbstractMesh.
  12531. * Some internal references are kept for further use.
  12532. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12533. * Returns nothing.
  12534. */
  12535. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12536. var _this = this;
  12537. var index;
  12538. // Action manager
  12539. if (this.actionManager) {
  12540. this.actionManager.dispose();
  12541. this.actionManager = null;
  12542. }
  12543. // Skeleton
  12544. this.skeleton = null;
  12545. // Animations
  12546. this.getScene().stopAnimation(this);
  12547. // Physics
  12548. if (this.physicsImpostor) {
  12549. this.physicsImpostor.dispose();
  12550. }
  12551. // Intersections in progress
  12552. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12553. var other = this._intersectionsInProgress[index];
  12554. var pos = other._intersectionsInProgress.indexOf(this);
  12555. other._intersectionsInProgress.splice(pos, 1);
  12556. }
  12557. this._intersectionsInProgress = [];
  12558. // Lights
  12559. var lights = this.getScene().lights;
  12560. lights.forEach(function (light) {
  12561. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12562. if (meshIndex !== -1) {
  12563. light.includedOnlyMeshes.splice(meshIndex, 1);
  12564. }
  12565. meshIndex = light.excludedMeshes.indexOf(_this);
  12566. if (meshIndex !== -1) {
  12567. light.excludedMeshes.splice(meshIndex, 1);
  12568. }
  12569. // Shadow generators
  12570. var generator = light.getShadowGenerator();
  12571. if (generator) {
  12572. var shadowMap = generator.getShadowMap();
  12573. meshIndex = shadowMap.renderList.indexOf(_this);
  12574. if (meshIndex !== -1) {
  12575. shadowMap.renderList.splice(meshIndex, 1);
  12576. }
  12577. }
  12578. });
  12579. // Edges
  12580. if (this._edgesRenderer) {
  12581. this._edgesRenderer.dispose();
  12582. this._edgesRenderer = null;
  12583. }
  12584. // SubMeshes
  12585. if (this.getClassName() !== "InstancedMesh") {
  12586. this.releaseSubMeshes();
  12587. }
  12588. // Octree
  12589. var sceneOctree = this.getScene().selectionOctree;
  12590. if (sceneOctree) {
  12591. var index = sceneOctree.dynamicContent.indexOf(this);
  12592. if (index !== -1) {
  12593. sceneOctree.dynamicContent.splice(index, 1);
  12594. }
  12595. }
  12596. // Engine
  12597. this.getScene().getEngine().wipeCaches();
  12598. // Remove from scene
  12599. this.getScene().removeMesh(this);
  12600. if (!doNotRecurse) {
  12601. // Particles
  12602. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12603. if (this.getScene().particleSystems[index].emitter === this) {
  12604. this.getScene().particleSystems[index].dispose();
  12605. index--;
  12606. }
  12607. }
  12608. // Children
  12609. var objects = this.getDescendants(true);
  12610. for (index = 0; index < objects.length; index++) {
  12611. objects[index].dispose();
  12612. }
  12613. }
  12614. else {
  12615. var childMeshes = this.getChildMeshes(true);
  12616. for (index = 0; index < childMeshes.length; index++) {
  12617. var child = childMeshes[index];
  12618. child.parent = null;
  12619. child.computeWorldMatrix(true);
  12620. }
  12621. }
  12622. // facet data
  12623. if (this._facetDataEnabled) {
  12624. this.disableFacetData();
  12625. }
  12626. this.onAfterWorldMatrixUpdateObservable.clear();
  12627. this.onCollideObservable.clear();
  12628. this.onCollisionPositionChangeObservable.clear();
  12629. this._isDisposed = true;
  12630. _super.prototype.dispose.call(this);
  12631. };
  12632. /**
  12633. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12634. * This Vector3 is expressed in the World space.
  12635. */
  12636. AbstractMesh.prototype.getDirection = function (localAxis) {
  12637. var result = BABYLON.Vector3.Zero();
  12638. this.getDirectionToRef(localAxis, result);
  12639. return result;
  12640. };
  12641. /**
  12642. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12643. * localAxis is expressed in the mesh local space.
  12644. * result is computed in the Wordl space from the mesh World matrix.
  12645. * Returns the AbstractMesh.
  12646. */
  12647. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12648. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12649. return this;
  12650. };
  12651. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12652. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12653. if (this.getScene().getRenderId() == 0) {
  12654. this.computeWorldMatrix(true);
  12655. }
  12656. var wm = this.getWorldMatrix();
  12657. if (space == BABYLON.Space.WORLD) {
  12658. var tmat = BABYLON.Tmp.Matrix[0];
  12659. wm.invertToRef(tmat);
  12660. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12661. }
  12662. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12663. this._pivotMatrix.m[12] = -point.x;
  12664. this._pivotMatrix.m[13] = -point.y;
  12665. this._pivotMatrix.m[14] = -point.z;
  12666. this._cache.pivotMatrixUpdated = true;
  12667. return this;
  12668. };
  12669. /**
  12670. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12671. */
  12672. AbstractMesh.prototype.getPivotPoint = function () {
  12673. var point = BABYLON.Vector3.Zero();
  12674. this.getPivotPointToRef(point);
  12675. return point;
  12676. };
  12677. /**
  12678. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12679. * Returns the AbstractMesh.
  12680. */
  12681. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12682. result.x = -this._pivotMatrix.m[12];
  12683. result.y = -this._pivotMatrix.m[13];
  12684. result.z = -this._pivotMatrix.m[14];
  12685. return this;
  12686. };
  12687. /**
  12688. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12689. */
  12690. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12691. var point = BABYLON.Vector3.Zero();
  12692. this.getAbsolutePivotPointToRef(point);
  12693. return point;
  12694. };
  12695. /**
  12696. * Defines the passed mesh as the parent of the current mesh.
  12697. * Returns the AbstractMesh.
  12698. */
  12699. AbstractMesh.prototype.setParent = function (mesh) {
  12700. var child = this;
  12701. var parent = mesh;
  12702. if (mesh == null) {
  12703. var rotation = BABYLON.Tmp.Quaternion[0];
  12704. var position = BABYLON.Tmp.Vector3[0];
  12705. var scale = BABYLON.Tmp.Vector3[1];
  12706. child.getWorldMatrix().decompose(scale, rotation, position);
  12707. if (child.rotationQuaternion) {
  12708. child.rotationQuaternion.copyFrom(rotation);
  12709. }
  12710. else {
  12711. rotation.toEulerAnglesToRef(child.rotation);
  12712. }
  12713. child.position.x = position.x;
  12714. child.position.y = position.y;
  12715. child.position.z = position.z;
  12716. }
  12717. else {
  12718. var rotation = BABYLON.Tmp.Quaternion[0];
  12719. var position = BABYLON.Tmp.Vector3[0];
  12720. var scale = BABYLON.Tmp.Vector3[1];
  12721. var m1 = BABYLON.Tmp.Matrix[0];
  12722. var m2 = BABYLON.Tmp.Matrix[1];
  12723. parent.getWorldMatrix().decompose(scale, rotation, position);
  12724. rotation.toRotationMatrix(m1);
  12725. m2.setTranslation(position);
  12726. m2.multiplyToRef(m1, m1);
  12727. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12728. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12729. m.decompose(scale, rotation, position);
  12730. if (child.rotationQuaternion) {
  12731. child.rotationQuaternion.copyFrom(rotation);
  12732. }
  12733. else {
  12734. rotation.toEulerAnglesToRef(child.rotation);
  12735. }
  12736. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12737. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12738. m.decompose(scale, rotation, position);
  12739. child.position.x = position.x;
  12740. child.position.y = position.y;
  12741. child.position.z = position.z;
  12742. }
  12743. child.parent = parent;
  12744. return this;
  12745. };
  12746. /**
  12747. * Adds the passed mesh as a child to the current mesh.
  12748. * Returns the AbstractMesh.
  12749. */
  12750. AbstractMesh.prototype.addChild = function (mesh) {
  12751. mesh.setParent(this);
  12752. return this;
  12753. };
  12754. /**
  12755. * Removes the passed mesh from the current mesh children list.
  12756. * Returns the AbstractMesh.
  12757. */
  12758. AbstractMesh.prototype.removeChild = function (mesh) {
  12759. mesh.setParent(null);
  12760. return this;
  12761. };
  12762. /**
  12763. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12764. * Returns the AbstractMesh.
  12765. */
  12766. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12767. result.x = this._pivotMatrix.m[12];
  12768. result.y = this._pivotMatrix.m[13];
  12769. result.z = this._pivotMatrix.m[14];
  12770. this.getPivotPointToRef(result);
  12771. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12772. return this;
  12773. };
  12774. // Facet data
  12775. /**
  12776. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12777. * Returns the AbstractMesh.
  12778. */
  12779. AbstractMesh.prototype._initFacetData = function () {
  12780. if (!this._facetNormals) {
  12781. this._facetNormals = new Array();
  12782. }
  12783. if (!this._facetPositions) {
  12784. this._facetPositions = new Array();
  12785. }
  12786. if (!this._facetPartitioning) {
  12787. this._facetPartitioning = new Array();
  12788. }
  12789. this._facetNb = this.getIndices().length / 3;
  12790. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12791. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12792. for (var f = 0; f < this._facetNb; f++) {
  12793. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12794. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12795. }
  12796. this._facetDataEnabled = true;
  12797. return this;
  12798. };
  12799. /**
  12800. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12801. * This method can be called within the render loop.
  12802. * 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.
  12803. * Returns the AbstractMesh.
  12804. */
  12805. AbstractMesh.prototype.updateFacetData = function () {
  12806. if (!this._facetDataEnabled) {
  12807. this._initFacetData();
  12808. }
  12809. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12810. var indices = this.getIndices();
  12811. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12812. var bInfo = this.getBoundingInfo();
  12813. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12814. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12815. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12816. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12817. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12818. this._subDiv.max = this._partitioningSubdivisions;
  12819. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12820. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12821. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12822. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12823. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12824. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12825. // set the parameters for ComputeNormals()
  12826. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12827. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12828. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12829. this._facetParameters.bInfo = bInfo;
  12830. this._facetParameters.bbSize = this._bbSize;
  12831. this._facetParameters.subDiv = this._subDiv;
  12832. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12833. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12834. return this;
  12835. };
  12836. /**
  12837. * Returns the facetLocalNormals array.
  12838. * The normals are expressed in the mesh local space.
  12839. */
  12840. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12841. if (!this._facetNormals) {
  12842. this.updateFacetData();
  12843. }
  12844. return this._facetNormals;
  12845. };
  12846. /**
  12847. * Returns the facetLocalPositions array.
  12848. * The facet positions are expressed in the mesh local space.
  12849. */
  12850. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12851. if (!this._facetPositions) {
  12852. this.updateFacetData();
  12853. }
  12854. return this._facetPositions;
  12855. };
  12856. /**
  12857. * Returns the facetLocalPartioning array.
  12858. */
  12859. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12860. if (!this._facetPartitioning) {
  12861. this.updateFacetData();
  12862. }
  12863. return this._facetPartitioning;
  12864. };
  12865. /**
  12866. * Returns the i-th facet position in the world system.
  12867. * This method allocates a new Vector3 per call.
  12868. */
  12869. AbstractMesh.prototype.getFacetPosition = function (i) {
  12870. var pos = BABYLON.Vector3.Zero();
  12871. this.getFacetPositionToRef(i, pos);
  12872. return pos;
  12873. };
  12874. /**
  12875. * Sets the reference Vector3 with the i-th facet position in the world system.
  12876. * Returns the AbstractMesh.
  12877. */
  12878. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12879. var localPos = (this.getFacetLocalPositions())[i];
  12880. var world = this.getWorldMatrix();
  12881. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12882. return this;
  12883. };
  12884. /**
  12885. * Returns the i-th facet normal in the world system.
  12886. * This method allocates a new Vector3 per call.
  12887. */
  12888. AbstractMesh.prototype.getFacetNormal = function (i) {
  12889. var norm = BABYLON.Vector3.Zero();
  12890. this.getFacetNormalToRef(i, norm);
  12891. return norm;
  12892. };
  12893. /**
  12894. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12895. * Returns the AbstractMesh.
  12896. */
  12897. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12898. var localNorm = (this.getFacetLocalNormals())[i];
  12899. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12900. return this;
  12901. };
  12902. /**
  12903. * 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).
  12904. */
  12905. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12906. var bInfo = this.getBoundingInfo();
  12907. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12908. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  12909. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  12910. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  12911. return null;
  12912. }
  12913. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  12914. };
  12915. /**
  12916. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  12917. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  12918. * 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.
  12919. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12920. * 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.
  12921. */
  12922. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  12923. if (checkFace === void 0) { checkFace = false; }
  12924. if (facing === void 0) { facing = true; }
  12925. var world = this.getWorldMatrix();
  12926. var invMat = BABYLON.Tmp.Matrix[5];
  12927. world.invertToRef(invMat);
  12928. var invVect = BABYLON.Tmp.Vector3[8];
  12929. var closest = null;
  12930. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  12931. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  12932. if (projected) {
  12933. // tranform the local computed projected vector to world coordinates
  12934. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  12935. }
  12936. return closest;
  12937. };
  12938. /**
  12939. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  12940. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  12941. * 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.
  12942. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12943. * 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.
  12944. */
  12945. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  12946. if (checkFace === void 0) { checkFace = false; }
  12947. if (facing === void 0) { facing = true; }
  12948. var closest = null;
  12949. var tmpx = 0.0;
  12950. var tmpy = 0.0;
  12951. var tmpz = 0.0;
  12952. var d = 0.0; // tmp dot facet normal * facet position
  12953. var t0 = 0.0;
  12954. var projx = 0.0;
  12955. var projy = 0.0;
  12956. var projz = 0.0;
  12957. // Get all the facets in the same partitioning block than (x, y, z)
  12958. var facetPositions = this.getFacetLocalPositions();
  12959. var facetNormals = this.getFacetLocalNormals();
  12960. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  12961. if (!facetsInBlock) {
  12962. return null;
  12963. }
  12964. // Get the closest facet to (x, y, z)
  12965. var shortest = Number.MAX_VALUE; // init distance vars
  12966. var tmpDistance = shortest;
  12967. var fib; // current facet in the block
  12968. var norm; // current facet normal
  12969. var p0; // current facet barycenter position
  12970. // loop on all the facets in the current partitioning block
  12971. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  12972. fib = facetsInBlock[idx];
  12973. norm = facetNormals[fib];
  12974. p0 = facetPositions[fib];
  12975. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  12976. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  12977. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  12978. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  12979. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  12980. projx = x + norm.x * t0;
  12981. projy = y + norm.y * t0;
  12982. projz = z + norm.z * t0;
  12983. tmpx = projx - x;
  12984. tmpy = projy - y;
  12985. tmpz = projz - z;
  12986. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  12987. if (tmpDistance < shortest) {
  12988. shortest = tmpDistance;
  12989. closest = fib;
  12990. if (projected) {
  12991. projected.x = projx;
  12992. projected.y = projy;
  12993. projected.z = projz;
  12994. }
  12995. }
  12996. }
  12997. }
  12998. return closest;
  12999. };
  13000. /**
  13001. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13002. */
  13003. AbstractMesh.prototype.getFacetDataParameters = function () {
  13004. return this._facetParameters;
  13005. };
  13006. /**
  13007. * Disables the feature FacetData and frees the related memory.
  13008. * Returns the AbstractMesh.
  13009. */
  13010. AbstractMesh.prototype.disableFacetData = function () {
  13011. if (this._facetDataEnabled) {
  13012. this._facetDataEnabled = false;
  13013. this._facetPositions = null;
  13014. this._facetNormals = null;
  13015. this._facetPartitioning = null;
  13016. this._facetParameters = null;
  13017. }
  13018. return this;
  13019. };
  13020. /**
  13021. * Creates new normals data for the mesh.
  13022. * @param updatable.
  13023. */
  13024. AbstractMesh.prototype.createNormals = function (updatable) {
  13025. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13026. var indices = this.getIndices();
  13027. var normals;
  13028. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13029. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13030. }
  13031. else {
  13032. normals = [];
  13033. }
  13034. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13035. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13036. };
  13037. return AbstractMesh;
  13038. }(BABYLON.Node));
  13039. // Statics
  13040. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13041. AbstractMesh._BILLBOARDMODE_X = 1;
  13042. AbstractMesh._BILLBOARDMODE_Y = 2;
  13043. AbstractMesh._BILLBOARDMODE_Z = 4;
  13044. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13045. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13046. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13047. BABYLON.AbstractMesh = AbstractMesh;
  13048. })(BABYLON || (BABYLON = {}));
  13049. //# sourceMappingURL=babylon.abstractMesh.js.map
  13050. var BABYLON;
  13051. (function (BABYLON) {
  13052. var Light = (function (_super) {
  13053. __extends(Light, _super);
  13054. /**
  13055. * Creates a Light object in the scene.
  13056. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13057. */
  13058. function Light(name, scene) {
  13059. var _this = _super.call(this, name, scene) || this;
  13060. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13061. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13062. _this.intensity = 1.0;
  13063. _this.range = Number.MAX_VALUE;
  13064. /**
  13065. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13066. * of light.
  13067. */
  13068. _this._photometricScale = 1.0;
  13069. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13070. _this._radius = 0.00001;
  13071. _this.renderPriority = 0;
  13072. /**
  13073. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13074. * the current shadow generator.
  13075. */
  13076. _this.shadowEnabled = true;
  13077. _this._excludeWithLayerMask = 0;
  13078. _this._includeOnlyWithLayerMask = 0;
  13079. _this._lightmapMode = 0;
  13080. _this._excludedMeshesIds = new Array();
  13081. _this._includedOnlyMeshesIds = new Array();
  13082. _this.getScene().addLight(_this);
  13083. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13084. _this._buildUniformLayout();
  13085. _this.includedOnlyMeshes = new Array();
  13086. _this.excludedMeshes = new Array();
  13087. _this._resyncMeshes();
  13088. return _this;
  13089. }
  13090. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13091. /**
  13092. * If every light affecting the material is in this lightmapMode,
  13093. * material.lightmapTexture adds or multiplies
  13094. * (depends on material.useLightmapAsShadowmap)
  13095. * after every other light calculations.
  13096. */
  13097. get: function () {
  13098. return Light._LIGHTMAP_DEFAULT;
  13099. },
  13100. enumerable: true,
  13101. configurable: true
  13102. });
  13103. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13104. /**
  13105. * material.lightmapTexture as only diffuse lighting from this light
  13106. * adds pnly specular lighting from this light
  13107. * adds dynamic shadows
  13108. */
  13109. get: function () {
  13110. return Light._LIGHTMAP_SPECULAR;
  13111. },
  13112. enumerable: true,
  13113. configurable: true
  13114. });
  13115. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13116. /**
  13117. * material.lightmapTexture as only lighting
  13118. * no light calculation from this light
  13119. * only adds dynamic shadows from this light
  13120. */
  13121. get: function () {
  13122. return Light._LIGHTMAP_SHADOWSONLY;
  13123. },
  13124. enumerable: true,
  13125. configurable: true
  13126. });
  13127. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13128. /**
  13129. * Each light type uses the default quantity according to its type:
  13130. * point/spot lights use luminous intensity
  13131. * directional lights use illuminance
  13132. */
  13133. get: function () {
  13134. return Light._INTENSITYMODE_AUTOMATIC;
  13135. },
  13136. enumerable: true,
  13137. configurable: true
  13138. });
  13139. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13140. /**
  13141. * lumen (lm)
  13142. */
  13143. get: function () {
  13144. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13145. },
  13146. enumerable: true,
  13147. configurable: true
  13148. });
  13149. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13150. /**
  13151. * candela (lm/sr)
  13152. */
  13153. get: function () {
  13154. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13155. },
  13156. enumerable: true,
  13157. configurable: true
  13158. });
  13159. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13160. /**
  13161. * lux (lm/m^2)
  13162. */
  13163. get: function () {
  13164. return Light._INTENSITYMODE_ILLUMINANCE;
  13165. },
  13166. enumerable: true,
  13167. configurable: true
  13168. });
  13169. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13170. /**
  13171. * nit (cd/m^2)
  13172. */
  13173. get: function () {
  13174. return Light._INTENSITYMODE_LUMINANCE;
  13175. },
  13176. enumerable: true,
  13177. configurable: true
  13178. });
  13179. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13180. /**
  13181. * Light type const id of the point light.
  13182. */
  13183. get: function () {
  13184. return Light._LIGHTTYPEID_POINTLIGHT;
  13185. },
  13186. enumerable: true,
  13187. configurable: true
  13188. });
  13189. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13190. /**
  13191. * Light type const id of the directional light.
  13192. */
  13193. get: function () {
  13194. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13195. },
  13196. enumerable: true,
  13197. configurable: true
  13198. });
  13199. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13200. /**
  13201. * Light type const id of the spot light.
  13202. */
  13203. get: function () {
  13204. return Light._LIGHTTYPEID_SPOTLIGHT;
  13205. },
  13206. enumerable: true,
  13207. configurable: true
  13208. });
  13209. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13210. /**
  13211. * Light type const id of the hemispheric light.
  13212. */
  13213. get: function () {
  13214. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13215. },
  13216. enumerable: true,
  13217. configurable: true
  13218. });
  13219. Object.defineProperty(Light.prototype, "intensityMode", {
  13220. /**
  13221. * Gets the photometric scale used to interpret the intensity.
  13222. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13223. */
  13224. get: function () {
  13225. return this._intensityMode;
  13226. },
  13227. /**
  13228. * Sets the photometric scale used to interpret the intensity.
  13229. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13230. */
  13231. set: function (value) {
  13232. this._intensityMode = value;
  13233. this._computePhotometricScale();
  13234. },
  13235. enumerable: true,
  13236. configurable: true
  13237. });
  13238. ;
  13239. ;
  13240. Object.defineProperty(Light.prototype, "radius", {
  13241. /**
  13242. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13243. */
  13244. get: function () {
  13245. return this._radius;
  13246. },
  13247. /**
  13248. * sets the light radius used by PBR Materials to simulate soft area lights.
  13249. */
  13250. set: function (value) {
  13251. this._radius = value;
  13252. this._computePhotometricScale();
  13253. },
  13254. enumerable: true,
  13255. configurable: true
  13256. });
  13257. ;
  13258. ;
  13259. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13260. get: function () {
  13261. return this._includedOnlyMeshes;
  13262. },
  13263. set: function (value) {
  13264. this._includedOnlyMeshes = value;
  13265. this._hookArrayForIncludedOnly(value);
  13266. },
  13267. enumerable: true,
  13268. configurable: true
  13269. });
  13270. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13271. get: function () {
  13272. return this._excludedMeshes;
  13273. },
  13274. set: function (value) {
  13275. this._excludedMeshes = value;
  13276. this._hookArrayForExcluded(value);
  13277. },
  13278. enumerable: true,
  13279. configurable: true
  13280. });
  13281. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13282. get: function () {
  13283. return this._excludeWithLayerMask;
  13284. },
  13285. set: function (value) {
  13286. this._excludeWithLayerMask = value;
  13287. this._resyncMeshes();
  13288. },
  13289. enumerable: true,
  13290. configurable: true
  13291. });
  13292. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13293. get: function () {
  13294. return this._includeOnlyWithLayerMask;
  13295. },
  13296. set: function (value) {
  13297. this._includeOnlyWithLayerMask = value;
  13298. this._resyncMeshes();
  13299. },
  13300. enumerable: true,
  13301. configurable: true
  13302. });
  13303. Object.defineProperty(Light.prototype, "lightmapMode", {
  13304. get: function () {
  13305. return this._lightmapMode;
  13306. },
  13307. set: function (value) {
  13308. if (this._lightmapMode === value) {
  13309. return;
  13310. }
  13311. this._lightmapMode = value;
  13312. this._markMeshesAsLightDirty();
  13313. },
  13314. enumerable: true,
  13315. configurable: true
  13316. });
  13317. Light.prototype._buildUniformLayout = function () {
  13318. // Overridden
  13319. };
  13320. /**
  13321. * Returns the string "Light".
  13322. */
  13323. Light.prototype.getClassName = function () {
  13324. return "Light";
  13325. };
  13326. /**
  13327. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13328. */
  13329. Light.prototype.toString = function (fullDetails) {
  13330. var ret = "Name: " + this.name;
  13331. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13332. if (this.animations) {
  13333. for (var i = 0; i < this.animations.length; i++) {
  13334. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13335. }
  13336. }
  13337. if (fullDetails) {
  13338. }
  13339. return ret;
  13340. };
  13341. /**
  13342. * Set the enabled state of this node.
  13343. * @param {boolean} value - the new enabled state
  13344. * @see isEnabled
  13345. */
  13346. Light.prototype.setEnabled = function (value) {
  13347. _super.prototype.setEnabled.call(this, value);
  13348. this._resyncMeshes();
  13349. };
  13350. /**
  13351. * Returns the Light associated shadow generator.
  13352. */
  13353. Light.prototype.getShadowGenerator = function () {
  13354. return this._shadowGenerator;
  13355. };
  13356. /**
  13357. * Returns a Vector3, the absolute light position in the World.
  13358. */
  13359. Light.prototype.getAbsolutePosition = function () {
  13360. return BABYLON.Vector3.Zero();
  13361. };
  13362. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13363. };
  13364. Light.prototype._getWorldMatrix = function () {
  13365. return BABYLON.Matrix.Identity();
  13366. };
  13367. /**
  13368. * Boolean : True if the light will affect the passed mesh.
  13369. */
  13370. Light.prototype.canAffectMesh = function (mesh) {
  13371. if (!mesh) {
  13372. return true;
  13373. }
  13374. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13375. return false;
  13376. }
  13377. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13378. return false;
  13379. }
  13380. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13381. return false;
  13382. }
  13383. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13384. return false;
  13385. }
  13386. return true;
  13387. };
  13388. /**
  13389. * Returns the light World matrix.
  13390. */
  13391. Light.prototype.getWorldMatrix = function () {
  13392. this._currentRenderId = this.getScene().getRenderId();
  13393. var worldMatrix = this._getWorldMatrix();
  13394. if (this.parent && this.parent.getWorldMatrix) {
  13395. if (!this._parentedWorldMatrix) {
  13396. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13397. }
  13398. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13399. this._markSyncedWithParent();
  13400. return this._parentedWorldMatrix;
  13401. }
  13402. return worldMatrix;
  13403. };
  13404. /**
  13405. * Sort function to order lights for rendering.
  13406. * @param a First Light object to compare to second.
  13407. * @param b Second Light object to compare first.
  13408. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13409. */
  13410. Light.compareLightsPriority = function (a, b) {
  13411. //shadow-casting lights have priority over non-shadow-casting lights
  13412. //the renderPrioirty is a secondary sort criterion
  13413. if (a.shadowEnabled !== b.shadowEnabled) {
  13414. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13415. }
  13416. return b.renderPriority - a.renderPriority;
  13417. };
  13418. /**
  13419. * Disposes the light.
  13420. */
  13421. Light.prototype.dispose = function () {
  13422. if (this._shadowGenerator) {
  13423. this._shadowGenerator.dispose();
  13424. this._shadowGenerator = null;
  13425. }
  13426. // Animations
  13427. this.getScene().stopAnimation(this);
  13428. // Remove from meshes
  13429. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13430. var mesh = _a[_i];
  13431. mesh._removeLightSource(this);
  13432. }
  13433. this._uniformBuffer.dispose();
  13434. // Remove from scene
  13435. this.getScene().removeLight(this);
  13436. _super.prototype.dispose.call(this);
  13437. };
  13438. /**
  13439. * Returns the light type ID (integer).
  13440. */
  13441. Light.prototype.getTypeID = function () {
  13442. return 0;
  13443. };
  13444. /**
  13445. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13446. */
  13447. Light.prototype.getScaledIntensity = function () {
  13448. return this._photometricScale * this.intensity;
  13449. };
  13450. /**
  13451. * Returns a new Light object, named "name", from the current one.
  13452. */
  13453. Light.prototype.clone = function (name) {
  13454. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13455. };
  13456. /**
  13457. * Serializes the current light into a Serialization object.
  13458. * Returns the serialized object.
  13459. */
  13460. Light.prototype.serialize = function () {
  13461. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13462. // Type
  13463. serializationObject.type = this.getTypeID();
  13464. // Parent
  13465. if (this.parent) {
  13466. serializationObject.parentId = this.parent.id;
  13467. }
  13468. // Inclusion / exclusions
  13469. if (this.excludedMeshes.length > 0) {
  13470. serializationObject.excludedMeshesIds = [];
  13471. this.excludedMeshes.forEach(function (mesh) {
  13472. serializationObject.excludedMeshesIds.push(mesh.id);
  13473. });
  13474. }
  13475. if (this.includedOnlyMeshes.length > 0) {
  13476. serializationObject.includedOnlyMeshesIds = [];
  13477. this.includedOnlyMeshes.forEach(function (mesh) {
  13478. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13479. });
  13480. }
  13481. // Animations
  13482. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13483. serializationObject.ranges = this.serializeAnimationRanges();
  13484. return serializationObject;
  13485. };
  13486. /**
  13487. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13488. * This new light is named "name" and added to the passed scene.
  13489. */
  13490. Light.GetConstructorFromName = function (type, name, scene) {
  13491. switch (type) {
  13492. case 0:
  13493. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13494. case 1:
  13495. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13496. case 2:
  13497. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13498. case 3:
  13499. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13500. }
  13501. };
  13502. /**
  13503. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13504. */
  13505. Light.Parse = function (parsedLight, scene) {
  13506. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13507. // Inclusion / exclusions
  13508. if (parsedLight.excludedMeshesIds) {
  13509. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13510. }
  13511. if (parsedLight.includedOnlyMeshesIds) {
  13512. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13513. }
  13514. // Parent
  13515. if (parsedLight.parentId) {
  13516. light._waitingParentId = parsedLight.parentId;
  13517. }
  13518. // Animations
  13519. if (parsedLight.animations) {
  13520. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13521. var parsedAnimation = parsedLight.animations[animationIndex];
  13522. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13523. }
  13524. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13525. }
  13526. if (parsedLight.autoAnimate) {
  13527. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13528. }
  13529. return light;
  13530. };
  13531. Light.prototype._hookArrayForExcluded = function (array) {
  13532. var _this = this;
  13533. var oldPush = array.push;
  13534. array.push = function () {
  13535. var items = [];
  13536. for (var _i = 0; _i < arguments.length; _i++) {
  13537. items[_i] = arguments[_i];
  13538. }
  13539. var result = oldPush.apply(array, items);
  13540. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13541. var item = items_1[_a];
  13542. item._resyncLighSource(_this);
  13543. }
  13544. return result;
  13545. };
  13546. var oldSplice = array.splice;
  13547. array.splice = function (index, deleteCount) {
  13548. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13549. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13550. var item = deleted_1[_i];
  13551. item._resyncLighSource(_this);
  13552. }
  13553. return deleted;
  13554. };
  13555. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13556. var item = array_1[_i];
  13557. item._resyncLighSource(this);
  13558. }
  13559. };
  13560. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13561. var _this = this;
  13562. var oldPush = array.push;
  13563. array.push = function () {
  13564. var items = [];
  13565. for (var _i = 0; _i < arguments.length; _i++) {
  13566. items[_i] = arguments[_i];
  13567. }
  13568. var result = oldPush.apply(array, items);
  13569. _this._resyncMeshes();
  13570. return result;
  13571. };
  13572. var oldSplice = array.splice;
  13573. array.splice = function (index, deleteCount) {
  13574. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13575. _this._resyncMeshes();
  13576. return deleted;
  13577. };
  13578. this._resyncMeshes();
  13579. };
  13580. Light.prototype._resyncMeshes = function () {
  13581. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13582. var mesh = _a[_i];
  13583. mesh._resyncLighSource(this);
  13584. }
  13585. };
  13586. Light.prototype._markMeshesAsLightDirty = function () {
  13587. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13588. var mesh = _a[_i];
  13589. if (mesh._lightSources.indexOf(this) !== -1) {
  13590. mesh._markSubMeshesAsLightDirty();
  13591. }
  13592. }
  13593. };
  13594. /**
  13595. * Recomputes the cached photometric scale if needed.
  13596. */
  13597. Light.prototype._computePhotometricScale = function () {
  13598. this._photometricScale = this._getPhotometricScale();
  13599. this.getScene().resetCachedMaterial();
  13600. };
  13601. /**
  13602. * Returns the Photometric Scale according to the light type and intensity mode.
  13603. */
  13604. Light.prototype._getPhotometricScale = function () {
  13605. var photometricScale = 0.0;
  13606. var lightTypeID = this.getTypeID();
  13607. //get photometric mode
  13608. var photometricMode = this.intensityMode;
  13609. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13610. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13611. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13612. }
  13613. else {
  13614. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13615. }
  13616. }
  13617. //compute photometric scale
  13618. switch (lightTypeID) {
  13619. case Light.LIGHTTYPEID_POINTLIGHT:
  13620. case Light.LIGHTTYPEID_SPOTLIGHT:
  13621. switch (photometricMode) {
  13622. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13623. photometricScale = 1.0 / (4.0 * Math.PI);
  13624. break;
  13625. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13626. photometricScale = 1.0;
  13627. break;
  13628. case Light.INTENSITYMODE_LUMINANCE:
  13629. photometricScale = this.radius * this.radius;
  13630. break;
  13631. }
  13632. break;
  13633. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13634. switch (photometricMode) {
  13635. case Light.INTENSITYMODE_ILLUMINANCE:
  13636. photometricScale = 1.0;
  13637. break;
  13638. case Light.INTENSITYMODE_LUMINANCE:
  13639. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13640. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13641. var apexAngleRadians = this.radius;
  13642. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13643. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13644. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13645. photometricScale = solidAngle;
  13646. break;
  13647. }
  13648. break;
  13649. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13650. // No fall off in hemisperic light.
  13651. photometricScale = 1.0;
  13652. break;
  13653. }
  13654. return photometricScale;
  13655. };
  13656. Light.prototype._reorderLightsInScene = function () {
  13657. var scene = this.getScene();
  13658. if (this.renderPriority != 0) {
  13659. scene.requireLightSorting = true;
  13660. }
  13661. this.getScene().sortLightsByPriority();
  13662. };
  13663. return Light;
  13664. }(BABYLON.Node));
  13665. //lightmapMode Consts
  13666. Light._LIGHTMAP_DEFAULT = 0;
  13667. Light._LIGHTMAP_SPECULAR = 1;
  13668. Light._LIGHTMAP_SHADOWSONLY = 2;
  13669. // Intensity Mode Consts
  13670. Light._INTENSITYMODE_AUTOMATIC = 0;
  13671. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13672. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13673. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13674. Light._INTENSITYMODE_LUMINANCE = 4;
  13675. // Light types ids const.
  13676. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13677. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13678. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13679. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13680. __decorate([
  13681. BABYLON.serializeAsColor3()
  13682. ], Light.prototype, "diffuse", void 0);
  13683. __decorate([
  13684. BABYLON.serializeAsColor3()
  13685. ], Light.prototype, "specular", void 0);
  13686. __decorate([
  13687. BABYLON.serialize()
  13688. ], Light.prototype, "intensity", void 0);
  13689. __decorate([
  13690. BABYLON.serialize()
  13691. ], Light.prototype, "range", void 0);
  13692. __decorate([
  13693. BABYLON.serialize()
  13694. ], Light.prototype, "intensityMode", null);
  13695. __decorate([
  13696. BABYLON.serialize()
  13697. ], Light.prototype, "radius", null);
  13698. __decorate([
  13699. BABYLON.serialize()
  13700. ], Light.prototype, "_renderPriority", void 0);
  13701. __decorate([
  13702. BABYLON.expandToProperty("_reorderLightsInScene")
  13703. ], Light.prototype, "renderPriority", void 0);
  13704. __decorate([
  13705. BABYLON.serialize()
  13706. ], Light.prototype, "shadowEnabled", void 0);
  13707. __decorate([
  13708. BABYLON.serialize("excludeWithLayerMask")
  13709. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13710. __decorate([
  13711. BABYLON.serialize("includeOnlyWithLayerMask")
  13712. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13713. __decorate([
  13714. BABYLON.serialize("lightmapMode")
  13715. ], Light.prototype, "_lightmapMode", void 0);
  13716. BABYLON.Light = Light;
  13717. })(BABYLON || (BABYLON = {}));
  13718. //# sourceMappingURL=babylon.light.js.map
  13719. var BABYLON;
  13720. (function (BABYLON) {
  13721. var Camera = (function (_super) {
  13722. __extends(Camera, _super);
  13723. function Camera(name, position, scene) {
  13724. var _this = _super.call(this, name, scene) || this;
  13725. _this.upVector = BABYLON.Vector3.Up();
  13726. _this.orthoLeft = null;
  13727. _this.orthoRight = null;
  13728. _this.orthoBottom = null;
  13729. _this.orthoTop = null;
  13730. _this.fov = 0.8;
  13731. _this.minZ = 1.0;
  13732. _this.maxZ = 10000.0;
  13733. _this.inertia = 0.9;
  13734. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13735. _this.isIntermediate = false;
  13736. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13737. _this.layerMask = 0x0FFFFFFF;
  13738. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13739. // Camera rig members
  13740. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13741. _this._rigCameras = new Array();
  13742. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13743. // Cache
  13744. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13745. _this._projectionMatrix = new BABYLON.Matrix();
  13746. _this._doNotComputeProjectionMatrix = false;
  13747. _this._postProcesses = new Array();
  13748. _this._transformMatrix = BABYLON.Matrix.Zero();
  13749. _this._activeMeshes = new BABYLON.SmartArray(256);
  13750. _this._globalPosition = BABYLON.Vector3.Zero();
  13751. _this._refreshFrustumPlanes = true;
  13752. _this.getScene().addCamera(_this);
  13753. if (!_this.getScene().activeCamera) {
  13754. _this.getScene().activeCamera = _this;
  13755. }
  13756. _this.position = position;
  13757. return _this;
  13758. }
  13759. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13760. get: function () {
  13761. return Camera._PERSPECTIVE_CAMERA;
  13762. },
  13763. enumerable: true,
  13764. configurable: true
  13765. });
  13766. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13767. get: function () {
  13768. return Camera._ORTHOGRAPHIC_CAMERA;
  13769. },
  13770. enumerable: true,
  13771. configurable: true
  13772. });
  13773. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13774. get: function () {
  13775. return Camera._FOVMODE_VERTICAL_FIXED;
  13776. },
  13777. enumerable: true,
  13778. configurable: true
  13779. });
  13780. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13781. get: function () {
  13782. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13783. },
  13784. enumerable: true,
  13785. configurable: true
  13786. });
  13787. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13788. get: function () {
  13789. return Camera._RIG_MODE_NONE;
  13790. },
  13791. enumerable: true,
  13792. configurable: true
  13793. });
  13794. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13795. get: function () {
  13796. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13797. },
  13798. enumerable: true,
  13799. configurable: true
  13800. });
  13801. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13802. get: function () {
  13803. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13804. },
  13805. enumerable: true,
  13806. configurable: true
  13807. });
  13808. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13809. get: function () {
  13810. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13811. },
  13812. enumerable: true,
  13813. configurable: true
  13814. });
  13815. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13816. get: function () {
  13817. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13818. },
  13819. enumerable: true,
  13820. configurable: true
  13821. });
  13822. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13823. get: function () {
  13824. return Camera._RIG_MODE_VR;
  13825. },
  13826. enumerable: true,
  13827. configurable: true
  13828. });
  13829. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13830. get: function () {
  13831. return Camera._RIG_MODE_WEBVR;
  13832. },
  13833. enumerable: true,
  13834. configurable: true
  13835. });
  13836. Camera.prototype.getClassName = function () {
  13837. return "Camera";
  13838. };
  13839. /**
  13840. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13841. */
  13842. Camera.prototype.toString = function (fullDetails) {
  13843. var ret = "Name: " + this.name;
  13844. ret += ", type: " + this.getClassName();
  13845. if (this.animations) {
  13846. for (var i = 0; i < this.animations.length; i++) {
  13847. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13848. }
  13849. }
  13850. if (fullDetails) {
  13851. }
  13852. return ret;
  13853. };
  13854. Object.defineProperty(Camera.prototype, "globalPosition", {
  13855. get: function () {
  13856. return this._globalPosition;
  13857. },
  13858. enumerable: true,
  13859. configurable: true
  13860. });
  13861. Camera.prototype.getActiveMeshes = function () {
  13862. return this._activeMeshes;
  13863. };
  13864. Camera.prototype.isActiveMesh = function (mesh) {
  13865. return (this._activeMeshes.indexOf(mesh) !== -1);
  13866. };
  13867. //Cache
  13868. Camera.prototype._initCache = function () {
  13869. _super.prototype._initCache.call(this);
  13870. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13871. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13872. this._cache.mode = undefined;
  13873. this._cache.minZ = undefined;
  13874. this._cache.maxZ = undefined;
  13875. this._cache.fov = undefined;
  13876. this._cache.fovMode = undefined;
  13877. this._cache.aspectRatio = undefined;
  13878. this._cache.orthoLeft = undefined;
  13879. this._cache.orthoRight = undefined;
  13880. this._cache.orthoBottom = undefined;
  13881. this._cache.orthoTop = undefined;
  13882. this._cache.renderWidth = undefined;
  13883. this._cache.renderHeight = undefined;
  13884. };
  13885. Camera.prototype._updateCache = function (ignoreParentClass) {
  13886. if (!ignoreParentClass) {
  13887. _super.prototype._updateCache.call(this);
  13888. }
  13889. var engine = this.getEngine();
  13890. this._cache.position.copyFrom(this.position);
  13891. this._cache.upVector.copyFrom(this.upVector);
  13892. this._cache.mode = this.mode;
  13893. this._cache.minZ = this.minZ;
  13894. this._cache.maxZ = this.maxZ;
  13895. this._cache.fov = this.fov;
  13896. this._cache.fovMode = this.fovMode;
  13897. this._cache.aspectRatio = engine.getAspectRatio(this);
  13898. this._cache.orthoLeft = this.orthoLeft;
  13899. this._cache.orthoRight = this.orthoRight;
  13900. this._cache.orthoBottom = this.orthoBottom;
  13901. this._cache.orthoTop = this.orthoTop;
  13902. this._cache.renderWidth = engine.getRenderWidth();
  13903. this._cache.renderHeight = engine.getRenderHeight();
  13904. };
  13905. Camera.prototype._updateFromScene = function () {
  13906. this.updateCache();
  13907. this.update();
  13908. };
  13909. // Synchronized
  13910. Camera.prototype._isSynchronized = function () {
  13911. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13912. };
  13913. Camera.prototype._isSynchronizedViewMatrix = function () {
  13914. if (!_super.prototype._isSynchronized.call(this))
  13915. return false;
  13916. return this._cache.position.equals(this.position)
  13917. && this._cache.upVector.equals(this.upVector)
  13918. && this.isSynchronizedWithParent();
  13919. };
  13920. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13921. var check = this._cache.mode === this.mode
  13922. && this._cache.minZ === this.minZ
  13923. && this._cache.maxZ === this.maxZ;
  13924. if (!check) {
  13925. return false;
  13926. }
  13927. var engine = this.getEngine();
  13928. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13929. check = this._cache.fov === this.fov
  13930. && this._cache.fovMode === this.fovMode
  13931. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13932. }
  13933. else {
  13934. check = this._cache.orthoLeft === this.orthoLeft
  13935. && this._cache.orthoRight === this.orthoRight
  13936. && this._cache.orthoBottom === this.orthoBottom
  13937. && this._cache.orthoTop === this.orthoTop
  13938. && this._cache.renderWidth === engine.getRenderWidth()
  13939. && this._cache.renderHeight === engine.getRenderHeight();
  13940. }
  13941. return check;
  13942. };
  13943. // Controls
  13944. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13945. };
  13946. Camera.prototype.detachControl = function (element) {
  13947. };
  13948. Camera.prototype.update = function () {
  13949. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13950. this._updateRigCameras();
  13951. }
  13952. this._checkInputs();
  13953. };
  13954. Camera.prototype._checkInputs = function () {
  13955. };
  13956. Object.defineProperty(Camera.prototype, "rigCameras", {
  13957. get: function () {
  13958. return this._rigCameras;
  13959. },
  13960. enumerable: true,
  13961. configurable: true
  13962. });
  13963. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  13964. get: function () {
  13965. return this._rigPostProcess;
  13966. },
  13967. enumerable: true,
  13968. configurable: true
  13969. });
  13970. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13971. // invalidate framebuffer
  13972. if (this._postProcesses.length > 0) {
  13973. this._postProcesses[0].markTextureDirty();
  13974. }
  13975. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13976. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13977. var cam = this._rigCameras[i];
  13978. var rigPostProcess = cam._rigPostProcess;
  13979. // for VR rig, there does not have to be a post process
  13980. if (rigPostProcess) {
  13981. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13982. if (isPass) {
  13983. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13984. cam.isIntermediate = this._postProcesses.length === 0;
  13985. }
  13986. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13987. rigPostProcess.markTextureDirty();
  13988. }
  13989. else {
  13990. cam._postProcesses = this._postProcesses.slice(0);
  13991. }
  13992. }
  13993. };
  13994. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13995. if (insertAt === void 0) { insertAt = null; }
  13996. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13997. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13998. return 0;
  13999. }
  14000. if (insertAt == null || insertAt < 0) {
  14001. this._postProcesses.push(postProcess);
  14002. }
  14003. else {
  14004. this._postProcesses.splice(insertAt, 0, postProcess);
  14005. }
  14006. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14007. return this._postProcesses.indexOf(postProcess);
  14008. };
  14009. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14010. if (atIndices === void 0) { atIndices = null; }
  14011. var result = [];
  14012. var i;
  14013. var index;
  14014. if (!atIndices) {
  14015. var idx = this._postProcesses.indexOf(postProcess);
  14016. if (idx !== -1) {
  14017. this._postProcesses.splice(idx, 1);
  14018. }
  14019. }
  14020. else {
  14021. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14022. // iterate descending, so can just splice as we go
  14023. for (i = atIndices.length - 1; i >= 0; i--) {
  14024. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14025. result.push(i);
  14026. continue;
  14027. }
  14028. index = atIndices[i];
  14029. this._postProcesses.splice(index, 1);
  14030. }
  14031. }
  14032. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14033. return result;
  14034. };
  14035. Camera.prototype.getWorldMatrix = function () {
  14036. if (!this._worldMatrix) {
  14037. this._worldMatrix = BABYLON.Matrix.Identity();
  14038. }
  14039. var viewMatrix = this.getViewMatrix();
  14040. viewMatrix.invertToRef(this._worldMatrix);
  14041. return this._worldMatrix;
  14042. };
  14043. Camera.prototype._getViewMatrix = function () {
  14044. return BABYLON.Matrix.Identity();
  14045. };
  14046. Camera.prototype.getViewMatrix = function (force) {
  14047. this._computedViewMatrix = this._computeViewMatrix(force);
  14048. if (!force && this._isSynchronizedViewMatrix()) {
  14049. return this._computedViewMatrix;
  14050. }
  14051. this._refreshFrustumPlanes = true;
  14052. if (!this.parent || !this.parent.getWorldMatrix) {
  14053. this._globalPosition.copyFrom(this.position);
  14054. }
  14055. else {
  14056. if (!this._worldMatrix) {
  14057. this._worldMatrix = BABYLON.Matrix.Identity();
  14058. }
  14059. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14060. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14061. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14062. this._computedViewMatrix.invert();
  14063. this._markSyncedWithParent();
  14064. }
  14065. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14066. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14067. }
  14068. this._currentRenderId = this.getScene().getRenderId();
  14069. return this._computedViewMatrix;
  14070. };
  14071. Camera.prototype._computeViewMatrix = function (force) {
  14072. if (!force && this._isSynchronizedViewMatrix()) {
  14073. return this._computedViewMatrix;
  14074. }
  14075. this._computedViewMatrix = this._getViewMatrix();
  14076. this._currentRenderId = this.getScene().getRenderId();
  14077. return this._computedViewMatrix;
  14078. };
  14079. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14080. this._doNotComputeProjectionMatrix = true;
  14081. if (projection !== undefined) {
  14082. this._projectionMatrix = projection;
  14083. }
  14084. };
  14085. ;
  14086. Camera.prototype.unfreezeProjectionMatrix = function () {
  14087. this._doNotComputeProjectionMatrix = false;
  14088. };
  14089. ;
  14090. Camera.prototype.getProjectionMatrix = function (force) {
  14091. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14092. return this._projectionMatrix;
  14093. }
  14094. this._refreshFrustumPlanes = true;
  14095. var engine = this.getEngine();
  14096. var scene = this.getScene();
  14097. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14098. if (this.minZ <= 0) {
  14099. this.minZ = 0.1;
  14100. }
  14101. if (scene.useRightHandedSystem) {
  14102. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14103. }
  14104. else {
  14105. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14106. }
  14107. return this._projectionMatrix;
  14108. }
  14109. var halfWidth = engine.getRenderWidth() / 2.0;
  14110. var halfHeight = engine.getRenderHeight() / 2.0;
  14111. if (scene.useRightHandedSystem) {
  14112. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14113. }
  14114. else {
  14115. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14116. }
  14117. return this._projectionMatrix;
  14118. };
  14119. Camera.prototype.getTranformationMatrix = function () {
  14120. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14121. return this._transformMatrix;
  14122. };
  14123. Camera.prototype.updateFrustumPlanes = function () {
  14124. if (!this._refreshFrustumPlanes) {
  14125. return;
  14126. }
  14127. this.getTranformationMatrix();
  14128. if (!this._frustumPlanes) {
  14129. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14130. }
  14131. else {
  14132. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14133. }
  14134. this._refreshFrustumPlanes = false;
  14135. };
  14136. Camera.prototype.isInFrustum = function (target) {
  14137. this.updateFrustumPlanes();
  14138. return target.isInFrustum(this._frustumPlanes);
  14139. };
  14140. Camera.prototype.isCompletelyInFrustum = function (target) {
  14141. this.updateFrustumPlanes();
  14142. return target.isCompletelyInFrustum(this._frustumPlanes);
  14143. };
  14144. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14145. if (length === void 0) { length = 100; }
  14146. if (!transform) {
  14147. transform = this.getWorldMatrix();
  14148. }
  14149. if (!origin) {
  14150. origin = this.position;
  14151. }
  14152. var forward = new BABYLON.Vector3(0, 0, 1);
  14153. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14154. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14155. return new BABYLON.Ray(origin, direction, length);
  14156. };
  14157. Camera.prototype.dispose = function () {
  14158. // Animations
  14159. this.getScene().stopAnimation(this);
  14160. // Remove from scene
  14161. this.getScene().removeCamera(this);
  14162. while (this._rigCameras.length > 0) {
  14163. this._rigCameras.pop().dispose();
  14164. }
  14165. // Postprocesses
  14166. var i = this._postProcesses.length;
  14167. while (--i >= 0) {
  14168. this._postProcesses[i].dispose(this);
  14169. }
  14170. _super.prototype.dispose.call(this);
  14171. };
  14172. Object.defineProperty(Camera.prototype, "leftCamera", {
  14173. // ---- Camera rigs section ----
  14174. get: function () {
  14175. if (this._rigCameras.length < 1) {
  14176. return undefined;
  14177. }
  14178. return this._rigCameras[0];
  14179. },
  14180. enumerable: true,
  14181. configurable: true
  14182. });
  14183. Object.defineProperty(Camera.prototype, "rightCamera", {
  14184. get: function () {
  14185. if (this._rigCameras.length < 2) {
  14186. return undefined;
  14187. }
  14188. return this._rigCameras[1];
  14189. },
  14190. enumerable: true,
  14191. configurable: true
  14192. });
  14193. Camera.prototype.getLeftTarget = function () {
  14194. if (this._rigCameras.length < 1) {
  14195. return undefined;
  14196. }
  14197. return this._rigCameras[0].getTarget();
  14198. };
  14199. Camera.prototype.getRightTarget = function () {
  14200. if (this._rigCameras.length < 2) {
  14201. return undefined;
  14202. }
  14203. return this._rigCameras[1].getTarget();
  14204. };
  14205. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14206. while (this._rigCameras.length > 0) {
  14207. this._rigCameras.pop().dispose();
  14208. }
  14209. this.cameraRigMode = mode;
  14210. this._cameraRigParams = {};
  14211. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14212. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14213. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14214. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14215. // create the rig cameras, unless none
  14216. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14217. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14218. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14219. }
  14220. switch (this.cameraRigMode) {
  14221. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14222. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14223. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14224. break;
  14225. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14226. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14227. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14228. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14229. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14230. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14231. break;
  14232. case Camera.RIG_MODE_VR:
  14233. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14234. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14235. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14236. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14237. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14238. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14239. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14240. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14241. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14242. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14243. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14244. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14245. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14246. if (metrics.compensateDistortion) {
  14247. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14248. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14249. }
  14250. break;
  14251. case Camera.RIG_MODE_WEBVR:
  14252. if (rigParams.vrDisplay) {
  14253. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14254. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14255. //Left eye
  14256. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14257. this._rigCameras[0].setCameraRigParameter("left", true);
  14258. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14259. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14260. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14261. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14262. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14263. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14264. this._rigCameras[0].parent = this;
  14265. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14266. //Right eye
  14267. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14268. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14269. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14270. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14271. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14272. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14273. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14274. this._rigCameras[1].parent = this;
  14275. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14276. }
  14277. break;
  14278. }
  14279. this._cascadePostProcessesToRigCams();
  14280. this.
  14281. update();
  14282. };
  14283. Camera.prototype._getVRProjectionMatrix = function () {
  14284. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14285. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14286. return this._projectionMatrix;
  14287. };
  14288. Camera.prototype._updateCameraRotationMatrix = function () {
  14289. //Here for WebVR
  14290. };
  14291. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14292. //Here for WebVR
  14293. };
  14294. /**
  14295. * This function MUST be overwritten by the different WebVR cameras available.
  14296. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14297. */
  14298. Camera.prototype._getWebVRProjectionMatrix = function () {
  14299. return BABYLON.Matrix.Identity();
  14300. };
  14301. /**
  14302. * This function MUST be overwritten by the different WebVR cameras available.
  14303. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14304. */
  14305. Camera.prototype._getWebVRViewMatrix = function () {
  14306. return BABYLON.Matrix.Identity();
  14307. };
  14308. Camera.prototype.setCameraRigParameter = function (name, value) {
  14309. if (!this._cameraRigParams) {
  14310. this._cameraRigParams = {};
  14311. }
  14312. this._cameraRigParams[name] = value;
  14313. //provisionnally:
  14314. if (name === "interaxialDistance") {
  14315. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14316. }
  14317. };
  14318. /**
  14319. * needs to be overridden by children so sub has required properties to be copied
  14320. */
  14321. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14322. return null;
  14323. };
  14324. /**
  14325. * May need to be overridden by children
  14326. */
  14327. Camera.prototype._updateRigCameras = function () {
  14328. for (var i = 0; i < this._rigCameras.length; i++) {
  14329. this._rigCameras[i].minZ = this.minZ;
  14330. this._rigCameras[i].maxZ = this.maxZ;
  14331. this._rigCameras[i].fov = this.fov;
  14332. }
  14333. // only update viewport when ANAGLYPH
  14334. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14335. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14336. }
  14337. };
  14338. Camera.prototype._setupInputs = function () {
  14339. };
  14340. Camera.prototype.serialize = function () {
  14341. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14342. // Type
  14343. serializationObject.type = this.getClassName();
  14344. // Parent
  14345. if (this.parent) {
  14346. serializationObject.parentId = this.parent.id;
  14347. }
  14348. if (this.inputs) {
  14349. this.inputs.serialize(serializationObject);
  14350. }
  14351. // Animations
  14352. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14353. serializationObject.ranges = this.serializeAnimationRanges();
  14354. return serializationObject;
  14355. };
  14356. Camera.prototype.clone = function (name) {
  14357. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14358. };
  14359. Camera.prototype.getDirection = function (localAxis) {
  14360. var result = BABYLON.Vector3.Zero();
  14361. this.getDirectionToRef(localAxis, result);
  14362. return result;
  14363. };
  14364. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14365. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14366. };
  14367. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14368. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14369. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14370. switch (type) {
  14371. case "ArcRotateCamera":
  14372. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14373. case "DeviceOrientationCamera":
  14374. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14375. case "FollowCamera":
  14376. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14377. case "ArcFollowCamera":
  14378. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14379. case "GamepadCamera":
  14380. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14381. case "TouchCamera":
  14382. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14383. case "VirtualJoysticksCamera":
  14384. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14385. case "WebVRFreeCamera":
  14386. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14387. case "WebVRGamepadCamera":
  14388. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14389. case "VRDeviceOrientationFreeCamera":
  14390. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14391. case "VRDeviceOrientationGamepadCamera":
  14392. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14393. case "AnaglyphArcRotateCamera":
  14394. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14395. case "AnaglyphFreeCamera":
  14396. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14397. case "AnaglyphGamepadCamera":
  14398. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14399. case "AnaglyphUniversalCamera":
  14400. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14401. case "StereoscopicArcRotateCamera":
  14402. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14403. case "StereoscopicFreeCamera":
  14404. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14405. case "StereoscopicGamepadCamera":
  14406. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14407. case "StereoscopicUniversalCamera":
  14408. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14409. case "FreeCamera":
  14410. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14411. default:
  14412. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14413. }
  14414. };
  14415. Camera.Parse = function (parsedCamera, scene) {
  14416. var type = parsedCamera.type;
  14417. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14418. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14419. // Parent
  14420. if (parsedCamera.parentId) {
  14421. camera._waitingParentId = parsedCamera.parentId;
  14422. }
  14423. //If camera has an input manager, let it parse inputs settings
  14424. if (camera.inputs) {
  14425. camera.inputs.parse(parsedCamera);
  14426. camera._setupInputs();
  14427. }
  14428. // Target
  14429. if (parsedCamera.target) {
  14430. if (camera.setTarget) {
  14431. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14432. }
  14433. }
  14434. // Apply 3d rig, when found
  14435. if (parsedCamera.cameraRigMode) {
  14436. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14437. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14438. }
  14439. // Animations
  14440. if (parsedCamera.animations) {
  14441. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14442. var parsedAnimation = parsedCamera.animations[animationIndex];
  14443. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14444. }
  14445. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14446. }
  14447. if (parsedCamera.autoAnimate) {
  14448. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14449. }
  14450. return camera;
  14451. };
  14452. return Camera;
  14453. }(BABYLON.Node));
  14454. // Statics
  14455. Camera._PERSPECTIVE_CAMERA = 0;
  14456. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14457. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14458. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14459. Camera._RIG_MODE_NONE = 0;
  14460. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14461. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14462. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14463. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14464. Camera._RIG_MODE_VR = 20;
  14465. Camera._RIG_MODE_WEBVR = 21;
  14466. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14467. __decorate([
  14468. BABYLON.serializeAsVector3()
  14469. ], Camera.prototype, "position", void 0);
  14470. __decorate([
  14471. BABYLON.serializeAsVector3()
  14472. ], Camera.prototype, "upVector", void 0);
  14473. __decorate([
  14474. BABYLON.serialize()
  14475. ], Camera.prototype, "orthoLeft", void 0);
  14476. __decorate([
  14477. BABYLON.serialize()
  14478. ], Camera.prototype, "orthoRight", void 0);
  14479. __decorate([
  14480. BABYLON.serialize()
  14481. ], Camera.prototype, "orthoBottom", void 0);
  14482. __decorate([
  14483. BABYLON.serialize()
  14484. ], Camera.prototype, "orthoTop", void 0);
  14485. __decorate([
  14486. BABYLON.serialize()
  14487. ], Camera.prototype, "fov", void 0);
  14488. __decorate([
  14489. BABYLON.serialize()
  14490. ], Camera.prototype, "minZ", void 0);
  14491. __decorate([
  14492. BABYLON.serialize()
  14493. ], Camera.prototype, "maxZ", void 0);
  14494. __decorate([
  14495. BABYLON.serialize()
  14496. ], Camera.prototype, "inertia", void 0);
  14497. __decorate([
  14498. BABYLON.serialize()
  14499. ], Camera.prototype, "mode", void 0);
  14500. __decorate([
  14501. BABYLON.serialize()
  14502. ], Camera.prototype, "layerMask", void 0);
  14503. __decorate([
  14504. BABYLON.serialize()
  14505. ], Camera.prototype, "fovMode", void 0);
  14506. __decorate([
  14507. BABYLON.serialize()
  14508. ], Camera.prototype, "cameraRigMode", void 0);
  14509. __decorate([
  14510. BABYLON.serialize()
  14511. ], Camera.prototype, "interaxialDistance", void 0);
  14512. __decorate([
  14513. BABYLON.serialize()
  14514. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14515. BABYLON.Camera = Camera;
  14516. })(BABYLON || (BABYLON = {}));
  14517. //# sourceMappingURL=babylon.camera.js.map
  14518. var BABYLON;
  14519. (function (BABYLON) {
  14520. var RenderingManager = (function () {
  14521. function RenderingManager(scene) {
  14522. this._renderingGroups = new Array();
  14523. this._autoClearDepthStencil = {};
  14524. this._customOpaqueSortCompareFn = {};
  14525. this._customAlphaTestSortCompareFn = {};
  14526. this._customTransparentSortCompareFn = {};
  14527. this._renderinGroupInfo = null;
  14528. this._scene = scene;
  14529. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14530. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14531. }
  14532. }
  14533. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14534. if (depth === void 0) { depth = true; }
  14535. if (stencil === void 0) { stencil = true; }
  14536. if (this._depthStencilBufferAlreadyCleaned) {
  14537. return;
  14538. }
  14539. this._scene.getEngine().clear(null, false, depth, stencil);
  14540. this._depthStencilBufferAlreadyCleaned = true;
  14541. };
  14542. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14543. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14544. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14545. var info = null;
  14546. if (observable) {
  14547. if (!this._renderinGroupInfo) {
  14548. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14549. }
  14550. info = this._renderinGroupInfo;
  14551. info.scene = this._scene;
  14552. info.camera = this._scene.activeCamera;
  14553. }
  14554. // Dispatch sprites
  14555. if (renderSprites) {
  14556. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14557. var manager = this._scene.spriteManagers[index];
  14558. this.dispatchSprites(manager);
  14559. }
  14560. }
  14561. // Render
  14562. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14563. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14564. var renderingGroup = this._renderingGroups[index];
  14565. if (!renderingGroup && !observable)
  14566. continue;
  14567. this._currentIndex = index;
  14568. var renderingGroupMask = 0;
  14569. // Fire PRECLEAR stage
  14570. if (observable) {
  14571. renderingGroupMask = Math.pow(2, index);
  14572. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14573. info.renderingGroupId = index;
  14574. observable.notifyObservers(info, renderingGroupMask);
  14575. }
  14576. // Clear depth/stencil if needed
  14577. if (RenderingManager.AUTOCLEAR) {
  14578. var autoClear = this._autoClearDepthStencil[index];
  14579. if (autoClear && autoClear.autoClear) {
  14580. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14581. }
  14582. }
  14583. if (observable) {
  14584. // Fire PREOPAQUE stage
  14585. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14586. observable.notifyObservers(info, renderingGroupMask);
  14587. // Fire PRETRANSPARENT stage
  14588. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14589. observable.notifyObservers(info, renderingGroupMask);
  14590. }
  14591. if (renderingGroup)
  14592. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14593. // Fire POSTTRANSPARENT stage
  14594. if (observable) {
  14595. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14596. observable.notifyObservers(info, renderingGroupMask);
  14597. }
  14598. }
  14599. };
  14600. RenderingManager.prototype.reset = function () {
  14601. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14602. var renderingGroup = this._renderingGroups[index];
  14603. if (renderingGroup) {
  14604. renderingGroup.prepare();
  14605. }
  14606. }
  14607. };
  14608. RenderingManager.prototype.dispose = function () {
  14609. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14610. var renderingGroup = this._renderingGroups[index];
  14611. if (renderingGroup) {
  14612. renderingGroup.dispose();
  14613. }
  14614. }
  14615. this._renderingGroups.length = 0;
  14616. };
  14617. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14618. if (!this._renderingGroups[renderingGroupId]) {
  14619. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14620. }
  14621. };
  14622. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14623. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14624. this._prepareRenderingGroup(renderingGroupId);
  14625. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14626. };
  14627. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14628. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14629. this._prepareRenderingGroup(renderingGroupId);
  14630. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14631. };
  14632. RenderingManager.prototype.dispatch = function (subMesh) {
  14633. var mesh = subMesh.getMesh();
  14634. var renderingGroupId = mesh.renderingGroupId || 0;
  14635. this._prepareRenderingGroup(renderingGroupId);
  14636. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14637. };
  14638. /**
  14639. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14640. * This allowed control for front to back rendering or reversly depending of the special needs.
  14641. *
  14642. * @param renderingGroupId The rendering group id corresponding to its index
  14643. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14644. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14645. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14646. */
  14647. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14648. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14649. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14650. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14651. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14652. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14653. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14654. if (this._renderingGroups[renderingGroupId]) {
  14655. var group = this._renderingGroups[renderingGroupId];
  14656. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14657. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14658. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14659. }
  14660. };
  14661. /**
  14662. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14663. *
  14664. * @param renderingGroupId The rendering group id corresponding to its index
  14665. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14666. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14667. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14668. */
  14669. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14670. if (depth === void 0) { depth = true; }
  14671. if (stencil === void 0) { stencil = true; }
  14672. this._autoClearDepthStencil[renderingGroupId] = {
  14673. autoClear: autoClearDepthStencil,
  14674. depth: depth,
  14675. stencil: stencil
  14676. };
  14677. };
  14678. return RenderingManager;
  14679. }());
  14680. /**
  14681. * The max id used for rendering groups (not included)
  14682. */
  14683. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14684. /**
  14685. * The min id used for rendering groups (included)
  14686. */
  14687. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14688. /**
  14689. * Used to globally prevent autoclearing scenes.
  14690. */
  14691. RenderingManager.AUTOCLEAR = true;
  14692. BABYLON.RenderingManager = RenderingManager;
  14693. })(BABYLON || (BABYLON = {}));
  14694. //# sourceMappingURL=babylon.renderingManager.js.map
  14695. var BABYLON;
  14696. (function (BABYLON) {
  14697. var RenderingGroup = (function () {
  14698. /**
  14699. * Creates a new rendering group.
  14700. * @param index The rendering group index
  14701. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14702. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14703. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14704. */
  14705. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14706. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14707. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14708. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14709. this.index = index;
  14710. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14711. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14712. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14713. this._particleSystems = new BABYLON.SmartArray(256);
  14714. this._spriteManagers = new BABYLON.SmartArray(256);
  14715. this._edgesRenderers = new BABYLON.SmartArray(16);
  14716. this._scene = scene;
  14717. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14718. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14719. this.transparentSortCompareFn = transparentSortCompareFn;
  14720. }
  14721. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14722. /**
  14723. * Set the opaque sort comparison function.
  14724. * If null the sub meshes will be render in the order they were created
  14725. */
  14726. set: function (value) {
  14727. this._opaqueSortCompareFn = value;
  14728. if (value) {
  14729. this._renderOpaque = this.renderOpaqueSorted;
  14730. }
  14731. else {
  14732. this._renderOpaque = RenderingGroup.renderUnsorted;
  14733. }
  14734. },
  14735. enumerable: true,
  14736. configurable: true
  14737. });
  14738. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14739. /**
  14740. * Set the alpha test sort comparison function.
  14741. * If null the sub meshes will be render in the order they were created
  14742. */
  14743. set: function (value) {
  14744. this._alphaTestSortCompareFn = value;
  14745. if (value) {
  14746. this._renderAlphaTest = this.renderAlphaTestSorted;
  14747. }
  14748. else {
  14749. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14750. }
  14751. },
  14752. enumerable: true,
  14753. configurable: true
  14754. });
  14755. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14756. /**
  14757. * Set the transparent sort comparison function.
  14758. * If null the sub meshes will be render in the order they were created
  14759. */
  14760. set: function (value) {
  14761. if (value) {
  14762. this._transparentSortCompareFn = value;
  14763. }
  14764. else {
  14765. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14766. }
  14767. this._renderTransparent = this.renderTransparentSorted;
  14768. },
  14769. enumerable: true,
  14770. configurable: true
  14771. });
  14772. /**
  14773. * Render all the sub meshes contained in the group.
  14774. * @param customRenderFunction Used to override the default render behaviour of the group.
  14775. * @returns true if rendered some submeshes.
  14776. */
  14777. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14778. if (customRenderFunction) {
  14779. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14780. return;
  14781. }
  14782. var engine = this._scene.getEngine();
  14783. // Opaque
  14784. if (this._opaqueSubMeshes.length !== 0) {
  14785. this._renderOpaque(this._opaqueSubMeshes);
  14786. }
  14787. // Alpha test
  14788. if (this._alphaTestSubMeshes.length !== 0) {
  14789. engine.setAlphaTesting(true);
  14790. this._renderAlphaTest(this._alphaTestSubMeshes);
  14791. engine.setAlphaTesting(false);
  14792. }
  14793. var stencilState = engine.getStencilBuffer();
  14794. engine.setStencilBuffer(false);
  14795. // Sprites
  14796. if (renderSprites) {
  14797. this._renderSprites();
  14798. }
  14799. // Particles
  14800. if (renderParticles) {
  14801. this._renderParticles(activeMeshes);
  14802. }
  14803. if (this.onBeforeTransparentRendering) {
  14804. this.onBeforeTransparentRendering();
  14805. }
  14806. // Transparent
  14807. if (this._transparentSubMeshes.length !== 0) {
  14808. this._renderTransparent(this._transparentSubMeshes);
  14809. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14810. }
  14811. engine.setStencilBuffer(stencilState);
  14812. // Edges
  14813. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14814. this._edgesRenderers.data[edgesRendererIndex].render();
  14815. }
  14816. };
  14817. /**
  14818. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14819. * @param subMeshes The submeshes to render
  14820. */
  14821. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14822. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14823. };
  14824. /**
  14825. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14826. * @param subMeshes The submeshes to render
  14827. */
  14828. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14829. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14830. };
  14831. /**
  14832. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14833. * @param subMeshes The submeshes to render
  14834. */
  14835. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14836. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14837. };
  14838. /**
  14839. * Renders the submeshes in a specified order.
  14840. * @param subMeshes The submeshes to sort before render
  14841. * @param sortCompareFn The comparison function use to sort
  14842. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14843. * @param transparent Specifies to activate blending if true
  14844. */
  14845. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14846. var subIndex = 0;
  14847. var subMesh;
  14848. for (; subIndex < subMeshes.length; subIndex++) {
  14849. subMesh = subMeshes.data[subIndex];
  14850. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14851. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14852. }
  14853. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14854. sortedArray.sort(sortCompareFn);
  14855. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14856. subMesh = sortedArray[subIndex];
  14857. subMesh.render(transparent);
  14858. }
  14859. };
  14860. /**
  14861. * Renders the submeshes in the order they were dispatched (no sort applied).
  14862. * @param subMeshes The submeshes to render
  14863. */
  14864. RenderingGroup.renderUnsorted = function (subMeshes) {
  14865. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14866. var submesh = subMeshes.data[subIndex];
  14867. submesh.render(false);
  14868. }
  14869. };
  14870. /**
  14871. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14872. * are rendered back to front if in the same alpha index.
  14873. *
  14874. * @param a The first submesh
  14875. * @param b The second submesh
  14876. * @returns The result of the comparison
  14877. */
  14878. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14879. // Alpha index first
  14880. if (a._alphaIndex > b._alphaIndex) {
  14881. return 1;
  14882. }
  14883. if (a._alphaIndex < b._alphaIndex) {
  14884. return -1;
  14885. }
  14886. // Then distance to camera
  14887. return RenderingGroup.backToFrontSortCompare(a, b);
  14888. };
  14889. /**
  14890. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14891. * are rendered back to front.
  14892. *
  14893. * @param a The first submesh
  14894. * @param b The second submesh
  14895. * @returns The result of the comparison
  14896. */
  14897. RenderingGroup.backToFrontSortCompare = function (a, b) {
  14898. // Then distance to camera
  14899. if (a._distanceToCamera < b._distanceToCamera) {
  14900. return 1;
  14901. }
  14902. if (a._distanceToCamera > b._distanceToCamera) {
  14903. return -1;
  14904. }
  14905. return 0;
  14906. };
  14907. /**
  14908. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14909. * are rendered front to back (prevent overdraw).
  14910. *
  14911. * @param a The first submesh
  14912. * @param b The second submesh
  14913. * @returns The result of the comparison
  14914. */
  14915. RenderingGroup.frontToBackSortCompare = function (a, b) {
  14916. // Then distance to camera
  14917. if (a._distanceToCamera < b._distanceToCamera) {
  14918. return -1;
  14919. }
  14920. if (a._distanceToCamera > b._distanceToCamera) {
  14921. return 1;
  14922. }
  14923. return 0;
  14924. };
  14925. /**
  14926. * Resets the different lists of submeshes to prepare a new frame.
  14927. */
  14928. RenderingGroup.prototype.prepare = function () {
  14929. this._opaqueSubMeshes.reset();
  14930. this._transparentSubMeshes.reset();
  14931. this._alphaTestSubMeshes.reset();
  14932. this._particleSystems.reset();
  14933. this._spriteManagers.reset();
  14934. this._edgesRenderers.reset();
  14935. };
  14936. RenderingGroup.prototype.dispose = function () {
  14937. this._opaqueSubMeshes.dispose();
  14938. this._transparentSubMeshes.dispose();
  14939. this._alphaTestSubMeshes.dispose();
  14940. this._particleSystems.dispose();
  14941. this._spriteManagers.dispose();
  14942. this._edgesRenderers.dispose();
  14943. };
  14944. /**
  14945. * Inserts the submesh in its correct queue depending on its material.
  14946. * @param subMesh The submesh to dispatch
  14947. */
  14948. RenderingGroup.prototype.dispatch = function (subMesh) {
  14949. var material = subMesh.getMaterial();
  14950. var mesh = subMesh.getMesh();
  14951. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14952. this._transparentSubMeshes.push(subMesh);
  14953. }
  14954. else if (material.needAlphaTesting()) {
  14955. this._alphaTestSubMeshes.push(subMesh);
  14956. }
  14957. else {
  14958. this._opaqueSubMeshes.push(subMesh); // Opaque
  14959. }
  14960. if (mesh._edgesRenderer) {
  14961. this._edgesRenderers.push(mesh._edgesRenderer);
  14962. }
  14963. };
  14964. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  14965. this._spriteManagers.push(spriteManager);
  14966. };
  14967. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  14968. this._particleSystems.push(particleSystem);
  14969. };
  14970. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  14971. if (this._particleSystems.length === 0) {
  14972. return;
  14973. }
  14974. // Particles
  14975. var activeCamera = this._scene.activeCamera;
  14976. this._scene._particlesDuration.beginMonitoring();
  14977. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14978. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14979. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14980. continue;
  14981. }
  14982. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14983. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14984. }
  14985. }
  14986. this._scene._particlesDuration.endMonitoring(false);
  14987. };
  14988. RenderingGroup.prototype._renderSprites = function () {
  14989. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  14990. return;
  14991. }
  14992. // Sprites
  14993. var activeCamera = this._scene.activeCamera;
  14994. this._scene._spritesDuration.beginMonitoring();
  14995. for (var id = 0; id < this._spriteManagers.length; id++) {
  14996. var spriteManager = this._spriteManagers.data[id];
  14997. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14998. spriteManager.render();
  14999. }
  15000. }
  15001. this._scene._spritesDuration.endMonitoring(false);
  15002. };
  15003. return RenderingGroup;
  15004. }());
  15005. BABYLON.RenderingGroup = RenderingGroup;
  15006. })(BABYLON || (BABYLON = {}));
  15007. //# sourceMappingURL=babylon.renderingGroup.js.map
  15008. var BABYLON;
  15009. (function (BABYLON) {
  15010. var ClickInfo = (function () {
  15011. function ClickInfo() {
  15012. this._singleClick = false;
  15013. this._doubleClick = false;
  15014. this._hasSwiped = false;
  15015. this._ignore = false;
  15016. }
  15017. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15018. get: function () {
  15019. return this._singleClick;
  15020. },
  15021. set: function (b) {
  15022. this._singleClick = b;
  15023. },
  15024. enumerable: true,
  15025. configurable: true
  15026. });
  15027. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15028. get: function () {
  15029. return this._doubleClick;
  15030. },
  15031. set: function (b) {
  15032. this._doubleClick = b;
  15033. },
  15034. enumerable: true,
  15035. configurable: true
  15036. });
  15037. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15038. get: function () {
  15039. return this._hasSwiped;
  15040. },
  15041. set: function (b) {
  15042. this._hasSwiped = b;
  15043. },
  15044. enumerable: true,
  15045. configurable: true
  15046. });
  15047. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15048. get: function () {
  15049. return this._ignore;
  15050. },
  15051. set: function (b) {
  15052. this._ignore = b;
  15053. },
  15054. enumerable: true,
  15055. configurable: true
  15056. });
  15057. return ClickInfo;
  15058. }());
  15059. var PointerEventTypes = (function () {
  15060. function PointerEventTypes() {
  15061. }
  15062. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15063. get: function () {
  15064. return PointerEventTypes._POINTERDOWN;
  15065. },
  15066. enumerable: true,
  15067. configurable: true
  15068. });
  15069. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15070. get: function () {
  15071. return PointerEventTypes._POINTERUP;
  15072. },
  15073. enumerable: true,
  15074. configurable: true
  15075. });
  15076. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15077. get: function () {
  15078. return PointerEventTypes._POINTERMOVE;
  15079. },
  15080. enumerable: true,
  15081. configurable: true
  15082. });
  15083. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15084. get: function () {
  15085. return PointerEventTypes._POINTERWHEEL;
  15086. },
  15087. enumerable: true,
  15088. configurable: true
  15089. });
  15090. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15091. get: function () {
  15092. return PointerEventTypes._POINTERPICK;
  15093. },
  15094. enumerable: true,
  15095. configurable: true
  15096. });
  15097. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15098. get: function () {
  15099. return PointerEventTypes._POINTERTAP;
  15100. },
  15101. enumerable: true,
  15102. configurable: true
  15103. });
  15104. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15105. get: function () {
  15106. return PointerEventTypes._POINTERDOUBLETAP;
  15107. },
  15108. enumerable: true,
  15109. configurable: true
  15110. });
  15111. return PointerEventTypes;
  15112. }());
  15113. PointerEventTypes._POINTERDOWN = 0x01;
  15114. PointerEventTypes._POINTERUP = 0x02;
  15115. PointerEventTypes._POINTERMOVE = 0x04;
  15116. PointerEventTypes._POINTERWHEEL = 0x08;
  15117. PointerEventTypes._POINTERPICK = 0x10;
  15118. PointerEventTypes._POINTERTAP = 0x20;
  15119. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15120. BABYLON.PointerEventTypes = PointerEventTypes;
  15121. var PointerInfoBase = (function () {
  15122. function PointerInfoBase(type, event) {
  15123. this.type = type;
  15124. this.event = event;
  15125. }
  15126. return PointerInfoBase;
  15127. }());
  15128. BABYLON.PointerInfoBase = PointerInfoBase;
  15129. /**
  15130. * This class is used to store pointer related info for the onPrePointerObservable event.
  15131. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15132. */
  15133. var PointerInfoPre = (function (_super) {
  15134. __extends(PointerInfoPre, _super);
  15135. function PointerInfoPre(type, event, localX, localY) {
  15136. var _this = _super.call(this, type, event) || this;
  15137. _this.skipOnPointerObservable = false;
  15138. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15139. return _this;
  15140. }
  15141. return PointerInfoPre;
  15142. }(PointerInfoBase));
  15143. BABYLON.PointerInfoPre = PointerInfoPre;
  15144. /**
  15145. * This type contains all the data related to a pointer event in Babylon.js.
  15146. * 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.
  15147. */
  15148. var PointerInfo = (function (_super) {
  15149. __extends(PointerInfo, _super);
  15150. function PointerInfo(type, event, pickInfo) {
  15151. var _this = _super.call(this, type, event) || this;
  15152. _this.pickInfo = pickInfo;
  15153. return _this;
  15154. }
  15155. return PointerInfo;
  15156. }(PointerInfoBase));
  15157. BABYLON.PointerInfo = PointerInfo;
  15158. /**
  15159. * This class is used by the onRenderingGroupObservable
  15160. */
  15161. var RenderingGroupInfo = (function () {
  15162. function RenderingGroupInfo() {
  15163. }
  15164. return RenderingGroupInfo;
  15165. }());
  15166. /**
  15167. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15168. * This stage will be fired no matter what
  15169. */
  15170. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15171. /**
  15172. * Called before opaque object are rendered.
  15173. * This stage will be fired only if there's 3D Opaque content to render
  15174. */
  15175. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15176. /**
  15177. * Called after the opaque objects are rendered and before the transparent ones
  15178. * This stage will be fired only if there's 3D transparent content to render
  15179. */
  15180. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15181. /**
  15182. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15183. * This stage will be fired no matter what
  15184. */
  15185. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15186. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15187. /**
  15188. * Represents a scene to be rendered by the engine.
  15189. * @see http://doc.babylonjs.com/page.php?p=21911
  15190. */
  15191. var Scene = (function () {
  15192. /**
  15193. * @constructor
  15194. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15195. */
  15196. function Scene(engine) {
  15197. // Members
  15198. this.autoClear = true;
  15199. this.autoClearDepthAndStencil = true;
  15200. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15201. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15202. this.forceWireframe = false;
  15203. this._forcePointsCloud = false;
  15204. this.forceShowBoundingBoxes = false;
  15205. this.animationsEnabled = true;
  15206. this.constantlyUpdateMeshUnderPointer = false;
  15207. this.hoverCursor = "pointer";
  15208. // Metadata
  15209. this.metadata = null;
  15210. // Events
  15211. /**
  15212. * An event triggered when the scene is disposed.
  15213. * @type {BABYLON.Observable}
  15214. */
  15215. this.onDisposeObservable = new BABYLON.Observable();
  15216. /**
  15217. * An event triggered before rendering the scene
  15218. * @type {BABYLON.Observable}
  15219. */
  15220. this.onBeforeRenderObservable = new BABYLON.Observable();
  15221. /**
  15222. * An event triggered after rendering the scene
  15223. * @type {BABYLON.Observable}
  15224. */
  15225. this.onAfterRenderObservable = new BABYLON.Observable();
  15226. /**
  15227. * An event triggered when the scene is ready
  15228. * @type {BABYLON.Observable}
  15229. */
  15230. this.onReadyObservable = new BABYLON.Observable();
  15231. /**
  15232. * An event triggered before rendering a camera
  15233. * @type {BABYLON.Observable}
  15234. */
  15235. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15236. /**
  15237. * An event triggered after rendering a camera
  15238. * @type {BABYLON.Observable}
  15239. */
  15240. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15241. /**
  15242. * An event triggered when a camera is created
  15243. * @type {BABYLON.Observable}
  15244. */
  15245. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15246. /**
  15247. * An event triggered when a camera is removed
  15248. * @type {BABYLON.Observable}
  15249. */
  15250. this.onCameraRemovedObservable = new BABYLON.Observable();
  15251. /**
  15252. * An event triggered when a light is created
  15253. * @type {BABYLON.Observable}
  15254. */
  15255. this.onNewLightAddedObservable = new BABYLON.Observable();
  15256. /**
  15257. * An event triggered when a light is removed
  15258. * @type {BABYLON.Observable}
  15259. */
  15260. this.onLightRemovedObservable = new BABYLON.Observable();
  15261. /**
  15262. * An event triggered when a geometry is created
  15263. * @type {BABYLON.Observable}
  15264. */
  15265. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15266. /**
  15267. * An event triggered when a geometry is removed
  15268. * @type {BABYLON.Observable}
  15269. */
  15270. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15271. /**
  15272. * An event triggered when a mesh is created
  15273. * @type {BABYLON.Observable}
  15274. */
  15275. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15276. /**
  15277. * An event triggered when a mesh is removed
  15278. * @type {BABYLON.Observable}
  15279. */
  15280. this.onMeshRemovedObservable = new BABYLON.Observable();
  15281. /**
  15282. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15283. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15284. * 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)
  15285. */
  15286. this.onRenderingGroupObservable = new BABYLON.Observable();
  15287. // Animations
  15288. this.animations = [];
  15289. /**
  15290. * 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).
  15291. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15292. */
  15293. this.onPrePointerObservable = new BABYLON.Observable();
  15294. /**
  15295. * Observable event triggered each time an input event is received from the rendering canvas
  15296. */
  15297. this.onPointerObservable = new BABYLON.Observable();
  15298. this._meshPickProceed = false;
  15299. this._previousHasSwiped = false;
  15300. this._currentPickResult = null;
  15301. this._previousPickResult = null;
  15302. this._isButtonPressed = false;
  15303. this._doubleClickOccured = false;
  15304. 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
  15305. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15306. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15307. this._startingPointerTime = 0;
  15308. this._previousStartingPointerTime = 0;
  15309. // Coordinate system
  15310. /**
  15311. * use right-handed coordinate system on this scene.
  15312. * @type {boolean}
  15313. */
  15314. this._useRightHandedSystem = false;
  15315. // Fog
  15316. /**
  15317. * is fog enabled on this scene.
  15318. * @type {boolean}
  15319. */
  15320. this._fogEnabled = true;
  15321. this._fogMode = Scene.FOGMODE_NONE;
  15322. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15323. this.fogDensity = 0.1;
  15324. this.fogStart = 0;
  15325. this.fogEnd = 1000.0;
  15326. // Lights
  15327. /**
  15328. * is shadow enabled on this scene.
  15329. * @type {boolean}
  15330. */
  15331. this._shadowsEnabled = true;
  15332. /**
  15333. * is light enabled on this scene.
  15334. * @type {boolean}
  15335. */
  15336. this._lightsEnabled = true;
  15337. /**
  15338. * All of the lights added to this scene.
  15339. * @see BABYLON.Light
  15340. * @type {BABYLON.Light[]}
  15341. */
  15342. this.lights = new Array();
  15343. // Cameras
  15344. /**
  15345. * All of the cameras added to this scene.
  15346. * @see BABYLON.Camera
  15347. * @type {BABYLON.Camera[]}
  15348. */
  15349. this.cameras = new Array();
  15350. this.activeCameras = new Array();
  15351. // Meshes
  15352. /**
  15353. * All of the (abstract) meshes added to this scene.
  15354. * @see BABYLON.AbstractMesh
  15355. * @type {BABYLON.AbstractMesh[]}
  15356. */
  15357. this.meshes = new Array();
  15358. // Geometries
  15359. this._geometries = new Array();
  15360. this.materials = new Array();
  15361. this.multiMaterials = new Array();
  15362. // Textures
  15363. this._texturesEnabled = true;
  15364. this.textures = new Array();
  15365. // Particles
  15366. this.particlesEnabled = true;
  15367. this.particleSystems = new Array();
  15368. // Sprites
  15369. this.spritesEnabled = true;
  15370. this.spriteManagers = new Array();
  15371. // Layers
  15372. this.layers = new Array();
  15373. this.highlightLayers = new Array();
  15374. // Skeletons
  15375. this._skeletonsEnabled = true;
  15376. this.skeletons = new Array();
  15377. // Morph targets
  15378. this.morphTargetManagers = new Array();
  15379. // Lens flares
  15380. this.lensFlaresEnabled = true;
  15381. this.lensFlareSystems = new Array();
  15382. // Collisions
  15383. this.collisionsEnabled = true;
  15384. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15385. // Postprocesses
  15386. this.postProcessesEnabled = true;
  15387. // Customs render targets
  15388. this.renderTargetsEnabled = true;
  15389. this.dumpNextRenderTargets = false;
  15390. this.customRenderTargets = new Array();
  15391. // Imported meshes
  15392. this.importedMeshesFiles = new Array();
  15393. // Probes
  15394. this.probesEnabled = true;
  15395. this.reflectionProbes = new Array();
  15396. this._actionManagers = new Array();
  15397. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15398. // Procedural textures
  15399. this.proceduralTexturesEnabled = true;
  15400. this._proceduralTextures = new Array();
  15401. this.soundTracks = new Array();
  15402. this._audioEnabled = true;
  15403. this._headphone = false;
  15404. // Performance counters
  15405. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15406. this._totalLightsCounter = new BABYLON.PerfCounter();
  15407. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15408. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15409. this._totalVertices = new BABYLON.PerfCounter();
  15410. this._activeIndices = new BABYLON.PerfCounter();
  15411. this._activeParticles = new BABYLON.PerfCounter();
  15412. this._lastFrameDuration = new BABYLON.PerfCounter();
  15413. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15414. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15415. this._particlesDuration = new BABYLON.PerfCounter();
  15416. this._renderDuration = new BABYLON.PerfCounter();
  15417. this._spritesDuration = new BABYLON.PerfCounter();
  15418. this._activeBones = new BABYLON.PerfCounter();
  15419. this._animationTime = 0;
  15420. this.animationTimeScale = 1;
  15421. this._renderId = 0;
  15422. this._executeWhenReadyTimeoutId = -1;
  15423. this._intermediateRendering = false;
  15424. this._viewUpdateFlag = -1;
  15425. this._projectionUpdateFlag = -1;
  15426. this._toBeDisposed = new BABYLON.SmartArray(256);
  15427. this._pendingData = []; //ANY
  15428. this._activeMeshes = new BABYLON.SmartArray(256);
  15429. this._processedMaterials = new BABYLON.SmartArray(256);
  15430. this._renderTargets = new BABYLON.SmartArray(256);
  15431. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15432. this._activeSkeletons = new BABYLON.SmartArray(32);
  15433. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15434. this._activeAnimatables = new Array();
  15435. this._transformMatrix = BABYLON.Matrix.Zero();
  15436. this.requireLightSorting = false;
  15437. this._uniqueIdCounter = 0;
  15438. this.offscreenRenderTarget = null;
  15439. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15440. this._engine.scenes.push(this);
  15441. this._uid = null;
  15442. this._renderingManager = new BABYLON.RenderingManager(this);
  15443. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15444. if (BABYLON.OutlineRenderer) {
  15445. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15446. }
  15447. this.attachControl();
  15448. if (BABYLON.SoundTrack) {
  15449. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15450. }
  15451. //simplification queue
  15452. if (BABYLON.SimplificationQueue) {
  15453. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15454. }
  15455. //collision coordinator initialization. For now legacy per default.
  15456. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15457. // Uniform Buffer
  15458. this._createUbo();
  15459. }
  15460. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15461. get: function () {
  15462. return Scene._FOGMODE_NONE;
  15463. },
  15464. enumerable: true,
  15465. configurable: true
  15466. });
  15467. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15468. get: function () {
  15469. return Scene._FOGMODE_EXP;
  15470. },
  15471. enumerable: true,
  15472. configurable: true
  15473. });
  15474. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15475. get: function () {
  15476. return Scene._FOGMODE_EXP2;
  15477. },
  15478. enumerable: true,
  15479. configurable: true
  15480. });
  15481. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15482. get: function () {
  15483. return Scene._FOGMODE_LINEAR;
  15484. },
  15485. enumerable: true,
  15486. configurable: true
  15487. });
  15488. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15489. /**
  15490. * Texture used in all pbr material as the reflection texture.
  15491. * As in the majority of the scene they are the same (exception for multi room and so on),
  15492. * this is easier to reference from here than from all the materials.
  15493. */
  15494. get: function () {
  15495. return this._environmentTexture;
  15496. },
  15497. /**
  15498. * Texture used in all pbr material as the reflection texture.
  15499. * As in the majority of the scene they are the same (exception for multi room and so on),
  15500. * this is easier to set here than in all the materials.
  15501. */
  15502. set: function (value) {
  15503. this._environmentTexture = value;
  15504. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15505. },
  15506. enumerable: true,
  15507. configurable: true
  15508. });
  15509. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15510. get: function () {
  15511. return this._forcePointsCloud;
  15512. },
  15513. set: function (value) {
  15514. if (this._forcePointsCloud === value) {
  15515. return;
  15516. }
  15517. this._forcePointsCloud = value;
  15518. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15519. },
  15520. enumerable: true,
  15521. configurable: true
  15522. });
  15523. Object.defineProperty(Scene.prototype, "onDispose", {
  15524. set: function (callback) {
  15525. if (this._onDisposeObserver) {
  15526. this.onDisposeObservable.remove(this._onDisposeObserver);
  15527. }
  15528. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15529. },
  15530. enumerable: true,
  15531. configurable: true
  15532. });
  15533. Object.defineProperty(Scene.prototype, "beforeRender", {
  15534. set: function (callback) {
  15535. if (this._onBeforeRenderObserver) {
  15536. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15537. }
  15538. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15539. },
  15540. enumerable: true,
  15541. configurable: true
  15542. });
  15543. Object.defineProperty(Scene.prototype, "afterRender", {
  15544. set: function (callback) {
  15545. if (this._onAfterRenderObserver) {
  15546. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15547. }
  15548. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15549. },
  15550. enumerable: true,
  15551. configurable: true
  15552. });
  15553. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15554. set: function (callback) {
  15555. if (this._onBeforeCameraRenderObserver) {
  15556. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15557. }
  15558. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15559. },
  15560. enumerable: true,
  15561. configurable: true
  15562. });
  15563. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15564. set: function (callback) {
  15565. if (this._onAfterCameraRenderObserver) {
  15566. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15567. }
  15568. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15569. },
  15570. enumerable: true,
  15571. configurable: true
  15572. });
  15573. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15574. get: function () {
  15575. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15576. },
  15577. enumerable: true,
  15578. configurable: true
  15579. });
  15580. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15581. get: function () {
  15582. return this._useRightHandedSystem;
  15583. },
  15584. set: function (value) {
  15585. if (this._useRightHandedSystem === value) {
  15586. return;
  15587. }
  15588. this._useRightHandedSystem = value;
  15589. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15590. },
  15591. enumerable: true,
  15592. configurable: true
  15593. });
  15594. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15595. get: function () {
  15596. return this._fogEnabled;
  15597. },
  15598. set: function (value) {
  15599. if (this._fogEnabled === value) {
  15600. return;
  15601. }
  15602. this._fogEnabled = value;
  15603. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15604. },
  15605. enumerable: true,
  15606. configurable: true
  15607. });
  15608. Object.defineProperty(Scene.prototype, "fogMode", {
  15609. get: function () {
  15610. return this._fogMode;
  15611. },
  15612. set: function (value) {
  15613. if (this._fogMode === value) {
  15614. return;
  15615. }
  15616. this._fogMode = value;
  15617. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15618. },
  15619. enumerable: true,
  15620. configurable: true
  15621. });
  15622. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15623. get: function () {
  15624. return this._shadowsEnabled;
  15625. },
  15626. set: function (value) {
  15627. if (this._shadowsEnabled === value) {
  15628. return;
  15629. }
  15630. this._shadowsEnabled = value;
  15631. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15632. },
  15633. enumerable: true,
  15634. configurable: true
  15635. });
  15636. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15637. get: function () {
  15638. return this._lightsEnabled;
  15639. },
  15640. set: function (value) {
  15641. if (this._lightsEnabled === value) {
  15642. return;
  15643. }
  15644. this._lightsEnabled = value;
  15645. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15646. },
  15647. enumerable: true,
  15648. configurable: true
  15649. });
  15650. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15651. get: function () {
  15652. if (!this._defaultMaterial) {
  15653. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15654. }
  15655. return this._defaultMaterial;
  15656. },
  15657. set: function (value) {
  15658. this._defaultMaterial = value;
  15659. },
  15660. enumerable: true,
  15661. configurable: true
  15662. });
  15663. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15664. get: function () {
  15665. return this._texturesEnabled;
  15666. },
  15667. set: function (value) {
  15668. if (this._texturesEnabled === value) {
  15669. return;
  15670. }
  15671. this._texturesEnabled = value;
  15672. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15673. },
  15674. enumerable: true,
  15675. configurable: true
  15676. });
  15677. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15678. get: function () {
  15679. return this._skeletonsEnabled;
  15680. },
  15681. set: function (value) {
  15682. if (this._skeletonsEnabled === value) {
  15683. return;
  15684. }
  15685. this._skeletonsEnabled = value;
  15686. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15687. },
  15688. enumerable: true,
  15689. configurable: true
  15690. });
  15691. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15692. get: function () {
  15693. if (!this._postProcessRenderPipelineManager) {
  15694. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15695. }
  15696. return this._postProcessRenderPipelineManager;
  15697. },
  15698. enumerable: true,
  15699. configurable: true
  15700. });
  15701. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15702. get: function () {
  15703. return this._frustumPlanes;
  15704. },
  15705. enumerable: true,
  15706. configurable: true
  15707. });
  15708. Object.defineProperty(Scene.prototype, "debugLayer", {
  15709. // Properties
  15710. get: function () {
  15711. if (!this._debugLayer) {
  15712. this._debugLayer = new BABYLON.DebugLayer(this);
  15713. }
  15714. return this._debugLayer;
  15715. },
  15716. enumerable: true,
  15717. configurable: true
  15718. });
  15719. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15720. get: function () {
  15721. return this._workerCollisions;
  15722. },
  15723. set: function (enabled) {
  15724. if (!BABYLON.CollisionCoordinatorLegacy) {
  15725. return;
  15726. }
  15727. enabled = (enabled && !!Worker);
  15728. this._workerCollisions = enabled;
  15729. if (this.collisionCoordinator) {
  15730. this.collisionCoordinator.destroy();
  15731. }
  15732. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15733. this.collisionCoordinator.init(this);
  15734. },
  15735. enumerable: true,
  15736. configurable: true
  15737. });
  15738. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15739. get: function () {
  15740. return this._selectionOctree;
  15741. },
  15742. enumerable: true,
  15743. configurable: true
  15744. });
  15745. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15746. /**
  15747. * The mesh that is currently under the pointer.
  15748. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15749. */
  15750. get: function () {
  15751. return this._pointerOverMesh;
  15752. },
  15753. enumerable: true,
  15754. configurable: true
  15755. });
  15756. Object.defineProperty(Scene.prototype, "pointerX", {
  15757. /**
  15758. * Current on-screen X position of the pointer
  15759. * @return {number} X position of the pointer
  15760. */
  15761. get: function () {
  15762. return this._pointerX;
  15763. },
  15764. enumerable: true,
  15765. configurable: true
  15766. });
  15767. Object.defineProperty(Scene.prototype, "pointerY", {
  15768. /**
  15769. * Current on-screen Y position of the pointer
  15770. * @return {number} Y position of the pointer
  15771. */
  15772. get: function () {
  15773. return this._pointerY;
  15774. },
  15775. enumerable: true,
  15776. configurable: true
  15777. });
  15778. Scene.prototype.getCachedMaterial = function () {
  15779. return this._cachedMaterial;
  15780. };
  15781. Scene.prototype.getCachedEffect = function () {
  15782. return this._cachedEffect;
  15783. };
  15784. Scene.prototype.getCachedVisibility = function () {
  15785. return this._cachedVisibility;
  15786. };
  15787. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  15788. if (visibility === void 0) { visibility = 0; }
  15789. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  15790. };
  15791. Scene.prototype.getBoundingBoxRenderer = function () {
  15792. if (!this._boundingBoxRenderer) {
  15793. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15794. }
  15795. return this._boundingBoxRenderer;
  15796. };
  15797. Scene.prototype.getOutlineRenderer = function () {
  15798. return this._outlineRenderer;
  15799. };
  15800. Scene.prototype.getEngine = function () {
  15801. return this._engine;
  15802. };
  15803. Scene.prototype.getTotalVertices = function () {
  15804. return this._totalVertices.current;
  15805. };
  15806. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15807. get: function () {
  15808. return this._totalVertices;
  15809. },
  15810. enumerable: true,
  15811. configurable: true
  15812. });
  15813. Scene.prototype.getActiveIndices = function () {
  15814. return this._activeIndices.current;
  15815. };
  15816. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15817. get: function () {
  15818. return this._activeIndices;
  15819. },
  15820. enumerable: true,
  15821. configurable: true
  15822. });
  15823. Scene.prototype.getActiveParticles = function () {
  15824. return this._activeParticles.current;
  15825. };
  15826. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15827. get: function () {
  15828. return this._activeParticles;
  15829. },
  15830. enumerable: true,
  15831. configurable: true
  15832. });
  15833. Scene.prototype.getActiveBones = function () {
  15834. return this._activeBones.current;
  15835. };
  15836. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15837. get: function () {
  15838. return this._activeBones;
  15839. },
  15840. enumerable: true,
  15841. configurable: true
  15842. });
  15843. // Stats
  15844. Scene.prototype.getLastFrameDuration = function () {
  15845. return this._lastFrameDuration.current;
  15846. };
  15847. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15848. get: function () {
  15849. return this._lastFrameDuration;
  15850. },
  15851. enumerable: true,
  15852. configurable: true
  15853. });
  15854. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15855. return this._evaluateActiveMeshesDuration.current;
  15856. };
  15857. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15858. get: function () {
  15859. return this._evaluateActiveMeshesDuration;
  15860. },
  15861. enumerable: true,
  15862. configurable: true
  15863. });
  15864. Scene.prototype.getActiveMeshes = function () {
  15865. return this._activeMeshes;
  15866. };
  15867. Scene.prototype.getRenderTargetsDuration = function () {
  15868. return this._renderTargetsDuration.current;
  15869. };
  15870. Scene.prototype.getRenderDuration = function () {
  15871. return this._renderDuration.current;
  15872. };
  15873. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15874. get: function () {
  15875. return this._renderDuration;
  15876. },
  15877. enumerable: true,
  15878. configurable: true
  15879. });
  15880. Scene.prototype.getParticlesDuration = function () {
  15881. return this._particlesDuration.current;
  15882. };
  15883. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15884. get: function () {
  15885. return this._particlesDuration;
  15886. },
  15887. enumerable: true,
  15888. configurable: true
  15889. });
  15890. Scene.prototype.getSpritesDuration = function () {
  15891. return this._spritesDuration.current;
  15892. };
  15893. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15894. get: function () {
  15895. return this._spritesDuration;
  15896. },
  15897. enumerable: true,
  15898. configurable: true
  15899. });
  15900. Scene.prototype.getAnimationRatio = function () {
  15901. return this._animationRatio;
  15902. };
  15903. Scene.prototype.getRenderId = function () {
  15904. return this._renderId;
  15905. };
  15906. Scene.prototype.incrementRenderId = function () {
  15907. this._renderId++;
  15908. };
  15909. Scene.prototype._updatePointerPosition = function (evt) {
  15910. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15911. this._pointerX = evt.clientX - canvasRect.left;
  15912. this._pointerY = evt.clientY - canvasRect.top;
  15913. this._unTranslatedPointerX = this._pointerX;
  15914. this._unTranslatedPointerY = this._pointerY;
  15915. if (this.cameraToUseForPointers) {
  15916. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15917. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15918. }
  15919. };
  15920. Scene.prototype._createUbo = function () {
  15921. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  15922. this._sceneUbo.addUniform("viewProjection", 16);
  15923. this._sceneUbo.addUniform("view", 16);
  15924. };
  15925. // Pointers handling
  15926. /**
  15927. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15928. * @param attachUp defines if you want to attach events to pointerup
  15929. * @param attachDown defines if you want to attach events to pointerdown
  15930. * @param attachMove defines if you want to attach events to pointermove
  15931. */
  15932. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15933. var _this = this;
  15934. if (attachUp === void 0) { attachUp = true; }
  15935. if (attachDown === void 0) { attachDown = true; }
  15936. if (attachMove === void 0) { attachMove = true; }
  15937. this._initActionManager = function (act, clickInfo) {
  15938. if (!_this._meshPickProceed) {
  15939. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15940. _this._currentPickResult = pickResult;
  15941. if (pickResult) {
  15942. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  15943. }
  15944. _this._meshPickProceed = true;
  15945. }
  15946. return act;
  15947. };
  15948. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  15949. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  15950. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  15951. btn !== _this._previousButtonPressed) {
  15952. _this._doubleClickOccured = false;
  15953. clickInfo.singleClick = true;
  15954. clickInfo.ignore = false;
  15955. cb(clickInfo, _this._currentPickResult);
  15956. }
  15957. };
  15958. this._initClickEvent = function (obs1, obs2, evt, cb) {
  15959. var clickInfo = new ClickInfo();
  15960. _this._currentPickResult = null;
  15961. var act;
  15962. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  15963. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  15964. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15965. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  15966. act = _this._initActionManager(act, clickInfo);
  15967. if (act)
  15968. checkPicking = act.hasPickTriggers;
  15969. }
  15970. if (checkPicking) {
  15971. var btn = evt.button;
  15972. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  15973. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  15974. if (!clickInfo.hasSwiped) {
  15975. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  15976. if (!checkSingleClickImmediately) {
  15977. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  15978. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15979. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15980. act = _this._initActionManager(act, clickInfo);
  15981. if (act)
  15982. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15983. }
  15984. }
  15985. if (checkSingleClickImmediately) {
  15986. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  15987. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  15988. btn !== _this._previousButtonPressed) {
  15989. clickInfo.singleClick = true;
  15990. cb(clickInfo, _this._currentPickResult);
  15991. }
  15992. }
  15993. else {
  15994. // wait that no double click has been raised during the double click delay
  15995. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15996. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  15997. }
  15998. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  15999. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16000. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16001. act = _this._initActionManager(act, clickInfo);
  16002. if (act)
  16003. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16004. }
  16005. if (checkDoubleClick) {
  16006. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16007. if (btn === _this._previousButtonPressed &&
  16008. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16009. !_this._doubleClickOccured) {
  16010. // pointer has not moved for 2 clicks, it's a double click
  16011. if (!clickInfo.hasSwiped &&
  16012. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16013. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16014. _this._previousStartingPointerTime = 0;
  16015. _this._doubleClickOccured = true;
  16016. clickInfo.doubleClick = true;
  16017. clickInfo.ignore = false;
  16018. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16019. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16020. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16021. cb(clickInfo, _this._currentPickResult);
  16022. }
  16023. else {
  16024. _this._doubleClickOccured = false;
  16025. _this._previousStartingPointerTime = _this._startingPointerTime;
  16026. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16027. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16028. _this._previousButtonPressed = btn;
  16029. _this._previousHasSwiped = clickInfo.hasSwiped;
  16030. if (Scene.ExclusiveDoubleClickMode) {
  16031. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16032. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16033. }
  16034. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16035. cb(clickInfo, _this._previousPickResult);
  16036. }
  16037. else {
  16038. cb(clickInfo, _this._currentPickResult);
  16039. }
  16040. }
  16041. }
  16042. else {
  16043. _this._doubleClickOccured = false;
  16044. _this._previousStartingPointerTime = _this._startingPointerTime;
  16045. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16046. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16047. _this._previousButtonPressed = btn;
  16048. _this._previousHasSwiped = clickInfo.hasSwiped;
  16049. }
  16050. }
  16051. }
  16052. }
  16053. clickInfo.ignore = true;
  16054. cb(clickInfo, _this._currentPickResult);
  16055. };
  16056. var spritePredicate = function (sprite) {
  16057. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16058. };
  16059. this._onPointerMove = function (evt) {
  16060. _this._updatePointerPosition(evt);
  16061. // PreObservable support
  16062. if (_this.onPrePointerObservable.hasObservers()) {
  16063. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16064. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16065. _this.onPrePointerObservable.notifyObservers(pi, type);
  16066. if (pi.skipOnPointerObservable) {
  16067. return;
  16068. }
  16069. }
  16070. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16071. return;
  16072. }
  16073. var canvas = _this._engine.getRenderingCanvas();
  16074. if (!_this.pointerMovePredicate) {
  16075. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16076. }
  16077. // Meshes
  16078. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16079. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16080. _this.setPointerOverSprite(null);
  16081. _this.setPointerOverMesh(pickResult.pickedMesh);
  16082. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16083. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16084. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16085. }
  16086. else {
  16087. canvas.style.cursor = _this.hoverCursor;
  16088. }
  16089. }
  16090. else {
  16091. canvas.style.cursor = "";
  16092. }
  16093. }
  16094. else {
  16095. _this.setPointerOverMesh(null);
  16096. // Sprites
  16097. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16098. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16099. _this.setPointerOverSprite(pickResult.pickedSprite);
  16100. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16101. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16102. }
  16103. else {
  16104. canvas.style.cursor = _this.hoverCursor;
  16105. }
  16106. }
  16107. else {
  16108. _this.setPointerOverSprite(null);
  16109. // Restore pointer
  16110. canvas.style.cursor = "";
  16111. }
  16112. }
  16113. if (_this.onPointerMove) {
  16114. _this.onPointerMove(evt, pickResult);
  16115. }
  16116. if (_this.onPointerObservable.hasObservers()) {
  16117. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16118. var pi = new PointerInfo(type, evt, pickResult);
  16119. _this.onPointerObservable.notifyObservers(pi, type);
  16120. }
  16121. };
  16122. this._onPointerDown = function (evt) {
  16123. _this._isButtonPressed = true;
  16124. _this._pickedDownMesh = null;
  16125. _this._meshPickProceed = false;
  16126. _this._updatePointerPosition(evt);
  16127. // PreObservable support
  16128. if (_this.onPrePointerObservable.hasObservers()) {
  16129. var type = PointerEventTypes.POINTERDOWN;
  16130. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16131. _this.onPrePointerObservable.notifyObservers(pi, type);
  16132. if (pi.skipOnPointerObservable) {
  16133. return;
  16134. }
  16135. }
  16136. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16137. return;
  16138. }
  16139. _this._startingPointerPosition.x = _this._pointerX;
  16140. _this._startingPointerPosition.y = _this._pointerY;
  16141. _this._startingPointerTime = new Date().getTime();
  16142. if (!_this.pointerDownPredicate) {
  16143. _this.pointerDownPredicate = function (mesh) {
  16144. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16145. };
  16146. }
  16147. // Meshes
  16148. _this._pickedDownMesh = null;
  16149. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16150. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16151. _this._pickedDownMesh = pickResult.pickedMesh;
  16152. var actionManager = pickResult.pickedMesh.actionManager;
  16153. if (actionManager) {
  16154. if (actionManager.hasPickTriggers) {
  16155. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16156. switch (evt.button) {
  16157. case 0:
  16158. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16159. break;
  16160. case 1:
  16161. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16162. break;
  16163. case 2:
  16164. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16165. break;
  16166. }
  16167. }
  16168. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16169. window.setTimeout((function () {
  16170. var _this = this;
  16171. 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);
  16172. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16173. if (this._isButtonPressed &&
  16174. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16175. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16176. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16177. this._startingPointerTime = 0;
  16178. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16179. }
  16180. }
  16181. }).bind(_this), Scene.LongPressDelay);
  16182. }
  16183. }
  16184. }
  16185. if (_this.onPointerDown) {
  16186. _this.onPointerDown(evt, pickResult);
  16187. }
  16188. if (_this.onPointerObservable.hasObservers()) {
  16189. var type = PointerEventTypes.POINTERDOWN;
  16190. var pi = new PointerInfo(type, evt, pickResult);
  16191. _this.onPointerObservable.notifyObservers(pi, type);
  16192. }
  16193. // Sprites
  16194. _this._pickedDownSprite = null;
  16195. if (_this.spriteManagers.length > 0) {
  16196. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16197. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16198. if (pickResult.pickedSprite.actionManager) {
  16199. _this._pickedDownSprite = pickResult.pickedSprite;
  16200. switch (evt.button) {
  16201. case 0:
  16202. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16203. break;
  16204. case 1:
  16205. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16206. break;
  16207. case 2:
  16208. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16209. break;
  16210. }
  16211. if (pickResult.pickedSprite.actionManager) {
  16212. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16213. }
  16214. }
  16215. }
  16216. }
  16217. };
  16218. this._onPointerUp = function (evt) {
  16219. _this._isButtonPressed = false;
  16220. _this._pickedUpMesh = null;
  16221. _this._meshPickProceed = false;
  16222. _this._updatePointerPosition(evt);
  16223. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16224. // PreObservable support
  16225. if (this.onPrePointerObservable.hasObservers()) {
  16226. if (!clickInfo.ignore) {
  16227. if (!clickInfo.hasSwiped) {
  16228. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16229. var type = PointerEventTypes.POINTERTAP;
  16230. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16231. this.onPrePointerObservable.notifyObservers(pi, type);
  16232. if (pi.skipOnPointerObservable) {
  16233. return;
  16234. }
  16235. }
  16236. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16237. var type = PointerEventTypes.POINTERDOUBLETAP;
  16238. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16239. this.onPrePointerObservable.notifyObservers(pi, type);
  16240. if (pi.skipOnPointerObservable) {
  16241. return;
  16242. }
  16243. }
  16244. }
  16245. }
  16246. else {
  16247. var type = PointerEventTypes.POINTERUP;
  16248. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16249. this.onPrePointerObservable.notifyObservers(pi, type);
  16250. if (pi.skipOnPointerObservable) {
  16251. return;
  16252. }
  16253. }
  16254. }
  16255. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16256. return;
  16257. }
  16258. if (!this.pointerUpPredicate) {
  16259. this.pointerUpPredicate = function (mesh) {
  16260. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16261. };
  16262. }
  16263. // Meshes
  16264. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16265. this._initActionManager(null, clickInfo);
  16266. }
  16267. if (!pickResult) {
  16268. pickResult = this._currentPickResult;
  16269. }
  16270. if (pickResult && pickResult && pickResult.pickedMesh) {
  16271. this._pickedUpMesh = pickResult.pickedMesh;
  16272. if (this._pickedDownMesh === this._pickedUpMesh) {
  16273. if (this.onPointerPick) {
  16274. this.onPointerPick(evt, pickResult);
  16275. }
  16276. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16277. var type = PointerEventTypes.POINTERPICK;
  16278. var pi = new PointerInfo(type, evt, pickResult);
  16279. this.onPointerObservable.notifyObservers(pi, type);
  16280. }
  16281. }
  16282. if (pickResult.pickedMesh.actionManager) {
  16283. if (clickInfo.ignore) {
  16284. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16285. }
  16286. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16287. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16288. }
  16289. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16290. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16291. }
  16292. }
  16293. }
  16294. if (this._pickedDownMesh &&
  16295. this._pickedDownMesh.actionManager &&
  16296. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16297. this._pickedDownMesh !== this._pickedUpMesh) {
  16298. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16299. }
  16300. if (this.onPointerUp) {
  16301. this.onPointerUp(evt, pickResult);
  16302. }
  16303. if (this.onPointerObservable.hasObservers()) {
  16304. if (!clickInfo.ignore) {
  16305. if (!clickInfo.hasSwiped) {
  16306. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16307. var type = PointerEventTypes.POINTERTAP;
  16308. var pi = new PointerInfo(type, evt, pickResult);
  16309. this.onPointerObservable.notifyObservers(pi, type);
  16310. }
  16311. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16312. var type = PointerEventTypes.POINTERDOUBLETAP;
  16313. var pi = new PointerInfo(type, evt, pickResult);
  16314. this.onPointerObservable.notifyObservers(pi, type);
  16315. }
  16316. }
  16317. }
  16318. else {
  16319. var type = PointerEventTypes.POINTERUP;
  16320. var pi = new PointerInfo(type, evt, pickResult);
  16321. this.onPointerObservable.notifyObservers(pi, type);
  16322. }
  16323. }
  16324. // Sprites
  16325. if (this.spriteManagers.length > 0) {
  16326. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16327. if (pickResult.hit && pickResult.pickedSprite) {
  16328. if (pickResult.pickedSprite.actionManager) {
  16329. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16330. if (pickResult.pickedSprite.actionManager) {
  16331. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16332. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16333. }
  16334. }
  16335. }
  16336. }
  16337. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16338. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16339. }
  16340. }
  16341. this._previousPickResult = this._currentPickResult;
  16342. }).bind(_this));
  16343. };
  16344. this._onKeyDown = function (evt) {
  16345. if (_this.actionManager) {
  16346. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16347. }
  16348. };
  16349. this._onKeyUp = function (evt) {
  16350. if (_this.actionManager) {
  16351. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16352. }
  16353. };
  16354. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16355. var canvas = this._engine.getRenderingCanvas();
  16356. if (attachMove) {
  16357. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16358. // Wheel
  16359. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16360. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16361. }
  16362. if (attachDown) {
  16363. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16364. }
  16365. if (attachUp) {
  16366. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16367. }
  16368. canvas.tabIndex = 1;
  16369. canvas.addEventListener("keydown", this._onKeyDown, false);
  16370. canvas.addEventListener("keyup", this._onKeyUp, false);
  16371. };
  16372. Scene.prototype.detachControl = function () {
  16373. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16374. var canvas = this._engine.getRenderingCanvas();
  16375. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16376. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16377. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16378. // Wheel
  16379. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16380. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16381. canvas.removeEventListener("keydown", this._onKeyDown);
  16382. canvas.removeEventListener("keyup", this._onKeyUp);
  16383. };
  16384. // Ready
  16385. Scene.prototype.isReady = function () {
  16386. if (this._pendingData.length > 0) {
  16387. return false;
  16388. }
  16389. var index;
  16390. // Geometries
  16391. for (index = 0; index < this._geometries.length; index++) {
  16392. var geometry = this._geometries[index];
  16393. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16394. return false;
  16395. }
  16396. }
  16397. // Meshes
  16398. for (index = 0; index < this.meshes.length; index++) {
  16399. var mesh = this.meshes[index];
  16400. if (!mesh.isEnabled()) {
  16401. continue;
  16402. }
  16403. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16404. continue;
  16405. }
  16406. if (!mesh.isReady()) {
  16407. return false;
  16408. }
  16409. var mat = mesh.material;
  16410. if (mat) {
  16411. if (!mat.isReady(mesh)) {
  16412. return false;
  16413. }
  16414. }
  16415. }
  16416. return true;
  16417. };
  16418. Scene.prototype.resetCachedMaterial = function () {
  16419. this._cachedMaterial = null;
  16420. this._cachedEffect = null;
  16421. this._cachedVisibility = null;
  16422. };
  16423. Scene.prototype.registerBeforeRender = function (func) {
  16424. this.onBeforeRenderObservable.add(func);
  16425. };
  16426. Scene.prototype.unregisterBeforeRender = function (func) {
  16427. this.onBeforeRenderObservable.removeCallback(func);
  16428. };
  16429. Scene.prototype.registerAfterRender = function (func) {
  16430. this.onAfterRenderObservable.add(func);
  16431. };
  16432. Scene.prototype.unregisterAfterRender = function (func) {
  16433. this.onAfterRenderObservable.removeCallback(func);
  16434. };
  16435. Scene.prototype._addPendingData = function (data) {
  16436. this._pendingData.push(data);
  16437. };
  16438. Scene.prototype._removePendingData = function (data) {
  16439. var index = this._pendingData.indexOf(data);
  16440. if (index !== -1) {
  16441. this._pendingData.splice(index, 1);
  16442. }
  16443. };
  16444. Scene.prototype.getWaitingItemsCount = function () {
  16445. return this._pendingData.length;
  16446. };
  16447. /**
  16448. * Registers a function to be executed when the scene is ready.
  16449. * @param {Function} func - the function to be executed.
  16450. */
  16451. Scene.prototype.executeWhenReady = function (func) {
  16452. var _this = this;
  16453. this.onReadyObservable.add(func);
  16454. if (this._executeWhenReadyTimeoutId !== -1) {
  16455. return;
  16456. }
  16457. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16458. _this._checkIsReady();
  16459. }, 150);
  16460. };
  16461. Scene.prototype._checkIsReady = function () {
  16462. var _this = this;
  16463. if (this.isReady()) {
  16464. this.onReadyObservable.notifyObservers(this);
  16465. this.onReadyObservable.clear();
  16466. this._executeWhenReadyTimeoutId = -1;
  16467. return;
  16468. }
  16469. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16470. _this._checkIsReady();
  16471. }, 150);
  16472. };
  16473. // Animations
  16474. /**
  16475. * Will start the animation sequence of a given target
  16476. * @param target - the target
  16477. * @param {number} from - from which frame should animation start
  16478. * @param {number} to - till which frame should animation run.
  16479. * @param {boolean} [loop] - should the animation loop
  16480. * @param {number} [speedRatio] - the speed in which to run the animation
  16481. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16482. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16483. * @return {BABYLON.Animatable} the animatable object created for this animation
  16484. * @see BABYLON.Animatable
  16485. * @see http://doc.babylonjs.com/page.php?p=22081
  16486. */
  16487. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16488. if (speedRatio === void 0) { speedRatio = 1.0; }
  16489. this.stopAnimation(target);
  16490. if (!animatable) {
  16491. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16492. }
  16493. // Local animations
  16494. if (target.animations) {
  16495. animatable.appendAnimations(target, target.animations);
  16496. }
  16497. // Children animations
  16498. if (target.getAnimatables) {
  16499. var animatables = target.getAnimatables();
  16500. for (var index = 0; index < animatables.length; index++) {
  16501. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16502. }
  16503. }
  16504. animatable.reset();
  16505. return animatable;
  16506. };
  16507. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16508. if (speedRatio === undefined) {
  16509. speedRatio = 1.0;
  16510. }
  16511. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16512. return animatable;
  16513. };
  16514. Scene.prototype.getAnimatableByTarget = function (target) {
  16515. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16516. if (this._activeAnimatables[index].target === target) {
  16517. return this._activeAnimatables[index];
  16518. }
  16519. }
  16520. return null;
  16521. };
  16522. Object.defineProperty(Scene.prototype, "Animatables", {
  16523. get: function () {
  16524. return this._activeAnimatables;
  16525. },
  16526. enumerable: true,
  16527. configurable: true
  16528. });
  16529. /**
  16530. * Will stop the animation of the given target
  16531. * @param target - the target
  16532. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16533. * @see beginAnimation
  16534. */
  16535. Scene.prototype.stopAnimation = function (target, animationName) {
  16536. var animatable = this.getAnimatableByTarget(target);
  16537. if (animatable) {
  16538. animatable.stop(animationName);
  16539. }
  16540. };
  16541. Scene.prototype._animate = function () {
  16542. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16543. return;
  16544. }
  16545. // Getting time
  16546. var now = BABYLON.Tools.Now;
  16547. if (!this._animationTimeLast) {
  16548. if (this._pendingData.length > 0) {
  16549. return;
  16550. }
  16551. this._animationTimeLast = now;
  16552. }
  16553. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16554. this._animationTime += deltaTime;
  16555. this._animationTimeLast = now;
  16556. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16557. this._activeAnimatables[index]._animate(this._animationTime);
  16558. }
  16559. };
  16560. // Matrix
  16561. Scene.prototype.getViewMatrix = function () {
  16562. return this._viewMatrix;
  16563. };
  16564. Scene.prototype.getProjectionMatrix = function () {
  16565. return this._projectionMatrix;
  16566. };
  16567. Scene.prototype.getTransformMatrix = function () {
  16568. return this._transformMatrix;
  16569. };
  16570. Scene.prototype.setTransformMatrix = function (view, projection) {
  16571. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16572. return;
  16573. }
  16574. this._viewUpdateFlag = view.updateFlag;
  16575. this._projectionUpdateFlag = projection.updateFlag;
  16576. this._viewMatrix = view;
  16577. this._projectionMatrix = projection;
  16578. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16579. // Update frustum
  16580. if (!this._frustumPlanes) {
  16581. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16582. }
  16583. else {
  16584. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16585. }
  16586. if (this._sceneUbo.useUbo) {
  16587. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16588. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16589. this._sceneUbo.update();
  16590. }
  16591. };
  16592. Scene.prototype.getSceneUniformBuffer = function () {
  16593. return this._sceneUbo;
  16594. };
  16595. // Methods
  16596. Scene.prototype.getUniqueId = function () {
  16597. var result = this._uniqueIdCounter;
  16598. this._uniqueIdCounter++;
  16599. return result;
  16600. };
  16601. Scene.prototype.addMesh = function (newMesh) {
  16602. newMesh.uniqueId = this.getUniqueId();
  16603. var position = this.meshes.push(newMesh);
  16604. //notify the collision coordinator
  16605. if (this.collisionCoordinator) {
  16606. this.collisionCoordinator.onMeshAdded(newMesh);
  16607. }
  16608. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16609. };
  16610. Scene.prototype.removeMesh = function (toRemove) {
  16611. var index = this.meshes.indexOf(toRemove);
  16612. if (index !== -1) {
  16613. // Remove from the scene if mesh found
  16614. this.meshes.splice(index, 1);
  16615. }
  16616. //notify the collision coordinator
  16617. if (this.collisionCoordinator) {
  16618. this.collisionCoordinator.onMeshRemoved(toRemove);
  16619. }
  16620. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16621. return index;
  16622. };
  16623. Scene.prototype.removeSkeleton = function (toRemove) {
  16624. var index = this.skeletons.indexOf(toRemove);
  16625. if (index !== -1) {
  16626. // Remove from the scene if found
  16627. this.skeletons.splice(index, 1);
  16628. }
  16629. return index;
  16630. };
  16631. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16632. var index = this.morphTargetManagers.indexOf(toRemove);
  16633. if (index !== -1) {
  16634. // Remove from the scene if found
  16635. this.morphTargetManagers.splice(index, 1);
  16636. }
  16637. return index;
  16638. };
  16639. Scene.prototype.removeLight = function (toRemove) {
  16640. var index = this.lights.indexOf(toRemove);
  16641. if (index !== -1) {
  16642. // Remove from the scene if mesh found
  16643. this.lights.splice(index, 1);
  16644. this.sortLightsByPriority();
  16645. }
  16646. this.onLightRemovedObservable.notifyObservers(toRemove);
  16647. return index;
  16648. };
  16649. Scene.prototype.removeCamera = function (toRemove) {
  16650. var index = this.cameras.indexOf(toRemove);
  16651. if (index !== -1) {
  16652. // Remove from the scene if mesh found
  16653. this.cameras.splice(index, 1);
  16654. }
  16655. // Remove from activeCameras
  16656. var index2 = this.activeCameras.indexOf(toRemove);
  16657. if (index2 !== -1) {
  16658. // Remove from the scene if mesh found
  16659. this.activeCameras.splice(index2, 1);
  16660. }
  16661. // Reset the activeCamera
  16662. if (this.activeCamera === toRemove) {
  16663. if (this.cameras.length > 0) {
  16664. this.activeCamera = this.cameras[0];
  16665. }
  16666. else {
  16667. this.activeCamera = null;
  16668. }
  16669. }
  16670. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16671. return index;
  16672. };
  16673. Scene.prototype.addLight = function (newLight) {
  16674. newLight.uniqueId = this.getUniqueId();
  16675. this.lights.push(newLight);
  16676. this.sortLightsByPriority();
  16677. this.onNewLightAddedObservable.notifyObservers(newLight);
  16678. };
  16679. Scene.prototype.sortLightsByPriority = function () {
  16680. if (this.requireLightSorting) {
  16681. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16682. }
  16683. };
  16684. Scene.prototype.addCamera = function (newCamera) {
  16685. newCamera.uniqueId = this.getUniqueId();
  16686. var position = this.cameras.push(newCamera);
  16687. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16688. };
  16689. /**
  16690. * Switch active camera
  16691. * @param {Camera} newCamera - new active camera
  16692. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16693. */
  16694. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16695. if (attachControl === void 0) { attachControl = true; }
  16696. var canvas = this._engine.getRenderingCanvas();
  16697. this.activeCamera.detachControl(canvas);
  16698. this.activeCamera = newCamera;
  16699. if (attachControl) {
  16700. newCamera.attachControl(canvas);
  16701. }
  16702. };
  16703. /**
  16704. * sets the active camera of the scene using its ID
  16705. * @param {string} id - the camera's ID
  16706. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16707. * @see activeCamera
  16708. */
  16709. Scene.prototype.setActiveCameraByID = function (id) {
  16710. var camera = this.getCameraByID(id);
  16711. if (camera) {
  16712. this.activeCamera = camera;
  16713. return camera;
  16714. }
  16715. return null;
  16716. };
  16717. /**
  16718. * sets the active camera of the scene using its name
  16719. * @param {string} name - the camera's name
  16720. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16721. * @see activeCamera
  16722. */
  16723. Scene.prototype.setActiveCameraByName = function (name) {
  16724. var camera = this.getCameraByName(name);
  16725. if (camera) {
  16726. this.activeCamera = camera;
  16727. return camera;
  16728. }
  16729. return null;
  16730. };
  16731. /**
  16732. * get a material using its id
  16733. * @param {string} the material's ID
  16734. * @return {BABYLON.Material|null} the material or null if none found.
  16735. */
  16736. Scene.prototype.getMaterialByID = function (id) {
  16737. for (var index = 0; index < this.materials.length; index++) {
  16738. if (this.materials[index].id === id) {
  16739. return this.materials[index];
  16740. }
  16741. }
  16742. return null;
  16743. };
  16744. /**
  16745. * get a material using its name
  16746. * @param {string} the material's name
  16747. * @return {BABYLON.Material|null} the material or null if none found.
  16748. */
  16749. Scene.prototype.getMaterialByName = function (name) {
  16750. for (var index = 0; index < this.materials.length; index++) {
  16751. if (this.materials[index].name === name) {
  16752. return this.materials[index];
  16753. }
  16754. }
  16755. return null;
  16756. };
  16757. Scene.prototype.getLensFlareSystemByName = function (name) {
  16758. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16759. if (this.lensFlareSystems[index].name === name) {
  16760. return this.lensFlareSystems[index];
  16761. }
  16762. }
  16763. return null;
  16764. };
  16765. Scene.prototype.getLensFlareSystemByID = function (id) {
  16766. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16767. if (this.lensFlareSystems[index].id === id) {
  16768. return this.lensFlareSystems[index];
  16769. }
  16770. }
  16771. return null;
  16772. };
  16773. Scene.prototype.getCameraByID = function (id) {
  16774. for (var index = 0; index < this.cameras.length; index++) {
  16775. if (this.cameras[index].id === id) {
  16776. return this.cameras[index];
  16777. }
  16778. }
  16779. return null;
  16780. };
  16781. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16782. for (var index = 0; index < this.cameras.length; index++) {
  16783. if (this.cameras[index].uniqueId === uniqueId) {
  16784. return this.cameras[index];
  16785. }
  16786. }
  16787. return null;
  16788. };
  16789. /**
  16790. * get a camera using its name
  16791. * @param {string} the camera's name
  16792. * @return {BABYLON.Camera|null} the camera or null if none found.
  16793. */
  16794. Scene.prototype.getCameraByName = function (name) {
  16795. for (var index = 0; index < this.cameras.length; index++) {
  16796. if (this.cameras[index].name === name) {
  16797. return this.cameras[index];
  16798. }
  16799. }
  16800. return null;
  16801. };
  16802. /**
  16803. * get a bone using its id
  16804. * @param {string} the bone's id
  16805. * @return {BABYLON.Bone|null} the bone or null if not found
  16806. */
  16807. Scene.prototype.getBoneByID = function (id) {
  16808. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16809. var skeleton = this.skeletons[skeletonIndex];
  16810. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16811. if (skeleton.bones[boneIndex].id === id) {
  16812. return skeleton.bones[boneIndex];
  16813. }
  16814. }
  16815. }
  16816. return null;
  16817. };
  16818. /**
  16819. * get a bone using its id
  16820. * @param {string} the bone's name
  16821. * @return {BABYLON.Bone|null} the bone or null if not found
  16822. */
  16823. Scene.prototype.getBoneByName = function (name) {
  16824. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16825. var skeleton = this.skeletons[skeletonIndex];
  16826. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16827. if (skeleton.bones[boneIndex].name === name) {
  16828. return skeleton.bones[boneIndex];
  16829. }
  16830. }
  16831. }
  16832. return null;
  16833. };
  16834. /**
  16835. * get a light node using its name
  16836. * @param {string} the light's name
  16837. * @return {BABYLON.Light|null} the light or null if none found.
  16838. */
  16839. Scene.prototype.getLightByName = function (name) {
  16840. for (var index = 0; index < this.lights.length; index++) {
  16841. if (this.lights[index].name === name) {
  16842. return this.lights[index];
  16843. }
  16844. }
  16845. return null;
  16846. };
  16847. /**
  16848. * get a light node using its ID
  16849. * @param {string} the light's id
  16850. * @return {BABYLON.Light|null} the light or null if none found.
  16851. */
  16852. Scene.prototype.getLightByID = function (id) {
  16853. for (var index = 0; index < this.lights.length; index++) {
  16854. if (this.lights[index].id === id) {
  16855. return this.lights[index];
  16856. }
  16857. }
  16858. return null;
  16859. };
  16860. /**
  16861. * get a light node using its scene-generated unique ID
  16862. * @param {number} the light's unique id
  16863. * @return {BABYLON.Light|null} the light or null if none found.
  16864. */
  16865. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16866. for (var index = 0; index < this.lights.length; index++) {
  16867. if (this.lights[index].uniqueId === uniqueId) {
  16868. return this.lights[index];
  16869. }
  16870. }
  16871. return null;
  16872. };
  16873. /**
  16874. * get a particle system by id
  16875. * @param id {number} the particle system id
  16876. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16877. */
  16878. Scene.prototype.getParticleSystemByID = function (id) {
  16879. for (var index = 0; index < this.particleSystems.length; index++) {
  16880. if (this.particleSystems[index].id === id) {
  16881. return this.particleSystems[index];
  16882. }
  16883. }
  16884. return null;
  16885. };
  16886. /**
  16887. * get a geometry using its ID
  16888. * @param {string} the geometry's id
  16889. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16890. */
  16891. Scene.prototype.getGeometryByID = function (id) {
  16892. for (var index = 0; index < this._geometries.length; index++) {
  16893. if (this._geometries[index].id === id) {
  16894. return this._geometries[index];
  16895. }
  16896. }
  16897. return null;
  16898. };
  16899. /**
  16900. * add a new geometry to this scene.
  16901. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16902. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16903. * @return {boolean} was the geometry added or not
  16904. */
  16905. Scene.prototype.pushGeometry = function (geometry, force) {
  16906. if (!force && this.getGeometryByID(geometry.id)) {
  16907. return false;
  16908. }
  16909. this._geometries.push(geometry);
  16910. //notify the collision coordinator
  16911. if (this.collisionCoordinator) {
  16912. this.collisionCoordinator.onGeometryAdded(geometry);
  16913. }
  16914. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16915. return true;
  16916. };
  16917. /**
  16918. * Removes an existing geometry
  16919. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16920. * @return {boolean} was the geometry removed or not
  16921. */
  16922. Scene.prototype.removeGeometry = function (geometry) {
  16923. var index = this._geometries.indexOf(geometry);
  16924. if (index > -1) {
  16925. this._geometries.splice(index, 1);
  16926. //notify the collision coordinator
  16927. if (this.collisionCoordinator) {
  16928. this.collisionCoordinator.onGeometryDeleted(geometry);
  16929. }
  16930. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16931. return true;
  16932. }
  16933. return false;
  16934. };
  16935. Scene.prototype.getGeometries = function () {
  16936. return this._geometries;
  16937. };
  16938. /**
  16939. * Get the first added mesh found of a given ID
  16940. * @param {string} id - the id to search for
  16941. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16942. */
  16943. Scene.prototype.getMeshByID = function (id) {
  16944. for (var index = 0; index < this.meshes.length; index++) {
  16945. if (this.meshes[index].id === id) {
  16946. return this.meshes[index];
  16947. }
  16948. }
  16949. return null;
  16950. };
  16951. Scene.prototype.getMeshesByID = function (id) {
  16952. return this.meshes.filter(function (m) {
  16953. return m.id === id;
  16954. });
  16955. };
  16956. /**
  16957. * Get a mesh with its auto-generated unique id
  16958. * @param {number} uniqueId - the unique id to search for
  16959. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16960. */
  16961. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16962. for (var index = 0; index < this.meshes.length; index++) {
  16963. if (this.meshes[index].uniqueId === uniqueId) {
  16964. return this.meshes[index];
  16965. }
  16966. }
  16967. return null;
  16968. };
  16969. /**
  16970. * Get a the last added mesh found of a given ID
  16971. * @param {string} id - the id to search for
  16972. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16973. */
  16974. Scene.prototype.getLastMeshByID = function (id) {
  16975. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16976. if (this.meshes[index].id === id) {
  16977. return this.meshes[index];
  16978. }
  16979. }
  16980. return null;
  16981. };
  16982. /**
  16983. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16984. * @param {string} id - the id to search for
  16985. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16986. */
  16987. Scene.prototype.getLastEntryByID = function (id) {
  16988. var index;
  16989. for (index = this.meshes.length - 1; index >= 0; index--) {
  16990. if (this.meshes[index].id === id) {
  16991. return this.meshes[index];
  16992. }
  16993. }
  16994. for (index = this.cameras.length - 1; index >= 0; index--) {
  16995. if (this.cameras[index].id === id) {
  16996. return this.cameras[index];
  16997. }
  16998. }
  16999. for (index = this.lights.length - 1; index >= 0; index--) {
  17000. if (this.lights[index].id === id) {
  17001. return this.lights[index];
  17002. }
  17003. }
  17004. return null;
  17005. };
  17006. Scene.prototype.getNodeByID = function (id) {
  17007. var mesh = this.getMeshByID(id);
  17008. if (mesh) {
  17009. return mesh;
  17010. }
  17011. var light = this.getLightByID(id);
  17012. if (light) {
  17013. return light;
  17014. }
  17015. var camera = this.getCameraByID(id);
  17016. if (camera) {
  17017. return camera;
  17018. }
  17019. var bone = this.getBoneByID(id);
  17020. return bone;
  17021. };
  17022. Scene.prototype.getNodeByName = function (name) {
  17023. var mesh = this.getMeshByName(name);
  17024. if (mesh) {
  17025. return mesh;
  17026. }
  17027. var light = this.getLightByName(name);
  17028. if (light) {
  17029. return light;
  17030. }
  17031. var camera = this.getCameraByName(name);
  17032. if (camera) {
  17033. return camera;
  17034. }
  17035. var bone = this.getBoneByName(name);
  17036. return bone;
  17037. };
  17038. Scene.prototype.getMeshByName = function (name) {
  17039. for (var index = 0; index < this.meshes.length; index++) {
  17040. if (this.meshes[index].name === name) {
  17041. return this.meshes[index];
  17042. }
  17043. }
  17044. return null;
  17045. };
  17046. Scene.prototype.getSoundByName = function (name) {
  17047. var index;
  17048. if (BABYLON.AudioEngine) {
  17049. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17050. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17051. return this.mainSoundTrack.soundCollection[index];
  17052. }
  17053. }
  17054. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17055. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17056. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17057. return this.soundTracks[sdIndex].soundCollection[index];
  17058. }
  17059. }
  17060. }
  17061. }
  17062. return null;
  17063. };
  17064. Scene.prototype.getLastSkeletonByID = function (id) {
  17065. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17066. if (this.skeletons[index].id === id) {
  17067. return this.skeletons[index];
  17068. }
  17069. }
  17070. return null;
  17071. };
  17072. Scene.prototype.getSkeletonById = function (id) {
  17073. for (var index = 0; index < this.skeletons.length; index++) {
  17074. if (this.skeletons[index].id === id) {
  17075. return this.skeletons[index];
  17076. }
  17077. }
  17078. return null;
  17079. };
  17080. Scene.prototype.getSkeletonByName = function (name) {
  17081. for (var index = 0; index < this.skeletons.length; index++) {
  17082. if (this.skeletons[index].name === name) {
  17083. return this.skeletons[index];
  17084. }
  17085. }
  17086. return null;
  17087. };
  17088. Scene.prototype.getMorphTargetManagerById = function (id) {
  17089. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17090. if (this.morphTargetManagers[index].uniqueId === id) {
  17091. return this.morphTargetManagers[index];
  17092. }
  17093. }
  17094. return null;
  17095. };
  17096. Scene.prototype.isActiveMesh = function (mesh) {
  17097. return (this._activeMeshes.indexOf(mesh) !== -1);
  17098. };
  17099. /**
  17100. * Return a the first highlight layer of the scene with a given name.
  17101. * @param name The name of the highlight layer to look for.
  17102. * @return The highlight layer if found otherwise null.
  17103. */
  17104. Scene.prototype.getHighlightLayerByName = function (name) {
  17105. for (var index = 0; index < this.highlightLayers.length; index++) {
  17106. if (this.highlightLayers[index].name === name) {
  17107. return this.highlightLayers[index];
  17108. }
  17109. }
  17110. return null;
  17111. };
  17112. Object.defineProperty(Scene.prototype, "uid", {
  17113. /**
  17114. * Return a unique id as a string which can serve as an identifier for the scene
  17115. */
  17116. get: function () {
  17117. if (!this._uid) {
  17118. this._uid = BABYLON.Tools.RandomId();
  17119. }
  17120. return this._uid;
  17121. },
  17122. enumerable: true,
  17123. configurable: true
  17124. });
  17125. /**
  17126. * Add an externaly attached data from its key.
  17127. * This method call will fail and return false, if such key already exists.
  17128. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17129. * @param key the unique key that identifies the data
  17130. * @param data the data object to associate to the key for this Engine instance
  17131. * @return true if no such key were already present and the data was added successfully, false otherwise
  17132. */
  17133. Scene.prototype.addExternalData = function (key, data) {
  17134. if (!this._externalData) {
  17135. this._externalData = new BABYLON.StringDictionary();
  17136. }
  17137. return this._externalData.add(key, data);
  17138. };
  17139. /**
  17140. * Get an externaly attached data from its key
  17141. * @param key the unique key that identifies the data
  17142. * @return the associated data, if present (can be null), or undefined if not present
  17143. */
  17144. Scene.prototype.getExternalData = function (key) {
  17145. if (!this._externalData) {
  17146. return null;
  17147. }
  17148. return this._externalData.get(key);
  17149. };
  17150. /**
  17151. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17152. * @param key the unique key that identifies the data
  17153. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17154. * @return the associated data, can be null if the factory returned null.
  17155. */
  17156. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17157. if (!this._externalData) {
  17158. this._externalData = new BABYLON.StringDictionary();
  17159. }
  17160. return this._externalData.getOrAddWithFactory(key, factory);
  17161. };
  17162. /**
  17163. * Remove an externaly attached data from the Engine instance
  17164. * @param key the unique key that identifies the data
  17165. * @return true if the data was successfully removed, false if it doesn't exist
  17166. */
  17167. Scene.prototype.removeExternalData = function (key) {
  17168. return this._externalData.remove(key);
  17169. };
  17170. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17171. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17172. var material = subMesh.getMaterial();
  17173. if (mesh.showSubMeshesBoundingBox) {
  17174. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17175. }
  17176. if (material) {
  17177. // Render targets
  17178. if (material.getRenderTargetTextures) {
  17179. if (this._processedMaterials.indexOf(material) === -1) {
  17180. this._processedMaterials.push(material);
  17181. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17182. }
  17183. }
  17184. // Dispatch
  17185. this._activeIndices.addCount(subMesh.indexCount, false);
  17186. this._renderingManager.dispatch(subMesh);
  17187. }
  17188. }
  17189. };
  17190. Scene.prototype._isInIntermediateRendering = function () {
  17191. return this._intermediateRendering;
  17192. };
  17193. Scene.prototype._evaluateActiveMeshes = function () {
  17194. this.activeCamera._activeMeshes.reset();
  17195. this._activeMeshes.reset();
  17196. this._renderingManager.reset();
  17197. this._processedMaterials.reset();
  17198. this._activeParticleSystems.reset();
  17199. this._activeSkeletons.reset();
  17200. this._softwareSkinnedMeshes.reset();
  17201. if (this._boundingBoxRenderer) {
  17202. this._boundingBoxRenderer.reset();
  17203. }
  17204. // Meshes
  17205. var meshes;
  17206. var len;
  17207. if (this._selectionOctree) {
  17208. var selection = this._selectionOctree.select(this._frustumPlanes);
  17209. meshes = selection.data;
  17210. len = selection.length;
  17211. }
  17212. else {
  17213. len = this.meshes.length;
  17214. meshes = this.meshes;
  17215. }
  17216. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17217. var mesh = meshes[meshIndex];
  17218. if (mesh.isBlocked) {
  17219. continue;
  17220. }
  17221. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17222. if (!mesh.isReady() || !mesh.isEnabled()) {
  17223. continue;
  17224. }
  17225. mesh.computeWorldMatrix();
  17226. // Intersections
  17227. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17228. this._meshesForIntersections.pushNoDuplicate(mesh);
  17229. }
  17230. // Switch to current LOD
  17231. var meshLOD = mesh.getLOD(this.activeCamera);
  17232. if (!meshLOD) {
  17233. continue;
  17234. }
  17235. mesh._preActivate();
  17236. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17237. this._activeMeshes.push(mesh);
  17238. this.activeCamera._activeMeshes.push(mesh);
  17239. mesh._activate(this._renderId);
  17240. this._activeMesh(mesh, meshLOD);
  17241. }
  17242. }
  17243. // Particle systems
  17244. this._particlesDuration.beginMonitoring();
  17245. var beforeParticlesDate = BABYLON.Tools.Now;
  17246. if (this.particlesEnabled) {
  17247. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17248. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17249. var particleSystem = this.particleSystems[particleIndex];
  17250. if (!particleSystem.isStarted()) {
  17251. continue;
  17252. }
  17253. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17254. this._activeParticleSystems.push(particleSystem);
  17255. particleSystem.animate();
  17256. this._renderingManager.dispatchParticles(particleSystem);
  17257. }
  17258. }
  17259. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17260. }
  17261. this._particlesDuration.endMonitoring(false);
  17262. };
  17263. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17264. if (mesh.skeleton && this.skeletonsEnabled) {
  17265. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17266. mesh.skeleton.prepare();
  17267. }
  17268. if (!mesh.computeBonesUsingShaders) {
  17269. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17270. }
  17271. }
  17272. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17273. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17274. }
  17275. if (mesh && mesh.subMeshes) {
  17276. // Submeshes Octrees
  17277. var len;
  17278. var subMeshes;
  17279. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17280. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17281. len = intersections.length;
  17282. subMeshes = intersections.data;
  17283. }
  17284. else {
  17285. subMeshes = mesh.subMeshes;
  17286. len = subMeshes.length;
  17287. }
  17288. for (var subIndex = 0; subIndex < len; subIndex++) {
  17289. var subMesh = subMeshes[subIndex];
  17290. this._evaluateSubMesh(subMesh, mesh);
  17291. }
  17292. }
  17293. };
  17294. Scene.prototype.updateTransformMatrix = function (force) {
  17295. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17296. };
  17297. Scene.prototype._renderForCamera = function (camera) {
  17298. var engine = this._engine;
  17299. var startTime = BABYLON.Tools.Now;
  17300. this.activeCamera = camera;
  17301. if (!this.activeCamera)
  17302. throw new Error("Active camera not set");
  17303. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17304. // Viewport
  17305. engine.setViewport(this.activeCamera.viewport);
  17306. // Camera
  17307. this.resetCachedMaterial();
  17308. this._renderId++;
  17309. this.updateTransformMatrix();
  17310. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17311. // Meshes
  17312. this._evaluateActiveMeshesDuration.beginMonitoring();
  17313. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17314. this._evaluateActiveMeshes();
  17315. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17316. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17317. // Software skinning
  17318. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17319. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17320. mesh.applySkeleton(mesh.skeleton);
  17321. }
  17322. // Render targets
  17323. this._renderTargetsDuration.beginMonitoring();
  17324. var needsRestoreFrameBuffer = false;
  17325. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17326. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17327. this._intermediateRendering = true;
  17328. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17329. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17330. var renderTarget = this._renderTargets.data[renderIndex];
  17331. if (renderTarget._shouldRender()) {
  17332. this._renderId++;
  17333. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17334. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17335. }
  17336. }
  17337. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17338. this._intermediateRendering = false;
  17339. this._renderId++;
  17340. needsRestoreFrameBuffer = true; // Restore back buffer
  17341. }
  17342. // Render HighlightLayer Texture
  17343. var stencilState = this._engine.getStencilBuffer();
  17344. var renderhighlights = false;
  17345. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17346. this._intermediateRendering = true;
  17347. for (var i = 0; i < this.highlightLayers.length; i++) {
  17348. var highlightLayer = this.highlightLayers[i];
  17349. if (highlightLayer.shouldRender() &&
  17350. (!highlightLayer.camera ||
  17351. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17352. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17353. renderhighlights = true;
  17354. var renderTarget = highlightLayer._mainTexture;
  17355. if (renderTarget._shouldRender()) {
  17356. this._renderId++;
  17357. renderTarget.render(false, false);
  17358. needsRestoreFrameBuffer = true;
  17359. }
  17360. }
  17361. }
  17362. this._intermediateRendering = false;
  17363. this._renderId++;
  17364. }
  17365. if (needsRestoreFrameBuffer) {
  17366. if (this.offscreenRenderTarget) {
  17367. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17368. }
  17369. else {
  17370. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17371. }
  17372. }
  17373. this._renderTargetsDuration.endMonitoring(false);
  17374. // Prepare Frame
  17375. this.postProcessManager._prepareFrame();
  17376. this._renderDuration.beginMonitoring();
  17377. // Backgrounds
  17378. var layerIndex;
  17379. var layer;
  17380. if (this.layers.length) {
  17381. engine.setDepthBuffer(false);
  17382. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17383. layer = this.layers[layerIndex];
  17384. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17385. layer.render();
  17386. }
  17387. }
  17388. engine.setDepthBuffer(true);
  17389. }
  17390. // Render
  17391. BABYLON.Tools.StartPerformanceCounter("Main render");
  17392. // Activate HighlightLayer stencil
  17393. if (renderhighlights) {
  17394. this._engine.setStencilBuffer(true);
  17395. }
  17396. this._renderingManager.render(null, null, true, true);
  17397. // Restore HighlightLayer stencil
  17398. if (renderhighlights) {
  17399. this._engine.setStencilBuffer(stencilState);
  17400. }
  17401. BABYLON.Tools.EndPerformanceCounter("Main render");
  17402. // Bounding boxes
  17403. if (this._boundingBoxRenderer) {
  17404. this._boundingBoxRenderer.render();
  17405. }
  17406. // Lens flares
  17407. if (this.lensFlaresEnabled) {
  17408. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17409. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17410. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17411. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17412. lensFlareSystem.render();
  17413. }
  17414. }
  17415. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17416. }
  17417. // Foregrounds
  17418. if (this.layers.length) {
  17419. engine.setDepthBuffer(false);
  17420. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17421. layer = this.layers[layerIndex];
  17422. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17423. layer.render();
  17424. }
  17425. }
  17426. engine.setDepthBuffer(true);
  17427. }
  17428. // Highlight Layer
  17429. if (renderhighlights) {
  17430. engine.setDepthBuffer(false);
  17431. for (var i = 0; i < this.highlightLayers.length; i++) {
  17432. if (this.highlightLayers[i].shouldRender()) {
  17433. this.highlightLayers[i].render();
  17434. }
  17435. }
  17436. engine.setDepthBuffer(true);
  17437. }
  17438. this._renderDuration.endMonitoring(false);
  17439. // Finalize frame
  17440. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17441. // Update camera
  17442. this.activeCamera._updateFromScene();
  17443. // Reset some special arrays
  17444. this._renderTargets.reset();
  17445. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17446. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17447. };
  17448. Scene.prototype._processSubCameras = function (camera) {
  17449. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17450. this._renderForCamera(camera);
  17451. return;
  17452. }
  17453. // rig cameras
  17454. for (var index = 0; index < camera._rigCameras.length; index++) {
  17455. this._renderForCamera(camera._rigCameras[index]);
  17456. }
  17457. this.activeCamera = camera;
  17458. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17459. // Update camera
  17460. this.activeCamera._updateFromScene();
  17461. };
  17462. Scene.prototype._checkIntersections = function () {
  17463. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17464. var sourceMesh = this._meshesForIntersections.data[index];
  17465. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17466. var action = sourceMesh.actionManager.actions[actionIndex];
  17467. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17468. var parameters = action.getTriggerParameter();
  17469. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17470. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17471. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17472. if (areIntersecting && currentIntersectionInProgress === -1) {
  17473. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17474. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17475. sourceMesh._intersectionsInProgress.push(otherMesh);
  17476. }
  17477. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17478. sourceMesh._intersectionsInProgress.push(otherMesh);
  17479. }
  17480. }
  17481. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17482. //They intersected, and now they don't.
  17483. //is this trigger an exit trigger? execute an event.
  17484. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17485. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17486. }
  17487. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17488. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17489. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17490. }
  17491. }
  17492. }
  17493. }
  17494. }
  17495. };
  17496. Scene.prototype.render = function () {
  17497. if (this.isDisposed) {
  17498. return;
  17499. }
  17500. this._lastFrameDuration.beginMonitoring();
  17501. this._particlesDuration.fetchNewFrame();
  17502. this._spritesDuration.fetchNewFrame();
  17503. this._activeParticles.fetchNewFrame();
  17504. this._renderDuration.fetchNewFrame();
  17505. this._renderTargetsDuration.fetchNewFrame();
  17506. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17507. this._totalVertices.fetchNewFrame();
  17508. this._activeIndices.fetchNewFrame();
  17509. this._activeBones.fetchNewFrame();
  17510. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17511. this._meshesForIntersections.reset();
  17512. this.resetCachedMaterial();
  17513. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17514. // Actions
  17515. if (this.actionManager) {
  17516. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17517. }
  17518. //Simplification Queue
  17519. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17520. this.simplificationQueue.executeNext();
  17521. }
  17522. // Animations
  17523. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17524. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17525. this._animate();
  17526. // Physics
  17527. if (this._physicsEngine) {
  17528. BABYLON.Tools.StartPerformanceCounter("Physics");
  17529. this._physicsEngine._step(deltaTime / 1000.0);
  17530. BABYLON.Tools.EndPerformanceCounter("Physics");
  17531. }
  17532. // Before render
  17533. this.onBeforeRenderObservable.notifyObservers(this);
  17534. // Customs render targets
  17535. this._renderTargetsDuration.beginMonitoring();
  17536. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17537. var engine = this.getEngine();
  17538. var currentActiveCamera = this.activeCamera;
  17539. if (this.renderTargetsEnabled) {
  17540. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17541. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17542. var renderTarget = this.customRenderTargets[customIndex];
  17543. if (renderTarget._shouldRender()) {
  17544. this._renderId++;
  17545. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17546. if (!this.activeCamera)
  17547. throw new Error("Active camera not set");
  17548. // Viewport
  17549. engine.setViewport(this.activeCamera.viewport);
  17550. // Camera
  17551. this.updateTransformMatrix();
  17552. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17553. }
  17554. }
  17555. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17556. this._renderId++;
  17557. }
  17558. if (this.offscreenRenderTarget) {
  17559. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17560. }
  17561. else {
  17562. // Restore back buffer
  17563. if (this.customRenderTargets.length > 0) {
  17564. engine.restoreDefaultFramebuffer();
  17565. }
  17566. }
  17567. this._renderTargetsDuration.endMonitoring();
  17568. this.activeCamera = currentActiveCamera;
  17569. // Procedural textures
  17570. if (this.proceduralTexturesEnabled) {
  17571. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17572. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17573. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17574. if (proceduralTexture._shouldRender()) {
  17575. proceduralTexture.render();
  17576. }
  17577. }
  17578. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17579. }
  17580. // Clear
  17581. if (this.autoClearDepthAndStencil || this.autoClear) {
  17582. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17583. }
  17584. // Shadows
  17585. if (this.shadowsEnabled) {
  17586. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17587. var light = this.lights[lightIndex];
  17588. var shadowGenerator = light.getShadowGenerator();
  17589. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17590. var shadowMap = shadowGenerator.getShadowMap();
  17591. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17592. this._renderTargets.push(shadowMap);
  17593. }
  17594. }
  17595. }
  17596. }
  17597. // Depth renderer
  17598. if (this._depthRenderer) {
  17599. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17600. }
  17601. // Geometry renderer
  17602. if (this._geometryBufferRenderer) {
  17603. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17604. }
  17605. // RenderPipeline
  17606. if (this._postProcessRenderPipelineManager) {
  17607. this._postProcessRenderPipelineManager.update();
  17608. }
  17609. // Multi-cameras?
  17610. if (this.activeCameras.length > 0) {
  17611. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17612. if (cameraIndex > 0) {
  17613. this._engine.clear(null, false, true, true);
  17614. }
  17615. this._processSubCameras(this.activeCameras[cameraIndex]);
  17616. }
  17617. }
  17618. else {
  17619. if (!this.activeCamera) {
  17620. throw new Error("No camera defined");
  17621. }
  17622. this._processSubCameras(this.activeCamera);
  17623. }
  17624. // Intersection checks
  17625. this._checkIntersections();
  17626. // Update the audio listener attached to the camera
  17627. if (BABYLON.AudioEngine) {
  17628. this._updateAudioParameters();
  17629. }
  17630. // After render
  17631. if (this.afterRender) {
  17632. this.afterRender();
  17633. }
  17634. this.onAfterRenderObservable.notifyObservers(this);
  17635. // Cleaning
  17636. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17637. this._toBeDisposed.data[index].dispose();
  17638. this._toBeDisposed[index] = null;
  17639. }
  17640. this._toBeDisposed.reset();
  17641. if (this.dumpNextRenderTargets) {
  17642. this.dumpNextRenderTargets = false;
  17643. }
  17644. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17645. this._lastFrameDuration.endMonitoring();
  17646. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17647. this._totalLightsCounter.addCount(this.lights.length, true);
  17648. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17649. this._totalTexturesCounter.addCount(this.textures.length, true);
  17650. this._activeBones.addCount(0, true);
  17651. this._activeIndices.addCount(0, true);
  17652. this._activeParticles.addCount(0, true);
  17653. };
  17654. Scene.prototype._updateAudioParameters = function () {
  17655. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17656. return;
  17657. }
  17658. var listeningCamera;
  17659. var audioEngine = BABYLON.Engine.audioEngine;
  17660. if (this.activeCameras.length > 0) {
  17661. listeningCamera = this.activeCameras[0];
  17662. }
  17663. else {
  17664. listeningCamera = this.activeCamera;
  17665. }
  17666. if (listeningCamera && audioEngine.canUseWebAudio) {
  17667. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17668. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17669. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17670. cameraDirection.normalize();
  17671. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17672. var i;
  17673. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17674. var sound = this.mainSoundTrack.soundCollection[i];
  17675. if (sound.useCustomAttenuation) {
  17676. sound.updateDistanceFromListener();
  17677. }
  17678. }
  17679. for (i = 0; i < this.soundTracks.length; i++) {
  17680. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17681. sound = this.soundTracks[i].soundCollection[j];
  17682. if (sound.useCustomAttenuation) {
  17683. sound.updateDistanceFromListener();
  17684. }
  17685. }
  17686. }
  17687. }
  17688. };
  17689. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17690. // Audio
  17691. get: function () {
  17692. return this._audioEnabled;
  17693. },
  17694. set: function (value) {
  17695. this._audioEnabled = value;
  17696. if (BABYLON.AudioEngine) {
  17697. if (this._audioEnabled) {
  17698. this._enableAudio();
  17699. }
  17700. else {
  17701. this._disableAudio();
  17702. }
  17703. }
  17704. },
  17705. enumerable: true,
  17706. configurable: true
  17707. });
  17708. Scene.prototype._disableAudio = function () {
  17709. var i;
  17710. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17711. this.mainSoundTrack.soundCollection[i].pause();
  17712. }
  17713. for (i = 0; i < this.soundTracks.length; i++) {
  17714. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17715. this.soundTracks[i].soundCollection[j].pause();
  17716. }
  17717. }
  17718. };
  17719. Scene.prototype._enableAudio = function () {
  17720. var i;
  17721. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17722. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17723. this.mainSoundTrack.soundCollection[i].play();
  17724. }
  17725. }
  17726. for (i = 0; i < this.soundTracks.length; i++) {
  17727. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17728. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17729. this.soundTracks[i].soundCollection[j].play();
  17730. }
  17731. }
  17732. }
  17733. };
  17734. Object.defineProperty(Scene.prototype, "headphone", {
  17735. get: function () {
  17736. return this._headphone;
  17737. },
  17738. set: function (value) {
  17739. this._headphone = value;
  17740. if (BABYLON.AudioEngine) {
  17741. if (this._headphone) {
  17742. this._switchAudioModeForHeadphones();
  17743. }
  17744. else {
  17745. this._switchAudioModeForNormalSpeakers();
  17746. }
  17747. }
  17748. },
  17749. enumerable: true,
  17750. configurable: true
  17751. });
  17752. Scene.prototype._switchAudioModeForHeadphones = function () {
  17753. this.mainSoundTrack.switchPanningModelToHRTF();
  17754. for (var i = 0; i < this.soundTracks.length; i++) {
  17755. this.soundTracks[i].switchPanningModelToHRTF();
  17756. }
  17757. };
  17758. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17759. this.mainSoundTrack.switchPanningModelToEqualPower();
  17760. for (var i = 0; i < this.soundTracks.length; i++) {
  17761. this.soundTracks[i].switchPanningModelToEqualPower();
  17762. }
  17763. };
  17764. Scene.prototype.enableDepthRenderer = function () {
  17765. if (this._depthRenderer) {
  17766. return this._depthRenderer;
  17767. }
  17768. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17769. return this._depthRenderer;
  17770. };
  17771. Scene.prototype.disableDepthRenderer = function () {
  17772. if (!this._depthRenderer) {
  17773. return;
  17774. }
  17775. this._depthRenderer.dispose();
  17776. this._depthRenderer = null;
  17777. };
  17778. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17779. if (ratio === void 0) { ratio = 1; }
  17780. if (this._geometryBufferRenderer) {
  17781. return this._geometryBufferRenderer;
  17782. }
  17783. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  17784. if (!this._geometryBufferRenderer.isSupported) {
  17785. this._geometryBufferRenderer = null;
  17786. }
  17787. return this._geometryBufferRenderer;
  17788. };
  17789. Scene.prototype.disableGeometryBufferRenderer = function () {
  17790. if (!this._geometryBufferRenderer) {
  17791. return;
  17792. }
  17793. this._geometryBufferRenderer.dispose();
  17794. this._geometryBufferRenderer = null;
  17795. };
  17796. Scene.prototype.freezeMaterials = function () {
  17797. for (var i = 0; i < this.materials.length; i++) {
  17798. this.materials[i].freeze();
  17799. }
  17800. };
  17801. Scene.prototype.unfreezeMaterials = function () {
  17802. for (var i = 0; i < this.materials.length; i++) {
  17803. this.materials[i].unfreeze();
  17804. }
  17805. };
  17806. Scene.prototype.dispose = function () {
  17807. this.beforeRender = null;
  17808. this.afterRender = null;
  17809. this.skeletons = [];
  17810. this.morphTargetManagers = [];
  17811. this.importedMeshesFiles = new Array();
  17812. if (this._depthRenderer) {
  17813. this._depthRenderer.dispose();
  17814. }
  17815. // Smart arrays
  17816. if (this.activeCamera) {
  17817. this.activeCamera._activeMeshes.dispose();
  17818. this.activeCamera = null;
  17819. }
  17820. this._activeMeshes.dispose();
  17821. this._renderingManager.dispose();
  17822. this._processedMaterials.dispose();
  17823. this._activeParticleSystems.dispose();
  17824. this._activeSkeletons.dispose();
  17825. this._softwareSkinnedMeshes.dispose();
  17826. if (this._boundingBoxRenderer) {
  17827. this._boundingBoxRenderer.dispose();
  17828. }
  17829. this._meshesForIntersections.dispose();
  17830. this._toBeDisposed.dispose();
  17831. // Debug layer
  17832. if (this._debugLayer) {
  17833. this._debugLayer.hide();
  17834. }
  17835. // Events
  17836. this.onDisposeObservable.notifyObservers(this);
  17837. this.onDisposeObservable.clear();
  17838. this.onBeforeRenderObservable.clear();
  17839. this.onAfterRenderObservable.clear();
  17840. this.detachControl();
  17841. // Release sounds & sounds tracks
  17842. if (BABYLON.AudioEngine) {
  17843. this.disposeSounds();
  17844. }
  17845. // Detach cameras
  17846. var canvas = this._engine.getRenderingCanvas();
  17847. var index;
  17848. for (index = 0; index < this.cameras.length; index++) {
  17849. this.cameras[index].detachControl(canvas);
  17850. }
  17851. // Release lights
  17852. while (this.lights.length) {
  17853. this.lights[0].dispose();
  17854. }
  17855. // Release meshes
  17856. while (this.meshes.length) {
  17857. this.meshes[0].dispose(true);
  17858. }
  17859. // Release cameras
  17860. while (this.cameras.length) {
  17861. this.cameras[0].dispose();
  17862. }
  17863. // Release materials
  17864. while (this.materials.length) {
  17865. this.materials[0].dispose();
  17866. }
  17867. // Release particles
  17868. while (this.particleSystems.length) {
  17869. this.particleSystems[0].dispose();
  17870. }
  17871. // Release sprites
  17872. while (this.spriteManagers.length) {
  17873. this.spriteManagers[0].dispose();
  17874. }
  17875. // Release layers
  17876. while (this.layers.length) {
  17877. this.layers[0].dispose();
  17878. }
  17879. while (this.highlightLayers.length) {
  17880. this.highlightLayers[0].dispose();
  17881. }
  17882. // Release textures
  17883. while (this.textures.length) {
  17884. this.textures[0].dispose();
  17885. }
  17886. // Release UBO
  17887. this._sceneUbo.dispose();
  17888. // Post-processes
  17889. this.postProcessManager.dispose();
  17890. // Physics
  17891. if (this._physicsEngine) {
  17892. this.disablePhysicsEngine();
  17893. }
  17894. // Remove from engine
  17895. index = this._engine.scenes.indexOf(this);
  17896. if (index > -1) {
  17897. this._engine.scenes.splice(index, 1);
  17898. }
  17899. this._engine.wipeCaches();
  17900. this._engine = null;
  17901. };
  17902. Object.defineProperty(Scene.prototype, "isDisposed", {
  17903. get: function () {
  17904. return !this._engine;
  17905. },
  17906. enumerable: true,
  17907. configurable: true
  17908. });
  17909. // Release sounds & sounds tracks
  17910. Scene.prototype.disposeSounds = function () {
  17911. this.mainSoundTrack.dispose();
  17912. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17913. this.soundTracks[scIndex].dispose();
  17914. }
  17915. };
  17916. // Octrees
  17917. Scene.prototype.getWorldExtends = function () {
  17918. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17919. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17920. for (var index = 0; index < this.meshes.length; index++) {
  17921. var mesh = this.meshes[index];
  17922. mesh.computeWorldMatrix(true);
  17923. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17924. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17925. BABYLON.Tools.CheckExtends(minBox, min, max);
  17926. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17927. }
  17928. return {
  17929. min: min,
  17930. max: max
  17931. };
  17932. };
  17933. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17934. if (maxCapacity === void 0) { maxCapacity = 64; }
  17935. if (maxDepth === void 0) { maxDepth = 2; }
  17936. if (!this._selectionOctree) {
  17937. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17938. }
  17939. var worldExtends = this.getWorldExtends();
  17940. // Update octree
  17941. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17942. return this._selectionOctree;
  17943. };
  17944. // Picking
  17945. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17946. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17947. var engine = this._engine;
  17948. if (!camera) {
  17949. if (!this.activeCamera)
  17950. throw new Error("Active camera not set");
  17951. camera = this.activeCamera;
  17952. }
  17953. var cameraViewport = camera.viewport;
  17954. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17955. // Moving coordinates to local viewport world
  17956. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17957. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17958. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17959. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17960. };
  17961. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17962. if (!BABYLON.PickingInfo) {
  17963. return null;
  17964. }
  17965. var engine = this._engine;
  17966. if (!camera) {
  17967. if (!this.activeCamera)
  17968. throw new Error("Active camera not set");
  17969. camera = this.activeCamera;
  17970. }
  17971. var cameraViewport = camera.viewport;
  17972. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17973. var identity = BABYLON.Matrix.Identity();
  17974. // Moving coordinates to local viewport world
  17975. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17976. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17977. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17978. };
  17979. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17980. if (!BABYLON.PickingInfo) {
  17981. return null;
  17982. }
  17983. var pickingInfo = null;
  17984. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17985. var mesh = this.meshes[meshIndex];
  17986. if (predicate) {
  17987. if (!predicate(mesh)) {
  17988. continue;
  17989. }
  17990. }
  17991. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17992. continue;
  17993. }
  17994. var world = mesh.getWorldMatrix();
  17995. var ray = rayFunction(world);
  17996. var result = mesh.intersects(ray, fastCheck);
  17997. if (!result || !result.hit)
  17998. continue;
  17999. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18000. continue;
  18001. pickingInfo = result;
  18002. if (fastCheck) {
  18003. break;
  18004. }
  18005. }
  18006. return pickingInfo || new BABYLON.PickingInfo();
  18007. };
  18008. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18009. if (!BABYLON.PickingInfo) {
  18010. return null;
  18011. }
  18012. var pickingInfos = new Array();
  18013. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18014. var mesh = this.meshes[meshIndex];
  18015. if (predicate) {
  18016. if (!predicate(mesh)) {
  18017. continue;
  18018. }
  18019. }
  18020. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18021. continue;
  18022. }
  18023. var world = mesh.getWorldMatrix();
  18024. var ray = rayFunction(world);
  18025. var result = mesh.intersects(ray, false);
  18026. if (!result || !result.hit)
  18027. continue;
  18028. pickingInfos.push(result);
  18029. }
  18030. return pickingInfos;
  18031. };
  18032. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18033. if (!BABYLON.PickingInfo) {
  18034. return null;
  18035. }
  18036. var pickingInfo = null;
  18037. camera = camera || this.activeCamera;
  18038. if (this.spriteManagers.length > 0) {
  18039. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18040. var spriteManager = this.spriteManagers[spriteIndex];
  18041. if (!spriteManager.isPickable) {
  18042. continue;
  18043. }
  18044. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18045. if (!result || !result.hit)
  18046. continue;
  18047. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18048. continue;
  18049. pickingInfo = result;
  18050. if (fastCheck) {
  18051. break;
  18052. }
  18053. }
  18054. }
  18055. return pickingInfo || new BABYLON.PickingInfo();
  18056. };
  18057. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18058. /// <param name="x">X position on screen</param>
  18059. /// <param name="y">Y position on screen</param>
  18060. /// <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>
  18061. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18062. /// <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>
  18063. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18064. var _this = this;
  18065. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18066. };
  18067. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18068. /// <param name="x">X position on screen</param>
  18069. /// <param name="y">Y position on screen</param>
  18070. /// <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>
  18071. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18072. /// <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>
  18073. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18074. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18075. };
  18076. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18077. var _this = this;
  18078. return this._internalPick(function (world) {
  18079. if (!_this._pickWithRayInverseMatrix) {
  18080. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18081. }
  18082. world.invertToRef(_this._pickWithRayInverseMatrix);
  18083. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18084. }, predicate, fastCheck);
  18085. };
  18086. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18087. /// <param name="x">X position on screen</param>
  18088. /// <param name="y">Y position on screen</param>
  18089. /// <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>
  18090. /// <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>
  18091. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18092. var _this = this;
  18093. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18094. };
  18095. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18096. /// <param name="ray">Ray to use</param>
  18097. /// <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>
  18098. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18099. var _this = this;
  18100. return this._internalMultiPick(function (world) {
  18101. if (!_this._pickWithRayInverseMatrix) {
  18102. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18103. }
  18104. world.invertToRef(_this._pickWithRayInverseMatrix);
  18105. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18106. }, predicate);
  18107. };
  18108. Scene.prototype.setPointerOverMesh = function (mesh) {
  18109. if (this._pointerOverMesh === mesh) {
  18110. return;
  18111. }
  18112. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18113. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18114. }
  18115. this._pointerOverMesh = mesh;
  18116. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18117. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18118. }
  18119. };
  18120. Scene.prototype.getPointerOverMesh = function () {
  18121. return this._pointerOverMesh;
  18122. };
  18123. Scene.prototype.setPointerOverSprite = function (sprite) {
  18124. if (this._pointerOverSprite === sprite) {
  18125. return;
  18126. }
  18127. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18128. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18129. }
  18130. this._pointerOverSprite = sprite;
  18131. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18132. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18133. }
  18134. };
  18135. Scene.prototype.getPointerOverSprite = function () {
  18136. return this._pointerOverSprite;
  18137. };
  18138. // Physics
  18139. Scene.prototype.getPhysicsEngine = function () {
  18140. return this._physicsEngine;
  18141. };
  18142. /**
  18143. * Enables physics to the current scene
  18144. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18145. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18146. * @return {boolean} was the physics engine initialized
  18147. */
  18148. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18149. if (this._physicsEngine) {
  18150. return true;
  18151. }
  18152. try {
  18153. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18154. return true;
  18155. }
  18156. catch (e) {
  18157. BABYLON.Tools.Error(e.message);
  18158. return false;
  18159. }
  18160. };
  18161. Scene.prototype.disablePhysicsEngine = function () {
  18162. if (!this._physicsEngine) {
  18163. return;
  18164. }
  18165. this._physicsEngine.dispose();
  18166. this._physicsEngine = undefined;
  18167. };
  18168. Scene.prototype.isPhysicsEnabled = function () {
  18169. return this._physicsEngine !== undefined;
  18170. };
  18171. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18172. var mesh = compound.parts[0].mesh;
  18173. mesh.physicsImpostor.dispose();
  18174. mesh.physicsImpostor = null;
  18175. };
  18176. // Misc.
  18177. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18178. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18179. // Light
  18180. if (this.lights.length === 0) {
  18181. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18182. }
  18183. // Camera
  18184. if (!this.activeCamera) {
  18185. var worldExtends = this.getWorldExtends();
  18186. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18187. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18188. var camera;
  18189. var radius = worldSize.length() * 1.5;
  18190. if (createArcRotateCamera) {
  18191. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18192. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18193. arcRotateCamera.wheelPrecision = 100 / radius;
  18194. camera = arcRotateCamera;
  18195. }
  18196. else {
  18197. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18198. freeCamera.setTarget(worldCenter);
  18199. camera = freeCamera;
  18200. }
  18201. camera.minZ = radius * 0.01;
  18202. camera.maxZ = radius * 100;
  18203. camera.speed = radius * 0.2;
  18204. this.activeCamera = camera;
  18205. }
  18206. };
  18207. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18208. if (pbr === void 0) { pbr = false; }
  18209. if (environmentTexture) {
  18210. this.environmentTexture = environmentTexture;
  18211. }
  18212. if (!this.environmentTexture) {
  18213. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18214. return;
  18215. }
  18216. if (!this.environmentTexture) {
  18217. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18218. return;
  18219. }
  18220. // Skybox
  18221. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18222. if (pbr) {
  18223. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18224. hdrSkyboxMaterial.backFaceCulling = false;
  18225. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18226. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18227. hdrSkyboxMaterial.microSurface = 1.0;
  18228. hdrSkyboxMaterial.disableLighting = true;
  18229. hdrSkybox.infiniteDistance = true;
  18230. hdrSkybox.material = hdrSkyboxMaterial;
  18231. }
  18232. else {
  18233. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18234. skyboxMaterial.backFaceCulling = false;
  18235. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18236. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18237. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18238. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18239. skyboxMaterial.disableLighting = true;
  18240. hdrSkybox.infiniteDistance = true;
  18241. hdrSkybox.material = skyboxMaterial;
  18242. }
  18243. return hdrSkybox;
  18244. };
  18245. // Tags
  18246. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18247. if (tagsQuery === undefined) {
  18248. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18249. return list;
  18250. }
  18251. var listByTags = [];
  18252. forEach = forEach || (function (item) { return; });
  18253. for (var i in list) {
  18254. var item = list[i];
  18255. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18256. listByTags.push(item);
  18257. forEach(item);
  18258. }
  18259. }
  18260. return listByTags;
  18261. };
  18262. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18263. return this._getByTags(this.meshes, tagsQuery, forEach);
  18264. };
  18265. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18266. return this._getByTags(this.cameras, tagsQuery, forEach);
  18267. };
  18268. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18269. return this._getByTags(this.lights, tagsQuery, forEach);
  18270. };
  18271. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18272. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18273. };
  18274. /**
  18275. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18276. * This allowed control for front to back rendering or reversly depending of the special needs.
  18277. *
  18278. * @param renderingGroupId The rendering group id corresponding to its index
  18279. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18280. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18281. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18282. */
  18283. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18284. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18285. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18286. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18287. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18288. };
  18289. /**
  18290. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18291. *
  18292. * @param renderingGroupId The rendering group id corresponding to its index
  18293. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18294. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18295. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18296. */
  18297. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18298. if (depth === void 0) { depth = true; }
  18299. if (stencil === void 0) { stencil = true; }
  18300. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18301. };
  18302. /**
  18303. * Will flag all materials as dirty to trigger new shader compilation
  18304. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18305. */
  18306. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18307. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18308. var material = _a[_i];
  18309. if (predicate && !predicate(material)) {
  18310. continue;
  18311. }
  18312. material.markAsDirty(flag);
  18313. }
  18314. };
  18315. return Scene;
  18316. }());
  18317. // Statics
  18318. Scene._FOGMODE_NONE = 0;
  18319. Scene._FOGMODE_EXP = 1;
  18320. Scene._FOGMODE_EXP2 = 2;
  18321. Scene._FOGMODE_LINEAR = 3;
  18322. Scene.MinDeltaTime = 1.0;
  18323. Scene.MaxDeltaTime = 1000.0;
  18324. Scene.DragMovementThreshold = 10; // in pixels
  18325. Scene.LongPressDelay = 500; // in milliseconds
  18326. Scene.DoubleClickDelay = 300; // in milliseconds
  18327. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18328. BABYLON.Scene = Scene;
  18329. })(BABYLON || (BABYLON = {}));
  18330. //# sourceMappingURL=babylon.scene.js.map
  18331. var BABYLON;
  18332. (function (BABYLON) {
  18333. var Buffer = (function () {
  18334. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18335. if (engine instanceof BABYLON.Mesh) {
  18336. this._engine = engine.getScene().getEngine();
  18337. }
  18338. else {
  18339. this._engine = engine;
  18340. }
  18341. this._updatable = updatable;
  18342. this._data = data;
  18343. this._strideSize = stride;
  18344. if (!postponeInternalCreation) {
  18345. this.create();
  18346. }
  18347. this._instanced = instanced;
  18348. }
  18349. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18350. // a lot of these parameters are ignored as they are overriden by the buffer
  18351. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18352. };
  18353. // Properties
  18354. Buffer.prototype.isUpdatable = function () {
  18355. return this._updatable;
  18356. };
  18357. Buffer.prototype.getData = function () {
  18358. return this._data;
  18359. };
  18360. Buffer.prototype.getBuffer = function () {
  18361. return this._buffer;
  18362. };
  18363. Buffer.prototype.getStrideSize = function () {
  18364. return this._strideSize;
  18365. };
  18366. Buffer.prototype.getIsInstanced = function () {
  18367. return this._instanced;
  18368. };
  18369. // Methods
  18370. Buffer.prototype.create = function (data) {
  18371. if (!data && this._buffer) {
  18372. return; // nothing to do
  18373. }
  18374. data = data || this._data;
  18375. if (!this._buffer) {
  18376. if (this._updatable) {
  18377. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18378. this._data = data;
  18379. }
  18380. else {
  18381. this._buffer = this._engine.createVertexBuffer(data);
  18382. }
  18383. }
  18384. else if (this._updatable) {
  18385. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18386. this._data = data;
  18387. }
  18388. };
  18389. Buffer.prototype.update = function (data) {
  18390. this.create(data);
  18391. };
  18392. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18393. if (!this._buffer) {
  18394. return;
  18395. }
  18396. if (this._updatable) {
  18397. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18398. this._data = null;
  18399. }
  18400. };
  18401. Buffer.prototype.dispose = function () {
  18402. if (!this._buffer) {
  18403. return;
  18404. }
  18405. if (this._engine._releaseBuffer(this._buffer)) {
  18406. this._buffer = null;
  18407. }
  18408. };
  18409. return Buffer;
  18410. }());
  18411. BABYLON.Buffer = Buffer;
  18412. })(BABYLON || (BABYLON = {}));
  18413. //# sourceMappingURL=babylon.buffer.js.map
  18414. var BABYLON;
  18415. (function (BABYLON) {
  18416. var VertexBuffer = (function () {
  18417. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18418. if (!stride) {
  18419. // Deduce stride from kind
  18420. switch (kind) {
  18421. case VertexBuffer.PositionKind:
  18422. stride = 3;
  18423. break;
  18424. case VertexBuffer.NormalKind:
  18425. stride = 3;
  18426. break;
  18427. case VertexBuffer.UVKind:
  18428. case VertexBuffer.UV2Kind:
  18429. case VertexBuffer.UV3Kind:
  18430. case VertexBuffer.UV4Kind:
  18431. case VertexBuffer.UV5Kind:
  18432. case VertexBuffer.UV6Kind:
  18433. stride = 2;
  18434. break;
  18435. case VertexBuffer.TangentKind:
  18436. case VertexBuffer.ColorKind:
  18437. stride = 4;
  18438. break;
  18439. case VertexBuffer.MatricesIndicesKind:
  18440. case VertexBuffer.MatricesIndicesExtraKind:
  18441. stride = 4;
  18442. break;
  18443. case VertexBuffer.MatricesWeightsKind:
  18444. case VertexBuffer.MatricesWeightsExtraKind:
  18445. stride = 4;
  18446. break;
  18447. }
  18448. }
  18449. if (data instanceof BABYLON.Buffer) {
  18450. if (!stride) {
  18451. stride = data.getStrideSize();
  18452. }
  18453. this._buffer = data;
  18454. this._ownsBuffer = false;
  18455. }
  18456. else {
  18457. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18458. this._ownsBuffer = true;
  18459. }
  18460. this._stride = stride;
  18461. this._offset = offset ? offset : 0;
  18462. this._size = size ? size : stride;
  18463. this._kind = kind;
  18464. }
  18465. /**
  18466. * Returns the kind of the VertexBuffer (string).
  18467. */
  18468. VertexBuffer.prototype.getKind = function () {
  18469. return this._kind;
  18470. };
  18471. // Properties
  18472. /**
  18473. * Boolean : is the VertexBuffer updatable ?
  18474. */
  18475. VertexBuffer.prototype.isUpdatable = function () {
  18476. return this._buffer.isUpdatable();
  18477. };
  18478. /**
  18479. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18480. */
  18481. VertexBuffer.prototype.getData = function () {
  18482. return this._buffer.getData();
  18483. };
  18484. /**
  18485. * Returns the WebGLBuffer associated to the VertexBuffer.
  18486. */
  18487. VertexBuffer.prototype.getBuffer = function () {
  18488. return this._buffer.getBuffer();
  18489. };
  18490. /**
  18491. * Returns the stride of the VertexBuffer (integer).
  18492. */
  18493. VertexBuffer.prototype.getStrideSize = function () {
  18494. return this._stride;
  18495. };
  18496. /**
  18497. * Returns the offset (integer).
  18498. */
  18499. VertexBuffer.prototype.getOffset = function () {
  18500. return this._offset;
  18501. };
  18502. /**
  18503. * Returns the VertexBuffer total size (integer).
  18504. */
  18505. VertexBuffer.prototype.getSize = function () {
  18506. return this._size;
  18507. };
  18508. /**
  18509. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18510. */
  18511. VertexBuffer.prototype.getIsInstanced = function () {
  18512. return this._buffer.getIsInstanced();
  18513. };
  18514. // Methods
  18515. /**
  18516. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18517. * Returns the created WebGLBuffer.
  18518. */
  18519. VertexBuffer.prototype.create = function (data) {
  18520. return this._buffer.create(data);
  18521. };
  18522. /**
  18523. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18524. * Returns the updated WebGLBuffer.
  18525. */
  18526. VertexBuffer.prototype.update = function (data) {
  18527. return this._buffer.update(data);
  18528. };
  18529. /**
  18530. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18531. * Returns the directly updated WebGLBuffer.
  18532. */
  18533. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18534. return this._buffer.updateDirectly(data, offset);
  18535. };
  18536. /**
  18537. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18538. */
  18539. VertexBuffer.prototype.dispose = function () {
  18540. if (this._ownsBuffer) {
  18541. this._buffer.dispose();
  18542. }
  18543. };
  18544. Object.defineProperty(VertexBuffer, "PositionKind", {
  18545. get: function () {
  18546. return VertexBuffer._PositionKind;
  18547. },
  18548. enumerable: true,
  18549. configurable: true
  18550. });
  18551. Object.defineProperty(VertexBuffer, "NormalKind", {
  18552. get: function () {
  18553. return VertexBuffer._NormalKind;
  18554. },
  18555. enumerable: true,
  18556. configurable: true
  18557. });
  18558. Object.defineProperty(VertexBuffer, "TangentKind", {
  18559. get: function () {
  18560. return VertexBuffer._TangentKind;
  18561. },
  18562. enumerable: true,
  18563. configurable: true
  18564. });
  18565. Object.defineProperty(VertexBuffer, "UVKind", {
  18566. get: function () {
  18567. return VertexBuffer._UVKind;
  18568. },
  18569. enumerable: true,
  18570. configurable: true
  18571. });
  18572. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18573. get: function () {
  18574. return VertexBuffer._UV2Kind;
  18575. },
  18576. enumerable: true,
  18577. configurable: true
  18578. });
  18579. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18580. get: function () {
  18581. return VertexBuffer._UV3Kind;
  18582. },
  18583. enumerable: true,
  18584. configurable: true
  18585. });
  18586. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18587. get: function () {
  18588. return VertexBuffer._UV4Kind;
  18589. },
  18590. enumerable: true,
  18591. configurable: true
  18592. });
  18593. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18594. get: function () {
  18595. return VertexBuffer._UV5Kind;
  18596. },
  18597. enumerable: true,
  18598. configurable: true
  18599. });
  18600. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18601. get: function () {
  18602. return VertexBuffer._UV6Kind;
  18603. },
  18604. enumerable: true,
  18605. configurable: true
  18606. });
  18607. Object.defineProperty(VertexBuffer, "ColorKind", {
  18608. get: function () {
  18609. return VertexBuffer._ColorKind;
  18610. },
  18611. enumerable: true,
  18612. configurable: true
  18613. });
  18614. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18615. get: function () {
  18616. return VertexBuffer._MatricesIndicesKind;
  18617. },
  18618. enumerable: true,
  18619. configurable: true
  18620. });
  18621. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18622. get: function () {
  18623. return VertexBuffer._MatricesWeightsKind;
  18624. },
  18625. enumerable: true,
  18626. configurable: true
  18627. });
  18628. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18629. get: function () {
  18630. return VertexBuffer._MatricesIndicesExtraKind;
  18631. },
  18632. enumerable: true,
  18633. configurable: true
  18634. });
  18635. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18636. get: function () {
  18637. return VertexBuffer._MatricesWeightsExtraKind;
  18638. },
  18639. enumerable: true,
  18640. configurable: true
  18641. });
  18642. return VertexBuffer;
  18643. }());
  18644. // Enums
  18645. VertexBuffer._PositionKind = "position";
  18646. VertexBuffer._NormalKind = "normal";
  18647. VertexBuffer._TangentKind = "tangent";
  18648. VertexBuffer._UVKind = "uv";
  18649. VertexBuffer._UV2Kind = "uv2";
  18650. VertexBuffer._UV3Kind = "uv3";
  18651. VertexBuffer._UV4Kind = "uv4";
  18652. VertexBuffer._UV5Kind = "uv5";
  18653. VertexBuffer._UV6Kind = "uv6";
  18654. VertexBuffer._ColorKind = "color";
  18655. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18656. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18657. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18658. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18659. BABYLON.VertexBuffer = VertexBuffer;
  18660. })(BABYLON || (BABYLON = {}));
  18661. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18662. var BABYLON;
  18663. (function (BABYLON) {
  18664. var BaseTexture = (function () {
  18665. function BaseTexture(scene) {
  18666. this._hasAlpha = false;
  18667. this.getAlphaFromRGB = false;
  18668. this.level = 1;
  18669. this.coordinatesIndex = 0;
  18670. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18671. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18672. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18673. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18674. this.isCube = false;
  18675. this.isRenderTarget = false;
  18676. this.animations = new Array();
  18677. /**
  18678. * An event triggered when the texture is disposed.
  18679. * @type {BABYLON.Observable}
  18680. */
  18681. this.onDisposeObservable = new BABYLON.Observable();
  18682. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18683. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18684. this._scene.textures.push(this);
  18685. this._uid = null;
  18686. }
  18687. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18688. get: function () {
  18689. return this._hasAlpha;
  18690. },
  18691. set: function (value) {
  18692. if (this._hasAlpha === value) {
  18693. return;
  18694. }
  18695. this._hasAlpha = value;
  18696. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18697. },
  18698. enumerable: true,
  18699. configurable: true
  18700. });
  18701. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18702. get: function () {
  18703. return this._coordinatesMode;
  18704. },
  18705. set: function (value) {
  18706. if (this._coordinatesMode === value) {
  18707. return;
  18708. }
  18709. this._coordinatesMode = value;
  18710. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18711. },
  18712. enumerable: true,
  18713. configurable: true
  18714. });
  18715. Object.defineProperty(BaseTexture.prototype, "uid", {
  18716. get: function () {
  18717. if (!this._uid) {
  18718. this._uid = BABYLON.Tools.RandomId();
  18719. }
  18720. return this._uid;
  18721. },
  18722. enumerable: true,
  18723. configurable: true
  18724. });
  18725. BaseTexture.prototype.toString = function () {
  18726. return this.name;
  18727. };
  18728. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18729. set: function (callback) {
  18730. if (this._onDisposeObserver) {
  18731. this.onDisposeObservable.remove(this._onDisposeObserver);
  18732. }
  18733. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18734. },
  18735. enumerable: true,
  18736. configurable: true
  18737. });
  18738. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18739. get: function () {
  18740. return true;
  18741. },
  18742. enumerable: true,
  18743. configurable: true
  18744. });
  18745. BaseTexture.prototype.getScene = function () {
  18746. return this._scene;
  18747. };
  18748. BaseTexture.prototype.getTextureMatrix = function () {
  18749. return null;
  18750. };
  18751. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18752. return null;
  18753. };
  18754. BaseTexture.prototype.getInternalTexture = function () {
  18755. return this._texture;
  18756. };
  18757. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18758. return !this.isBlocking || this.isReady();
  18759. };
  18760. BaseTexture.prototype.isReady = function () {
  18761. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18762. this.delayLoad();
  18763. return false;
  18764. }
  18765. if (this._texture) {
  18766. return this._texture.isReady;
  18767. }
  18768. return false;
  18769. };
  18770. BaseTexture.prototype.getSize = function () {
  18771. if (this._texture._width) {
  18772. return new BABYLON.Size(this._texture._width, this._texture._height);
  18773. }
  18774. if (this._texture._size) {
  18775. return new BABYLON.Size(this._texture._size, this._texture._size);
  18776. }
  18777. return BABYLON.Size.Zero();
  18778. };
  18779. BaseTexture.prototype.getBaseSize = function () {
  18780. if (!this.isReady() || !this._texture)
  18781. return BABYLON.Size.Zero();
  18782. if (this._texture._size) {
  18783. return new BABYLON.Size(this._texture._size, this._texture._size);
  18784. }
  18785. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  18786. };
  18787. BaseTexture.prototype.scale = function (ratio) {
  18788. };
  18789. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18790. get: function () {
  18791. return false;
  18792. },
  18793. enumerable: true,
  18794. configurable: true
  18795. });
  18796. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18797. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18798. for (var index = 0; index < texturesCache.length; index++) {
  18799. var texturesCacheEntry = texturesCache[index];
  18800. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18801. texturesCache.splice(index, 1);
  18802. return;
  18803. }
  18804. }
  18805. };
  18806. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18807. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18808. for (var index = 0; index < texturesCache.length; index++) {
  18809. var texturesCacheEntry = texturesCache[index];
  18810. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18811. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18812. texturesCacheEntry.references++;
  18813. return texturesCacheEntry;
  18814. }
  18815. }
  18816. }
  18817. return null;
  18818. };
  18819. BaseTexture.prototype.delayLoad = function () {
  18820. };
  18821. BaseTexture.prototype.clone = function () {
  18822. return null;
  18823. };
  18824. BaseTexture.prototype.releaseInternalTexture = function () {
  18825. if (this._texture) {
  18826. this._scene.getEngine().releaseInternalTexture(this._texture);
  18827. delete this._texture;
  18828. }
  18829. };
  18830. BaseTexture.prototype.dispose = function () {
  18831. // Animations
  18832. this.getScene().stopAnimation(this);
  18833. // Remove from scene
  18834. this._scene._removePendingData(this);
  18835. var index = this._scene.textures.indexOf(this);
  18836. if (index >= 0) {
  18837. this._scene.textures.splice(index, 1);
  18838. }
  18839. if (this._texture === undefined) {
  18840. return;
  18841. }
  18842. // Release
  18843. this.releaseInternalTexture();
  18844. // Callback
  18845. this.onDisposeObservable.notifyObservers(this);
  18846. this.onDisposeObservable.clear();
  18847. };
  18848. BaseTexture.prototype.serialize = function () {
  18849. if (!this.name) {
  18850. return null;
  18851. }
  18852. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18853. // Animations
  18854. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18855. return serializationObject;
  18856. };
  18857. return BaseTexture;
  18858. }());
  18859. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  18860. __decorate([
  18861. BABYLON.serialize()
  18862. ], BaseTexture.prototype, "name", void 0);
  18863. __decorate([
  18864. BABYLON.serialize("hasAlpha")
  18865. ], BaseTexture.prototype, "_hasAlpha", void 0);
  18866. __decorate([
  18867. BABYLON.serialize()
  18868. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  18869. __decorate([
  18870. BABYLON.serialize()
  18871. ], BaseTexture.prototype, "level", void 0);
  18872. __decorate([
  18873. BABYLON.serialize()
  18874. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18875. __decorate([
  18876. BABYLON.serialize("coordinatesMode")
  18877. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  18878. __decorate([
  18879. BABYLON.serialize()
  18880. ], BaseTexture.prototype, "wrapU", void 0);
  18881. __decorate([
  18882. BABYLON.serialize()
  18883. ], BaseTexture.prototype, "wrapV", void 0);
  18884. __decorate([
  18885. BABYLON.serialize()
  18886. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  18887. __decorate([
  18888. BABYLON.serialize()
  18889. ], BaseTexture.prototype, "isCube", void 0);
  18890. __decorate([
  18891. BABYLON.serialize()
  18892. ], BaseTexture.prototype, "isRenderTarget", void 0);
  18893. BABYLON.BaseTexture = BaseTexture;
  18894. })(BABYLON || (BABYLON = {}));
  18895. //# sourceMappingURL=babylon.baseTexture.js.map
  18896. var BABYLON;
  18897. (function (BABYLON) {
  18898. var Texture = (function (_super) {
  18899. __extends(Texture, _super);
  18900. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  18901. if (noMipmap === void 0) { noMipmap = false; }
  18902. if (invertY === void 0) { invertY = true; }
  18903. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18904. if (onLoad === void 0) { onLoad = null; }
  18905. if (onError === void 0) { onError = null; }
  18906. if (buffer === void 0) { buffer = null; }
  18907. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18908. var _this = _super.call(this, scene) || this;
  18909. _this.uOffset = 0;
  18910. _this.vOffset = 0;
  18911. _this.uScale = 1.0;
  18912. _this.vScale = 1.0;
  18913. _this.uAng = 0;
  18914. _this.vAng = 0;
  18915. _this.wAng = 0;
  18916. _this._isBlocking = true;
  18917. _this.name = url;
  18918. _this.url = url;
  18919. _this._noMipmap = noMipmap;
  18920. _this._invertY = invertY;
  18921. _this._samplingMode = samplingMode;
  18922. _this._buffer = buffer;
  18923. _this._deleteBuffer = deleteBuffer;
  18924. _this._format = format;
  18925. scene = _this.getScene();
  18926. if (!url) {
  18927. return _this;
  18928. }
  18929. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  18930. var load = function () {
  18931. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  18932. _this.onLoadObservable.notifyObservers(true);
  18933. }
  18934. if (onLoad) {
  18935. onLoad();
  18936. }
  18937. if (!_this.isBlocking) {
  18938. scene.resetCachedMaterial();
  18939. }
  18940. };
  18941. if (!_this._texture) {
  18942. if (!scene.useDelayedTextureLoading) {
  18943. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  18944. if (deleteBuffer) {
  18945. delete _this._buffer;
  18946. }
  18947. }
  18948. else {
  18949. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18950. _this._delayedOnLoad = load;
  18951. _this._delayedOnError = onError;
  18952. }
  18953. }
  18954. else {
  18955. if (_this._texture.isReady) {
  18956. BABYLON.Tools.SetImmediate(function () { return load(); });
  18957. }
  18958. else {
  18959. _this._texture.onLoadedCallbacks.push(load);
  18960. }
  18961. }
  18962. return _this;
  18963. }
  18964. Object.defineProperty(Texture.prototype, "noMipmap", {
  18965. get: function () {
  18966. return this._noMipmap;
  18967. },
  18968. enumerable: true,
  18969. configurable: true
  18970. });
  18971. Object.defineProperty(Texture.prototype, "isBlocking", {
  18972. get: function () {
  18973. return this._isBlocking;
  18974. },
  18975. set: function (value) {
  18976. this._isBlocking = value;
  18977. },
  18978. enumerable: true,
  18979. configurable: true
  18980. });
  18981. Texture.prototype.delayLoad = function () {
  18982. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18983. return;
  18984. }
  18985. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18986. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  18987. if (!this._texture) {
  18988. 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);
  18989. if (this._deleteBuffer) {
  18990. delete this._buffer;
  18991. }
  18992. }
  18993. };
  18994. Texture.prototype.updateSamplingMode = function (samplingMode) {
  18995. if (!this._texture) {
  18996. return;
  18997. }
  18998. this._samplingMode = samplingMode;
  18999. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19000. };
  19001. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19002. x *= this.uScale;
  19003. y *= this.vScale;
  19004. x -= 0.5 * this.uScale;
  19005. y -= 0.5 * this.vScale;
  19006. z -= 0.5;
  19007. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19008. t.x += 0.5 * this.uScale + this.uOffset;
  19009. t.y += 0.5 * this.vScale + this.vOffset;
  19010. t.z += 0.5;
  19011. };
  19012. Texture.prototype.getTextureMatrix = function () {
  19013. if (this.uOffset === this._cachedUOffset &&
  19014. this.vOffset === this._cachedVOffset &&
  19015. this.uScale === this._cachedUScale &&
  19016. this.vScale === this._cachedVScale &&
  19017. this.uAng === this._cachedUAng &&
  19018. this.vAng === this._cachedVAng &&
  19019. this.wAng === this._cachedWAng) {
  19020. return this._cachedTextureMatrix;
  19021. }
  19022. this._cachedUOffset = this.uOffset;
  19023. this._cachedVOffset = this.vOffset;
  19024. this._cachedUScale = this.uScale;
  19025. this._cachedVScale = this.vScale;
  19026. this._cachedUAng = this.uAng;
  19027. this._cachedVAng = this.vAng;
  19028. this._cachedWAng = this.wAng;
  19029. if (!this._cachedTextureMatrix) {
  19030. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19031. this._rowGenerationMatrix = new BABYLON.Matrix();
  19032. this._t0 = BABYLON.Vector3.Zero();
  19033. this._t1 = BABYLON.Vector3.Zero();
  19034. this._t2 = BABYLON.Vector3.Zero();
  19035. }
  19036. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19037. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19038. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19039. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19040. this._t1.subtractInPlace(this._t0);
  19041. this._t2.subtractInPlace(this._t0);
  19042. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19043. this._cachedTextureMatrix.m[0] = this._t1.x;
  19044. this._cachedTextureMatrix.m[1] = this._t1.y;
  19045. this._cachedTextureMatrix.m[2] = this._t1.z;
  19046. this._cachedTextureMatrix.m[4] = this._t2.x;
  19047. this._cachedTextureMatrix.m[5] = this._t2.y;
  19048. this._cachedTextureMatrix.m[6] = this._t2.z;
  19049. this._cachedTextureMatrix.m[8] = this._t0.x;
  19050. this._cachedTextureMatrix.m[9] = this._t0.y;
  19051. this._cachedTextureMatrix.m[10] = this._t0.z;
  19052. return this._cachedTextureMatrix;
  19053. };
  19054. Texture.prototype.getReflectionTextureMatrix = function () {
  19055. if (this.uOffset === this._cachedUOffset &&
  19056. this.vOffset === this._cachedVOffset &&
  19057. this.uScale === this._cachedUScale &&
  19058. this.vScale === this._cachedVScale &&
  19059. this.coordinatesMode === this._cachedCoordinatesMode) {
  19060. return this._cachedTextureMatrix;
  19061. }
  19062. if (!this._cachedTextureMatrix) {
  19063. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19064. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19065. }
  19066. this._cachedCoordinatesMode = this.coordinatesMode;
  19067. switch (this.coordinatesMode) {
  19068. case Texture.PLANAR_MODE:
  19069. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19070. this._cachedTextureMatrix[0] = this.uScale;
  19071. this._cachedTextureMatrix[5] = this.vScale;
  19072. this._cachedTextureMatrix[12] = this.uOffset;
  19073. this._cachedTextureMatrix[13] = this.vOffset;
  19074. break;
  19075. case Texture.PROJECTION_MODE:
  19076. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19077. this._projectionModeMatrix.m[0] = 0.5;
  19078. this._projectionModeMatrix.m[5] = -0.5;
  19079. this._projectionModeMatrix.m[10] = 0.0;
  19080. this._projectionModeMatrix.m[12] = 0.5;
  19081. this._projectionModeMatrix.m[13] = 0.5;
  19082. this._projectionModeMatrix.m[14] = 1.0;
  19083. this._projectionModeMatrix.m[15] = 1.0;
  19084. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19085. break;
  19086. default:
  19087. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19088. break;
  19089. }
  19090. return this._cachedTextureMatrix;
  19091. };
  19092. Texture.prototype.clone = function () {
  19093. var _this = this;
  19094. return BABYLON.SerializationHelper.Clone(function () {
  19095. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19096. }, this);
  19097. };
  19098. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19099. get: function () {
  19100. if (!this._onLoadObservarble) {
  19101. this._onLoadObservarble = new BABYLON.Observable();
  19102. }
  19103. return this._onLoadObservarble;
  19104. },
  19105. enumerable: true,
  19106. configurable: true
  19107. });
  19108. // Statics
  19109. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19110. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19111. if (onLoad === void 0) { onLoad = null; }
  19112. if (onError === void 0) { onError = null; }
  19113. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19114. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19115. };
  19116. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19117. if (parsedTexture.customType) {
  19118. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19119. // Update Sampling Mode
  19120. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19121. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19122. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19123. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19124. }
  19125. }
  19126. return parsedCustomTexture;
  19127. }
  19128. if (parsedTexture.isCube) {
  19129. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19130. }
  19131. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19132. return null;
  19133. }
  19134. var texture = BABYLON.SerializationHelper.Parse(function () {
  19135. if (parsedTexture.mirrorPlane) {
  19136. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19137. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19138. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19139. return mirrorTexture;
  19140. }
  19141. else if (parsedTexture.isRenderTarget) {
  19142. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19143. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19144. return renderTargetTexture;
  19145. }
  19146. else {
  19147. var texture;
  19148. if (parsedTexture.base64String) {
  19149. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19150. }
  19151. else {
  19152. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19153. }
  19154. return texture;
  19155. }
  19156. }, parsedTexture, scene);
  19157. // Update Sampling Mode
  19158. if (parsedTexture.samplingMode) {
  19159. var sampling = parsedTexture.samplingMode;
  19160. if (texture._samplingMode !== sampling) {
  19161. texture.updateSamplingMode(sampling);
  19162. }
  19163. }
  19164. // Animations
  19165. if (parsedTexture.animations) {
  19166. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19167. var parsedAnimation = parsedTexture.animations[animationIndex];
  19168. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19169. }
  19170. }
  19171. return texture;
  19172. };
  19173. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19174. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19175. if (noMipmap === void 0) { noMipmap = false; }
  19176. if (invertY === void 0) { invertY = true; }
  19177. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19178. if (onLoad === void 0) { onLoad = null; }
  19179. if (onError === void 0) { onError = null; }
  19180. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19181. if (name.substr(0, 5) !== "data:") {
  19182. name = "data:" + name;
  19183. }
  19184. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19185. };
  19186. return Texture;
  19187. }(BABYLON.BaseTexture));
  19188. // Constants
  19189. Texture.NEAREST_SAMPLINGMODE = 1;
  19190. Texture.BILINEAR_SAMPLINGMODE = 2;
  19191. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19192. Texture.EXPLICIT_MODE = 0;
  19193. Texture.SPHERICAL_MODE = 1;
  19194. Texture.PLANAR_MODE = 2;
  19195. Texture.CUBIC_MODE = 3;
  19196. Texture.PROJECTION_MODE = 4;
  19197. Texture.SKYBOX_MODE = 5;
  19198. Texture.INVCUBIC_MODE = 6;
  19199. Texture.EQUIRECTANGULAR_MODE = 7;
  19200. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19201. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19202. Texture.CLAMP_ADDRESSMODE = 0;
  19203. Texture.WRAP_ADDRESSMODE = 1;
  19204. Texture.MIRROR_ADDRESSMODE = 2;
  19205. __decorate([
  19206. BABYLON.serialize()
  19207. ], Texture.prototype, "url", void 0);
  19208. __decorate([
  19209. BABYLON.serialize()
  19210. ], Texture.prototype, "uOffset", void 0);
  19211. __decorate([
  19212. BABYLON.serialize()
  19213. ], Texture.prototype, "vOffset", void 0);
  19214. __decorate([
  19215. BABYLON.serialize()
  19216. ], Texture.prototype, "uScale", void 0);
  19217. __decorate([
  19218. BABYLON.serialize()
  19219. ], Texture.prototype, "vScale", void 0);
  19220. __decorate([
  19221. BABYLON.serialize()
  19222. ], Texture.prototype, "uAng", void 0);
  19223. __decorate([
  19224. BABYLON.serialize()
  19225. ], Texture.prototype, "vAng", void 0);
  19226. __decorate([
  19227. BABYLON.serialize()
  19228. ], Texture.prototype, "wAng", void 0);
  19229. __decorate([
  19230. BABYLON.serialize()
  19231. ], Texture.prototype, "isBlocking", null);
  19232. BABYLON.Texture = Texture;
  19233. })(BABYLON || (BABYLON = {}));
  19234. //# sourceMappingURL=babylon.texture.js.map
  19235. var BABYLON;
  19236. (function (BABYLON) {
  19237. var _InstancesBatch = (function () {
  19238. function _InstancesBatch() {
  19239. this.mustReturn = false;
  19240. this.visibleInstances = new Array();
  19241. this.renderSelf = new Array();
  19242. }
  19243. return _InstancesBatch;
  19244. }());
  19245. BABYLON._InstancesBatch = _InstancesBatch;
  19246. var Mesh = (function (_super) {
  19247. __extends(Mesh, _super);
  19248. /**
  19249. * @constructor
  19250. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19251. * @param {Scene} scene The scene to add this mesh to.
  19252. * @param {Node} parent The parent of this mesh, if it has one
  19253. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19254. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19255. * When false, achieved by calling a clone(), also passing False.
  19256. * This will make creation of children, recursive.
  19257. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19258. */
  19259. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19260. if (parent === void 0) { parent = null; }
  19261. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19262. var _this = _super.call(this, name, scene) || this;
  19263. // Events
  19264. /**
  19265. * An event triggered before rendering the mesh
  19266. * @type {BABYLON.Observable}
  19267. */
  19268. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19269. /**
  19270. * An event triggered after rendering the mesh
  19271. * @type {BABYLON.Observable}
  19272. */
  19273. _this.onAfterRenderObservable = new BABYLON.Observable();
  19274. /**
  19275. * An event triggered before drawing the mesh
  19276. * @type {BABYLON.Observable}
  19277. */
  19278. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19279. // Members
  19280. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19281. _this.instances = new Array();
  19282. _this._LODLevels = new Array();
  19283. _this._visibleInstances = {};
  19284. _this._renderIdForInstances = new Array();
  19285. _this._batchCache = new _InstancesBatch();
  19286. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19287. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19288. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19289. // Will be used to save a source mesh reference, If any
  19290. _this._source = null;
  19291. if (source) {
  19292. // Source mesh
  19293. _this._source = source;
  19294. // Geometry
  19295. if (source._geometry) {
  19296. source._geometry.applyToMesh(_this);
  19297. }
  19298. // Deep copy
  19299. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19300. // Parent
  19301. _this.parent = source.parent;
  19302. // Pivot
  19303. _this.setPivotMatrix(source.getPivotMatrix());
  19304. _this.id = name + "." + source.id;
  19305. // Material
  19306. _this.material = source.material;
  19307. var index;
  19308. if (!doNotCloneChildren) {
  19309. // Children
  19310. for (index = 0; index < scene.meshes.length; index++) {
  19311. var mesh = scene.meshes[index];
  19312. if (mesh.parent === source) {
  19313. // doNotCloneChildren is always going to be False
  19314. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19315. }
  19316. }
  19317. }
  19318. // Physics clone
  19319. var physicsEngine = _this.getScene().getPhysicsEngine();
  19320. if (clonePhysicsImpostor && physicsEngine) {
  19321. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19322. if (impostor) {
  19323. _this.physicsImpostor = impostor.clone(_this);
  19324. }
  19325. }
  19326. // Particles
  19327. for (index = 0; index < scene.particleSystems.length; index++) {
  19328. var system = scene.particleSystems[index];
  19329. if (system.emitter === source) {
  19330. system.clone(system.name, _this);
  19331. }
  19332. }
  19333. _this.computeWorldMatrix(true);
  19334. }
  19335. // Parent
  19336. if (parent !== null) {
  19337. _this.parent = parent;
  19338. }
  19339. return _this;
  19340. }
  19341. Object.defineProperty(Mesh, "FRONTSIDE", {
  19342. /**
  19343. * Mesh side orientation : usually the external or front surface
  19344. */
  19345. get: function () {
  19346. return Mesh._FRONTSIDE;
  19347. },
  19348. enumerable: true,
  19349. configurable: true
  19350. });
  19351. Object.defineProperty(Mesh, "BACKSIDE", {
  19352. /**
  19353. * Mesh side orientation : usually the internal or back surface
  19354. */
  19355. get: function () {
  19356. return Mesh._BACKSIDE;
  19357. },
  19358. enumerable: true,
  19359. configurable: true
  19360. });
  19361. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19362. /**
  19363. * Mesh side orientation : both internal and external or front and back surfaces
  19364. */
  19365. get: function () {
  19366. return Mesh._DOUBLESIDE;
  19367. },
  19368. enumerable: true,
  19369. configurable: true
  19370. });
  19371. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19372. /**
  19373. * Mesh side orientation : by default, `FRONTSIDE`
  19374. */
  19375. get: function () {
  19376. return Mesh._DEFAULTSIDE;
  19377. },
  19378. enumerable: true,
  19379. configurable: true
  19380. });
  19381. Object.defineProperty(Mesh, "NO_CAP", {
  19382. /**
  19383. * Mesh cap setting : no cap
  19384. */
  19385. get: function () {
  19386. return Mesh._NO_CAP;
  19387. },
  19388. enumerable: true,
  19389. configurable: true
  19390. });
  19391. Object.defineProperty(Mesh, "CAP_START", {
  19392. /**
  19393. * Mesh cap setting : one cap at the beginning of the mesh
  19394. */
  19395. get: function () {
  19396. return Mesh._CAP_START;
  19397. },
  19398. enumerable: true,
  19399. configurable: true
  19400. });
  19401. Object.defineProperty(Mesh, "CAP_END", {
  19402. /**
  19403. * Mesh cap setting : one cap at the end of the mesh
  19404. */
  19405. get: function () {
  19406. return Mesh._CAP_END;
  19407. },
  19408. enumerable: true,
  19409. configurable: true
  19410. });
  19411. Object.defineProperty(Mesh, "CAP_ALL", {
  19412. /**
  19413. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19414. */
  19415. get: function () {
  19416. return Mesh._CAP_ALL;
  19417. },
  19418. enumerable: true,
  19419. configurable: true
  19420. });
  19421. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19422. set: function (callback) {
  19423. if (this._onBeforeDrawObserver) {
  19424. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19425. }
  19426. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19427. },
  19428. enumerable: true,
  19429. configurable: true
  19430. });
  19431. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19432. get: function () {
  19433. return this._morphTargetManager;
  19434. },
  19435. set: function (value) {
  19436. if (this._morphTargetManager === value) {
  19437. return;
  19438. }
  19439. this._morphTargetManager = value;
  19440. this._syncGeometryWithMorphTargetManager();
  19441. },
  19442. enumerable: true,
  19443. configurable: true
  19444. });
  19445. Object.defineProperty(Mesh.prototype, "source", {
  19446. get: function () {
  19447. return this._source;
  19448. },
  19449. enumerable: true,
  19450. configurable: true
  19451. });
  19452. // Methods
  19453. /**
  19454. * Returns the string "Mesh".
  19455. */
  19456. Mesh.prototype.getClassName = function () {
  19457. return "Mesh";
  19458. };
  19459. /**
  19460. * Returns a string.
  19461. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19462. */
  19463. Mesh.prototype.toString = function (fullDetails) {
  19464. var ret = _super.prototype.toString.call(this, fullDetails);
  19465. ret += ", n vertices: " + this.getTotalVertices();
  19466. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19467. if (this.animations) {
  19468. for (var i = 0; i < this.animations.length; i++) {
  19469. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19470. }
  19471. }
  19472. if (fullDetails) {
  19473. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19474. }
  19475. return ret;
  19476. };
  19477. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19478. /**
  19479. * True if the mesh has some Levels Of Details (LOD).
  19480. * Returns a boolean.
  19481. */
  19482. get: function () {
  19483. return this._LODLevels.length > 0;
  19484. },
  19485. enumerable: true,
  19486. configurable: true
  19487. });
  19488. Mesh.prototype._sortLODLevels = function () {
  19489. this._LODLevels.sort(function (a, b) {
  19490. if (a.distance < b.distance) {
  19491. return 1;
  19492. }
  19493. if (a.distance > b.distance) {
  19494. return -1;
  19495. }
  19496. return 0;
  19497. });
  19498. };
  19499. /**
  19500. * Add a mesh as LOD level triggered at the given distance.
  19501. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19502. * @param {number} distance The distance from the center of the object to show this level
  19503. * @param {Mesh} mesh The mesh to be added as LOD level
  19504. * @return {Mesh} This mesh (for chaining)
  19505. */
  19506. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19507. if (mesh && mesh._masterMesh) {
  19508. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19509. return this;
  19510. }
  19511. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19512. this._LODLevels.push(level);
  19513. if (mesh) {
  19514. mesh._masterMesh = this;
  19515. }
  19516. this._sortLODLevels();
  19517. return this;
  19518. };
  19519. /**
  19520. * Returns the LOD level mesh at the passed distance or null if not found.
  19521. * It is related to the method `addLODLevel(distance, mesh)`.
  19522. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19523. * Returns an object Mesh or `null`.
  19524. */
  19525. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19526. for (var index = 0; index < this._LODLevels.length; index++) {
  19527. var level = this._LODLevels[index];
  19528. if (level.distance === distance) {
  19529. return level.mesh;
  19530. }
  19531. }
  19532. return null;
  19533. };
  19534. /**
  19535. * Remove a mesh from the LOD array
  19536. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19537. * @param {Mesh} mesh The mesh to be removed.
  19538. * @return {Mesh} This mesh (for chaining)
  19539. */
  19540. Mesh.prototype.removeLODLevel = function (mesh) {
  19541. for (var index = 0; index < this._LODLevels.length; index++) {
  19542. if (this._LODLevels[index].mesh === mesh) {
  19543. this._LODLevels.splice(index, 1);
  19544. if (mesh) {
  19545. mesh._masterMesh = null;
  19546. }
  19547. }
  19548. }
  19549. this._sortLODLevels();
  19550. return this;
  19551. };
  19552. /**
  19553. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19554. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19555. */
  19556. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19557. if (!this._LODLevels || this._LODLevels.length === 0) {
  19558. return this;
  19559. }
  19560. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19561. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19562. if (this.onLODLevelSelection) {
  19563. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19564. }
  19565. return this;
  19566. }
  19567. for (var index = 0; index < this._LODLevels.length; index++) {
  19568. var level = this._LODLevels[index];
  19569. if (level.distance < distanceToCamera) {
  19570. if (level.mesh) {
  19571. level.mesh._preActivate();
  19572. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19573. }
  19574. if (this.onLODLevelSelection) {
  19575. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19576. }
  19577. return level.mesh;
  19578. }
  19579. }
  19580. if (this.onLODLevelSelection) {
  19581. this.onLODLevelSelection(distanceToCamera, this, this);
  19582. }
  19583. return this;
  19584. };
  19585. Object.defineProperty(Mesh.prototype, "geometry", {
  19586. /**
  19587. * Returns the mesh internal Geometry object.
  19588. */
  19589. get: function () {
  19590. return this._geometry;
  19591. },
  19592. enumerable: true,
  19593. configurable: true
  19594. });
  19595. /**
  19596. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19597. */
  19598. Mesh.prototype.getTotalVertices = function () {
  19599. if (!this._geometry) {
  19600. return 0;
  19601. }
  19602. return this._geometry.getTotalVertices();
  19603. };
  19604. /**
  19605. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19606. * 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.
  19607. * You can force the copy with forceCopy === true
  19608. * Returns null if the mesh has no geometry or no vertex buffer.
  19609. * Possible `kind` values :
  19610. * - BABYLON.VertexBuffer.PositionKind
  19611. * - BABYLON.VertexBuffer.UVKind
  19612. * - BABYLON.VertexBuffer.UV2Kind
  19613. * - BABYLON.VertexBuffer.UV3Kind
  19614. * - BABYLON.VertexBuffer.UV4Kind
  19615. * - BABYLON.VertexBuffer.UV5Kind
  19616. * - BABYLON.VertexBuffer.UV6Kind
  19617. * - BABYLON.VertexBuffer.ColorKind
  19618. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19619. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19620. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19621. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19622. */
  19623. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19624. if (!this._geometry) {
  19625. return null;
  19626. }
  19627. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19628. };
  19629. /**
  19630. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19631. * Returns `undefined` if the mesh has no geometry.
  19632. * Possible `kind` values :
  19633. * - BABYLON.VertexBuffer.PositionKind
  19634. * - BABYLON.VertexBuffer.UVKind
  19635. * - BABYLON.VertexBuffer.UV2Kind
  19636. * - BABYLON.VertexBuffer.UV3Kind
  19637. * - BABYLON.VertexBuffer.UV4Kind
  19638. * - BABYLON.VertexBuffer.UV5Kind
  19639. * - BABYLON.VertexBuffer.UV6Kind
  19640. * - BABYLON.VertexBuffer.ColorKind
  19641. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19642. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19643. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19644. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19645. */
  19646. Mesh.prototype.getVertexBuffer = function (kind) {
  19647. if (!this._geometry) {
  19648. return undefined;
  19649. }
  19650. return this._geometry.getVertexBuffer(kind);
  19651. };
  19652. /**
  19653. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19654. * Possible `kind` values :
  19655. * - BABYLON.VertexBuffer.PositionKind
  19656. * - BABYLON.VertexBuffer.UVKind
  19657. * - BABYLON.VertexBuffer.UV2Kind
  19658. * - BABYLON.VertexBuffer.UV3Kind
  19659. * - BABYLON.VertexBuffer.UV4Kind
  19660. * - BABYLON.VertexBuffer.UV5Kind
  19661. * - BABYLON.VertexBuffer.UV6Kind
  19662. * - BABYLON.VertexBuffer.ColorKind
  19663. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19664. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19665. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19666. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19667. */
  19668. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19669. if (!this._geometry) {
  19670. if (this._delayInfo) {
  19671. return this._delayInfo.indexOf(kind) !== -1;
  19672. }
  19673. return false;
  19674. }
  19675. return this._geometry.isVerticesDataPresent(kind);
  19676. };
  19677. /**
  19678. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19679. * Possible `kind` values :
  19680. * - BABYLON.VertexBuffer.PositionKind
  19681. * - BABYLON.VertexBuffer.UVKind
  19682. * - BABYLON.VertexBuffer.UV2Kind
  19683. * - BABYLON.VertexBuffer.UV3Kind
  19684. * - BABYLON.VertexBuffer.UV4Kind
  19685. * - BABYLON.VertexBuffer.UV5Kind
  19686. * - BABYLON.VertexBuffer.UV6Kind
  19687. * - BABYLON.VertexBuffer.ColorKind
  19688. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19689. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19690. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19691. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19692. */
  19693. Mesh.prototype.getVerticesDataKinds = function () {
  19694. if (!this._geometry) {
  19695. var result = [];
  19696. if (this._delayInfo) {
  19697. this._delayInfo.forEach(function (kind, index, array) {
  19698. result.push(kind);
  19699. });
  19700. }
  19701. return result;
  19702. }
  19703. return this._geometry.getVerticesDataKinds();
  19704. };
  19705. /**
  19706. * Returns a positive integer : the total number of indices in this mesh geometry.
  19707. * Returns zero if the mesh has no geometry.
  19708. */
  19709. Mesh.prototype.getTotalIndices = function () {
  19710. if (!this._geometry) {
  19711. return 0;
  19712. }
  19713. return this._geometry.getTotalIndices();
  19714. };
  19715. /**
  19716. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  19717. * 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.
  19718. * Returns an empty array if the mesh has no geometry.
  19719. */
  19720. Mesh.prototype.getIndices = function (copyWhenShared) {
  19721. if (!this._geometry) {
  19722. return [];
  19723. }
  19724. return this._geometry.getIndices(copyWhenShared);
  19725. };
  19726. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19727. get: function () {
  19728. return this._masterMesh !== null && this._masterMesh !== undefined;
  19729. },
  19730. enumerable: true,
  19731. configurable: true
  19732. });
  19733. /**
  19734. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19735. */
  19736. Mesh.prototype.isReady = function () {
  19737. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19738. return false;
  19739. }
  19740. return _super.prototype.isReady.call(this);
  19741. };
  19742. /**
  19743. * Boolean : true if the mesh has been disposed.
  19744. */
  19745. Mesh.prototype.isDisposed = function () {
  19746. return this._isDisposed;
  19747. };
  19748. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19749. get: function () {
  19750. return this._sideOrientation;
  19751. },
  19752. /**
  19753. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19754. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19755. */
  19756. set: function (sideO) {
  19757. this._sideOrientation = sideO;
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19763. /**
  19764. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19765. * This property is pertinent only for updatable parametric shapes.
  19766. */
  19767. get: function () {
  19768. return this._areNormalsFrozen;
  19769. },
  19770. enumerable: true,
  19771. configurable: true
  19772. });
  19773. /**
  19774. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19775. * It has no effect at all on other shapes.
  19776. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19777. * Returns the Mesh.
  19778. */
  19779. Mesh.prototype.freezeNormals = function () {
  19780. this._areNormalsFrozen = true;
  19781. return this;
  19782. };
  19783. /**
  19784. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19785. * It has no effect at all on other shapes.
  19786. * It reactivates the mesh normals computation if it was previously frozen.
  19787. * Returns the Mesh.
  19788. */
  19789. Mesh.prototype.unfreezeNormals = function () {
  19790. this._areNormalsFrozen = false;
  19791. return this;
  19792. };
  19793. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19794. /**
  19795. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19796. */
  19797. set: function (count) {
  19798. this._overridenInstanceCount = count;
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. // Methods
  19804. Mesh.prototype._preActivate = function () {
  19805. var sceneRenderId = this.getScene().getRenderId();
  19806. if (this._preActivateId === sceneRenderId) {
  19807. return this;
  19808. }
  19809. this._preActivateId = sceneRenderId;
  19810. this._visibleInstances = null;
  19811. return this;
  19812. };
  19813. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19814. if (this._visibleInstances) {
  19815. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19816. }
  19817. return this;
  19818. };
  19819. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19820. if (!this._visibleInstances) {
  19821. this._visibleInstances = {};
  19822. this._visibleInstances.defaultRenderId = renderId;
  19823. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19824. }
  19825. if (!this._visibleInstances[renderId]) {
  19826. this._visibleInstances[renderId] = new Array();
  19827. }
  19828. this._visibleInstances[renderId].push(instance);
  19829. return this;
  19830. };
  19831. /**
  19832. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19833. * This means the mesh underlying bounding box and sphere are recomputed.
  19834. * Returns the Mesh.
  19835. */
  19836. Mesh.prototype.refreshBoundingInfo = function () {
  19837. if (this._boundingInfo.isLocked) {
  19838. return;
  19839. }
  19840. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19841. if (data) {
  19842. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19843. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19844. }
  19845. if (this.subMeshes) {
  19846. for (var index = 0; index < this.subMeshes.length; index++) {
  19847. this.subMeshes[index].refreshBoundingInfo();
  19848. }
  19849. }
  19850. this._updateBoundingInfo();
  19851. return this;
  19852. };
  19853. Mesh.prototype._createGlobalSubMesh = function () {
  19854. var totalVertices = this.getTotalVertices();
  19855. if (!totalVertices || !this.getIndices()) {
  19856. return null;
  19857. }
  19858. this.releaseSubMeshes();
  19859. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19860. };
  19861. Mesh.prototype.subdivide = function (count) {
  19862. if (count < 1) {
  19863. return;
  19864. }
  19865. var totalIndices = this.getTotalIndices();
  19866. var subdivisionSize = (totalIndices / count) | 0;
  19867. var offset = 0;
  19868. // Ensure that subdivisionSize is a multiple of 3
  19869. while (subdivisionSize % 3 !== 0) {
  19870. subdivisionSize++;
  19871. }
  19872. this.releaseSubMeshes();
  19873. for (var index = 0; index < count; index++) {
  19874. if (offset >= totalIndices) {
  19875. break;
  19876. }
  19877. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19878. offset += subdivisionSize;
  19879. }
  19880. this.synchronizeInstances();
  19881. };
  19882. /**
  19883. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19884. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19885. * The `data` are either a numeric array either a Float32Array.
  19886. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19887. * 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).
  19888. * Note that a new underlying VertexBuffer object is created each call.
  19889. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19890. *
  19891. * Possible `kind` values :
  19892. * - BABYLON.VertexBuffer.PositionKind
  19893. * - BABYLON.VertexBuffer.UVKind
  19894. * - BABYLON.VertexBuffer.UV2Kind
  19895. * - BABYLON.VertexBuffer.UV3Kind
  19896. * - BABYLON.VertexBuffer.UV4Kind
  19897. * - BABYLON.VertexBuffer.UV5Kind
  19898. * - BABYLON.VertexBuffer.UV6Kind
  19899. * - BABYLON.VertexBuffer.ColorKind
  19900. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19901. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19902. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19903. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19904. *
  19905. * Returns the Mesh.
  19906. */
  19907. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19908. if (!this._geometry) {
  19909. var vertexData = new BABYLON.VertexData();
  19910. vertexData.set(data, kind);
  19911. var scene = this.getScene();
  19912. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19913. }
  19914. else {
  19915. this._geometry.setVerticesData(kind, data, updatable, stride);
  19916. }
  19917. return this;
  19918. };
  19919. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  19920. if (updatable === void 0) { updatable = true; }
  19921. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  19922. return;
  19923. }
  19924. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  19925. };
  19926. /**
  19927. * Sets the mesh VertexBuffer.
  19928. * Returns the Mesh.
  19929. */
  19930. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19931. if (!this._geometry) {
  19932. var scene = this.getScene();
  19933. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19934. }
  19935. this._geometry.setVerticesBuffer(buffer);
  19936. return this;
  19937. };
  19938. /**
  19939. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19940. * If the mesh has no geometry, it is simply returned as it is.
  19941. * The `data` are either a numeric array either a Float32Array.
  19942. * No new underlying VertexBuffer object is created.
  19943. * 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.
  19944. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19945. *
  19946. * Possible `kind` values :
  19947. * - BABYLON.VertexBuffer.PositionKind
  19948. * - BABYLON.VertexBuffer.UVKind
  19949. * - BABYLON.VertexBuffer.UV2Kind
  19950. * - BABYLON.VertexBuffer.UV3Kind
  19951. * - BABYLON.VertexBuffer.UV4Kind
  19952. * - BABYLON.VertexBuffer.UV5Kind
  19953. * - BABYLON.VertexBuffer.UV6Kind
  19954. * - BABYLON.VertexBuffer.ColorKind
  19955. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19956. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19957. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19958. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19959. *
  19960. * Returns the Mesh.
  19961. */
  19962. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19963. if (!this._geometry) {
  19964. return;
  19965. }
  19966. if (!makeItUnique) {
  19967. this._geometry.updateVerticesData(kind, data, updateExtends);
  19968. }
  19969. else {
  19970. this.makeGeometryUnique();
  19971. this.updateVerticesData(kind, data, updateExtends, false);
  19972. }
  19973. return this;
  19974. };
  19975. /**
  19976. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19977. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19978. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19979. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19980. * Returns the Mesh.
  19981. */
  19982. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19983. if (computeNormals === void 0) { computeNormals = true; }
  19984. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19985. positionFunction(positions);
  19986. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19987. if (computeNormals) {
  19988. var indices = this.getIndices();
  19989. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19990. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19991. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19992. }
  19993. return this;
  19994. };
  19995. /**
  19996. * Creates a un-shared specific occurence of the geometry for the mesh.
  19997. * Returns the Mesh.
  19998. */
  19999. Mesh.prototype.makeGeometryUnique = function () {
  20000. if (!this._geometry) {
  20001. return;
  20002. }
  20003. var oldGeometry = this._geometry;
  20004. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20005. oldGeometry.releaseForMesh(this, true);
  20006. geometry.applyToMesh(this);
  20007. return this;
  20008. };
  20009. /**
  20010. * Sets the mesh indices.
  20011. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20012. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20013. * This method creates a new index buffer each call.
  20014. * Returns the Mesh.
  20015. */
  20016. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20017. if (!this._geometry) {
  20018. var vertexData = new BABYLON.VertexData();
  20019. vertexData.indices = indices;
  20020. var scene = this.getScene();
  20021. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20022. }
  20023. else {
  20024. this._geometry.setIndices(indices, totalVertices);
  20025. }
  20026. return this;
  20027. };
  20028. /**
  20029. * Invert the geometry to move from a right handed system to a left handed one.
  20030. * Returns the Mesh.
  20031. */
  20032. Mesh.prototype.toLeftHanded = function () {
  20033. if (!this._geometry) {
  20034. return;
  20035. }
  20036. this._geometry.toLeftHanded();
  20037. return this;
  20038. };
  20039. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20040. var engine = this.getScene().getEngine();
  20041. // Wireframe
  20042. var indexToBind;
  20043. if (this._unIndexed) {
  20044. indexToBind = null;
  20045. }
  20046. else {
  20047. switch (fillMode) {
  20048. case BABYLON.Material.PointFillMode:
  20049. indexToBind = null;
  20050. break;
  20051. case BABYLON.Material.WireFrameFillMode:
  20052. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20053. break;
  20054. default:
  20055. case BABYLON.Material.TriangleFillMode:
  20056. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20057. break;
  20058. }
  20059. }
  20060. // VBOs
  20061. this._geometry._bind(effect, indexToBind);
  20062. return this;
  20063. };
  20064. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20065. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20066. return this;
  20067. }
  20068. this.onBeforeDrawObservable.notifyObservers(this);
  20069. var engine = this.getScene().getEngine();
  20070. // Draw order
  20071. switch (fillMode) {
  20072. case BABYLON.Material.PointFillMode:
  20073. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20074. break;
  20075. case BABYLON.Material.WireFrameFillMode:
  20076. if (this._unIndexed) {
  20077. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20078. }
  20079. else {
  20080. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20081. }
  20082. break;
  20083. default:
  20084. if (this._unIndexed) {
  20085. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20086. }
  20087. else {
  20088. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20089. }
  20090. }
  20091. return this;
  20092. };
  20093. /**
  20094. * Registers for this mesh a javascript function called just before the rendering process.
  20095. * This function is passed the current mesh.
  20096. * Return the Mesh.
  20097. */
  20098. Mesh.prototype.registerBeforeRender = function (func) {
  20099. this.onBeforeRenderObservable.add(func);
  20100. return this;
  20101. };
  20102. /**
  20103. * Disposes a previously registered javascript function called before the rendering.
  20104. * This function is passed the current mesh.
  20105. * Returns the Mesh.
  20106. */
  20107. Mesh.prototype.unregisterBeforeRender = function (func) {
  20108. this.onBeforeRenderObservable.removeCallback(func);
  20109. return this;
  20110. };
  20111. /**
  20112. * Registers for this mesh a javascript function called just after the rendering is complete.
  20113. * This function is passed the current mesh.
  20114. * Returns the Mesh.
  20115. */
  20116. Mesh.prototype.registerAfterRender = function (func) {
  20117. this.onAfterRenderObservable.add(func);
  20118. return this;
  20119. };
  20120. /**
  20121. * Disposes a previously registered javascript function called after the rendering.
  20122. * This function is passed the current mesh.
  20123. * Return the Mesh.
  20124. */
  20125. Mesh.prototype.unregisterAfterRender = function (func) {
  20126. this.onAfterRenderObservable.removeCallback(func);
  20127. return this;
  20128. };
  20129. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20130. var scene = this.getScene();
  20131. this._batchCache.mustReturn = false;
  20132. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20133. this._batchCache.visibleInstances[subMeshId] = null;
  20134. if (this._visibleInstances) {
  20135. var currentRenderId = scene.getRenderId();
  20136. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20137. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20138. var selfRenderId = this._renderId;
  20139. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20140. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20141. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20142. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20143. }
  20144. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20145. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20146. this._batchCache.mustReturn = true;
  20147. return this._batchCache;
  20148. }
  20149. if (currentRenderId !== selfRenderId) {
  20150. this._batchCache.renderSelf[subMeshId] = false;
  20151. }
  20152. }
  20153. this._renderIdForInstances[subMeshId] = currentRenderId;
  20154. }
  20155. return this._batchCache;
  20156. };
  20157. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20158. var visibleInstances = batch.visibleInstances[subMesh._id];
  20159. var matricesCount = visibleInstances.length + 1;
  20160. var bufferSize = matricesCount * 16 * 4;
  20161. var currentInstancesBufferSize = this._instancesBufferSize;
  20162. var instancesBuffer = this._instancesBuffer;
  20163. while (this._instancesBufferSize < bufferSize) {
  20164. this._instancesBufferSize *= 2;
  20165. }
  20166. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20167. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20168. }
  20169. var offset = 0;
  20170. var instancesCount = 0;
  20171. var world = this.getWorldMatrix();
  20172. if (batch.renderSelf[subMesh._id]) {
  20173. world.copyToArray(this._instancesData, offset);
  20174. offset += 16;
  20175. instancesCount++;
  20176. }
  20177. if (visibleInstances) {
  20178. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20179. var instance = visibleInstances[instanceIndex];
  20180. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20181. offset += 16;
  20182. instancesCount++;
  20183. }
  20184. }
  20185. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20186. if (instancesBuffer) {
  20187. instancesBuffer.dispose();
  20188. }
  20189. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20190. this._instancesBuffer = instancesBuffer;
  20191. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20192. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20193. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20194. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20195. }
  20196. else {
  20197. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20198. }
  20199. this.geometry._bind(effect);
  20200. this._draw(subMesh, fillMode, instancesCount);
  20201. engine.unbindInstanceAttributes();
  20202. return this;
  20203. };
  20204. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20205. var scene = this.getScene();
  20206. var engine = scene.getEngine();
  20207. if (hardwareInstancedRendering) {
  20208. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20209. }
  20210. else {
  20211. if (batch.renderSelf[subMesh._id]) {
  20212. // Draw
  20213. if (onBeforeDraw) {
  20214. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20215. }
  20216. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20217. }
  20218. if (batch.visibleInstances[subMesh._id]) {
  20219. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20220. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20221. // World
  20222. var world = instance.getWorldMatrix();
  20223. if (onBeforeDraw) {
  20224. onBeforeDraw(true, world, effectiveMaterial);
  20225. }
  20226. // Draw
  20227. this._draw(subMesh, fillMode);
  20228. }
  20229. }
  20230. }
  20231. return this;
  20232. };
  20233. /**
  20234. * Triggers the draw call for the mesh.
  20235. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20236. * Returns the Mesh.
  20237. */
  20238. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20239. var scene = this.getScene();
  20240. // Managing instances
  20241. var batch = this._getInstancesRenderList(subMesh._id);
  20242. if (batch.mustReturn) {
  20243. return this;
  20244. }
  20245. // Checking geometry state
  20246. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20247. return this;
  20248. }
  20249. var callbackIndex;
  20250. this.onBeforeRenderObservable.notifyObservers(this);
  20251. var engine = scene.getEngine();
  20252. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20253. // Material
  20254. var effectiveMaterial = subMesh.getMaterial();
  20255. if (!effectiveMaterial) {
  20256. return this;
  20257. }
  20258. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20259. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20260. return this;
  20261. }
  20262. }
  20263. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20264. return this;
  20265. }
  20266. // Outline - step 1
  20267. var savedDepthWrite = engine.getDepthWrite();
  20268. if (this.renderOutline) {
  20269. engine.setDepthWrite(false);
  20270. scene.getOutlineRenderer().render(subMesh, batch);
  20271. engine.setDepthWrite(savedDepthWrite);
  20272. }
  20273. var effect;
  20274. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20275. effect = subMesh.effect;
  20276. }
  20277. else {
  20278. effect = effectiveMaterial.getEffect();
  20279. }
  20280. effectiveMaterial._preBind(effect);
  20281. // Bind
  20282. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20283. this._bind(subMesh, effect, fillMode);
  20284. var world = this.getWorldMatrix();
  20285. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20286. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20287. }
  20288. else {
  20289. effectiveMaterial.bind(world, this);
  20290. }
  20291. // Alpha mode
  20292. if (enableAlphaMode) {
  20293. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20294. }
  20295. // Draw
  20296. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20297. // Unbind
  20298. effectiveMaterial.unbind();
  20299. // Outline - step 2
  20300. if (this.renderOutline && savedDepthWrite) {
  20301. engine.setDepthWrite(true);
  20302. engine.setColorWrite(false);
  20303. scene.getOutlineRenderer().render(subMesh, batch);
  20304. engine.setColorWrite(true);
  20305. }
  20306. // Overlay
  20307. if (this.renderOverlay) {
  20308. var currentMode = engine.getAlphaMode();
  20309. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20310. scene.getOutlineRenderer().render(subMesh, batch, true);
  20311. engine.setAlphaMode(currentMode);
  20312. }
  20313. this.onAfterRenderObservable.notifyObservers(this);
  20314. return this;
  20315. };
  20316. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20317. if (isInstance) {
  20318. effectiveMaterial.bindOnlyWorldMatrix(world);
  20319. }
  20320. return this;
  20321. };
  20322. /**
  20323. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20324. */
  20325. Mesh.prototype.getEmittedParticleSystems = function () {
  20326. var results = new Array();
  20327. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20328. var particleSystem = this.getScene().particleSystems[index];
  20329. if (particleSystem.emitter === this) {
  20330. results.push(particleSystem);
  20331. }
  20332. }
  20333. return results;
  20334. };
  20335. /**
  20336. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20337. */
  20338. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20339. var results = new Array();
  20340. var descendants = this.getDescendants();
  20341. descendants.push(this);
  20342. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20343. var particleSystem = this.getScene().particleSystems[index];
  20344. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20345. results.push(particleSystem);
  20346. }
  20347. }
  20348. return results;
  20349. };
  20350. Mesh.prototype._checkDelayState = function () {
  20351. var scene = this.getScene();
  20352. if (this._geometry) {
  20353. this._geometry.load(scene);
  20354. }
  20355. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20356. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20357. this._queueLoad(this, scene);
  20358. }
  20359. return this;
  20360. };
  20361. Mesh.prototype._queueLoad = function (mesh, scene) {
  20362. var _this = this;
  20363. scene._addPendingData(mesh);
  20364. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20365. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20366. if (data instanceof ArrayBuffer) {
  20367. _this._delayLoadingFunction(data, _this);
  20368. }
  20369. else {
  20370. _this._delayLoadingFunction(JSON.parse(data), _this);
  20371. }
  20372. _this.instances.forEach(function (instance) {
  20373. instance._syncSubMeshes();
  20374. });
  20375. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20376. scene._removePendingData(_this);
  20377. }, function () { }, scene.database, getBinaryData);
  20378. return this;
  20379. };
  20380. /**
  20381. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20382. */
  20383. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20384. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20385. return false;
  20386. }
  20387. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20388. return false;
  20389. }
  20390. this._checkDelayState();
  20391. return true;
  20392. };
  20393. /**
  20394. * Sets the mesh material by the material or multiMaterial `id` property.
  20395. * The material `id` is a string identifying the material or the multiMaterial.
  20396. * This method returns the Mesh.
  20397. */
  20398. Mesh.prototype.setMaterialByID = function (id) {
  20399. var materials = this.getScene().materials;
  20400. var index;
  20401. for (index = materials.length - 1; index > -1; index--) {
  20402. if (materials[index].id === id) {
  20403. this.material = materials[index];
  20404. return this;
  20405. }
  20406. }
  20407. // Multi
  20408. var multiMaterials = this.getScene().multiMaterials;
  20409. for (index = multiMaterials.length - 1; index > -1; index--) {
  20410. if (multiMaterials[index].id === id) {
  20411. this.material = multiMaterials[index];
  20412. return this;
  20413. }
  20414. }
  20415. return this;
  20416. };
  20417. /**
  20418. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20419. */
  20420. Mesh.prototype.getAnimatables = function () {
  20421. var results = [];
  20422. if (this.material) {
  20423. results.push(this.material);
  20424. }
  20425. if (this.skeleton) {
  20426. results.push(this.skeleton);
  20427. }
  20428. return results;
  20429. };
  20430. /**
  20431. * Modifies the mesh geometry according to the passed transformation matrix.
  20432. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20433. * The mesh normals are modified accordingly the same transformation.
  20434. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20435. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20436. * Returns the Mesh.
  20437. */
  20438. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20439. // Position
  20440. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20441. return this;
  20442. }
  20443. var submeshes = this.subMeshes.splice(0);
  20444. this._resetPointsArrayCache();
  20445. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20446. var temp = [];
  20447. var index;
  20448. for (index = 0; index < data.length; index += 3) {
  20449. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20450. }
  20451. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20452. // Normals
  20453. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20454. return this;
  20455. }
  20456. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20457. temp = [];
  20458. for (index = 0; index < data.length; index += 3) {
  20459. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20460. }
  20461. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20462. // flip faces?
  20463. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20464. this.flipFaces();
  20465. }
  20466. // Restore submeshes
  20467. this.releaseSubMeshes();
  20468. this.subMeshes = submeshes;
  20469. return this;
  20470. };
  20471. /**
  20472. * Modifies the mesh geometry according to its own current World Matrix.
  20473. * The mesh World Matrix is then reset.
  20474. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20475. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20476. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20477. * Returns the Mesh.
  20478. */
  20479. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20480. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20481. this.scaling.copyFromFloats(1, 1, 1);
  20482. this.position.copyFromFloats(0, 0, 0);
  20483. this.rotation.copyFromFloats(0, 0, 0);
  20484. //only if quaternion is already set
  20485. if (this.rotationQuaternion) {
  20486. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20487. }
  20488. this._worldMatrix = BABYLON.Matrix.Identity();
  20489. return this;
  20490. };
  20491. Object.defineProperty(Mesh.prototype, "_positions", {
  20492. // Cache
  20493. get: function () {
  20494. if (this._geometry) {
  20495. return this._geometry._positions;
  20496. }
  20497. return null;
  20498. },
  20499. enumerable: true,
  20500. configurable: true
  20501. });
  20502. Mesh.prototype._resetPointsArrayCache = function () {
  20503. if (this._geometry) {
  20504. this._geometry._resetPointsArrayCache();
  20505. }
  20506. return this;
  20507. };
  20508. Mesh.prototype._generatePointsArray = function () {
  20509. if (this._geometry) {
  20510. return this._geometry._generatePointsArray();
  20511. }
  20512. return false;
  20513. };
  20514. /**
  20515. * Returns a new Mesh object generated from the current mesh properties.
  20516. * This method must not get confused with createInstance().
  20517. * The parameter `name` is a string, the name given to the new mesh.
  20518. * The optional parameter `newParent` can be any Node object (default `null`).
  20519. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20520. * 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.
  20521. */
  20522. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20523. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20524. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20525. };
  20526. /**
  20527. * Disposes the mesh.
  20528. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20529. */
  20530. Mesh.prototype.dispose = function (doNotRecurse) {
  20531. var _this = this;
  20532. this.morphTargetManager = undefined;
  20533. if (this._geometry) {
  20534. this._geometry.releaseForMesh(this, true);
  20535. }
  20536. // Sources
  20537. var meshes = this.getScene().meshes;
  20538. meshes.forEach(function (mesh) {
  20539. if (mesh._source && mesh._source === _this) {
  20540. mesh._source = null;
  20541. }
  20542. });
  20543. this._source = null;
  20544. // Instances
  20545. if (this._instancesBuffer) {
  20546. this._instancesBuffer.dispose();
  20547. this._instancesBuffer = null;
  20548. }
  20549. while (this.instances.length) {
  20550. this.instances[0].dispose();
  20551. }
  20552. // Highlight layers.
  20553. var highlightLayers = this.getScene().highlightLayers;
  20554. for (var i = 0; i < highlightLayers.length; i++) {
  20555. var highlightLayer = highlightLayers[i];
  20556. if (highlightLayer) {
  20557. highlightLayer.removeMesh(this);
  20558. highlightLayer.removeExcludedMesh(this);
  20559. }
  20560. }
  20561. _super.prototype.dispose.call(this, doNotRecurse);
  20562. };
  20563. /**
  20564. * Modifies the mesh geometry according to a displacement map.
  20565. * 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.
  20566. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20567. * This method returns nothing.
  20568. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20569. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20570. * 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.
  20571. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20572. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20573. *
  20574. * Returns the Mesh.
  20575. */
  20576. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20577. var _this = this;
  20578. var scene = this.getScene();
  20579. var onload = function (img) {
  20580. // Getting height map data
  20581. var canvas = document.createElement("canvas");
  20582. var context = canvas.getContext("2d");
  20583. var heightMapWidth = img.width;
  20584. var heightMapHeight = img.height;
  20585. canvas.width = heightMapWidth;
  20586. canvas.height = heightMapHeight;
  20587. context.drawImage(img, 0, 0);
  20588. // Create VertexData from map data
  20589. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20590. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20591. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20592. //execute success callback, if set
  20593. if (onSuccess) {
  20594. onSuccess(_this);
  20595. }
  20596. };
  20597. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20598. return this;
  20599. };
  20600. /**
  20601. * Modifies the mesh geometry according to a displacementMap buffer.
  20602. * 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.
  20603. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20604. * This method returns nothing.
  20605. * 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.
  20606. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20607. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20608. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20609. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20610. *
  20611. * Returns the Mesh.
  20612. */
  20613. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20614. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20615. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20616. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20617. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20618. return this;
  20619. }
  20620. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20621. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20622. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20623. var position = BABYLON.Vector3.Zero();
  20624. var normal = BABYLON.Vector3.Zero();
  20625. var uv = BABYLON.Vector2.Zero();
  20626. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20627. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20628. for (var index = 0; index < positions.length; index += 3) {
  20629. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20630. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20631. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20632. // Compute height
  20633. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20634. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20635. var pos = (u + v * heightMapWidth) * 4;
  20636. var r = buffer[pos] / 255.0;
  20637. var g = buffer[pos + 1] / 255.0;
  20638. var b = buffer[pos + 2] / 255.0;
  20639. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20640. normal.normalize();
  20641. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20642. position = position.add(normal);
  20643. position.toArray(positions, index);
  20644. }
  20645. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20646. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20647. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20648. return this;
  20649. };
  20650. /**
  20651. * Modify the mesh to get a flat shading rendering.
  20652. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20653. * This method returns the Mesh.
  20654. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20655. */
  20656. Mesh.prototype.convertToFlatShadedMesh = function () {
  20657. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20658. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20659. var kinds = this.getVerticesDataKinds();
  20660. var vbs = [];
  20661. var data = [];
  20662. var newdata = [];
  20663. var updatableNormals = false;
  20664. var kindIndex;
  20665. var kind;
  20666. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20667. kind = kinds[kindIndex];
  20668. var vertexBuffer = this.getVertexBuffer(kind);
  20669. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20670. updatableNormals = vertexBuffer.isUpdatable();
  20671. kinds.splice(kindIndex, 1);
  20672. kindIndex--;
  20673. continue;
  20674. }
  20675. vbs[kind] = vertexBuffer;
  20676. data[kind] = vbs[kind].getData();
  20677. newdata[kind] = [];
  20678. }
  20679. // Save previous submeshes
  20680. var previousSubmeshes = this.subMeshes.slice(0);
  20681. var indices = this.getIndices();
  20682. var totalIndices = this.getTotalIndices();
  20683. // Generating unique vertices per face
  20684. var index;
  20685. for (index = 0; index < totalIndices; index++) {
  20686. var vertexIndex = indices[index];
  20687. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20688. kind = kinds[kindIndex];
  20689. var stride = vbs[kind].getStrideSize();
  20690. for (var offset = 0; offset < stride; offset++) {
  20691. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20692. }
  20693. }
  20694. }
  20695. // Updating faces & normal
  20696. var normals = [];
  20697. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20698. for (index = 0; index < totalIndices; index += 3) {
  20699. indices[index] = index;
  20700. indices[index + 1] = index + 1;
  20701. indices[index + 2] = index + 2;
  20702. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20703. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20704. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20705. var p1p2 = p1.subtract(p2);
  20706. var p3p2 = p3.subtract(p2);
  20707. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20708. // Store same normals for every vertex
  20709. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20710. normals.push(normal.x);
  20711. normals.push(normal.y);
  20712. normals.push(normal.z);
  20713. }
  20714. }
  20715. this.setIndices(indices);
  20716. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20717. // Updating vertex buffers
  20718. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20719. kind = kinds[kindIndex];
  20720. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20721. }
  20722. // Updating submeshes
  20723. this.releaseSubMeshes();
  20724. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20725. var previousOne = previousSubmeshes[submeshIndex];
  20726. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20727. }
  20728. this.synchronizeInstances();
  20729. return this;
  20730. };
  20731. /**
  20732. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20733. * In other words, more vertices, no more indices and a single bigger VBO.
  20734. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20735. * Returns the Mesh.
  20736. */
  20737. Mesh.prototype.convertToUnIndexedMesh = function () {
  20738. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20739. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20740. var kinds = this.getVerticesDataKinds();
  20741. var vbs = [];
  20742. var data = [];
  20743. var newdata = [];
  20744. var updatableNormals = false;
  20745. var kindIndex;
  20746. var kind;
  20747. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20748. kind = kinds[kindIndex];
  20749. var vertexBuffer = this.getVertexBuffer(kind);
  20750. vbs[kind] = vertexBuffer;
  20751. data[kind] = vbs[kind].getData();
  20752. newdata[kind] = [];
  20753. }
  20754. // Save previous submeshes
  20755. var previousSubmeshes = this.subMeshes.slice(0);
  20756. var indices = this.getIndices();
  20757. var totalIndices = this.getTotalIndices();
  20758. // Generating unique vertices per face
  20759. var index;
  20760. for (index = 0; index < totalIndices; index++) {
  20761. var vertexIndex = indices[index];
  20762. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20763. kind = kinds[kindIndex];
  20764. var stride = vbs[kind].getStrideSize();
  20765. for (var offset = 0; offset < stride; offset++) {
  20766. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20767. }
  20768. }
  20769. }
  20770. // Updating indices
  20771. for (index = 0; index < totalIndices; index += 3) {
  20772. indices[index] = index;
  20773. indices[index + 1] = index + 1;
  20774. indices[index + 2] = index + 2;
  20775. }
  20776. this.setIndices(indices);
  20777. // Updating vertex buffers
  20778. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20779. kind = kinds[kindIndex];
  20780. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20781. }
  20782. // Updating submeshes
  20783. this.releaseSubMeshes();
  20784. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20785. var previousOne = previousSubmeshes[submeshIndex];
  20786. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20787. }
  20788. this._unIndexed = true;
  20789. this.synchronizeInstances();
  20790. return this;
  20791. };
  20792. /**
  20793. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20794. * This method returns the Mesh.
  20795. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20796. */
  20797. Mesh.prototype.flipFaces = function (flipNormals) {
  20798. if (flipNormals === void 0) { flipNormals = false; }
  20799. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20800. var i;
  20801. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20802. for (i = 0; i < vertex_data.normals.length; i++) {
  20803. vertex_data.normals[i] *= -1;
  20804. }
  20805. }
  20806. var temp;
  20807. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20808. // reassign indices
  20809. temp = vertex_data.indices[i + 1];
  20810. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20811. vertex_data.indices[i + 2] = temp;
  20812. }
  20813. vertex_data.applyToMesh(this);
  20814. return this;
  20815. };
  20816. // Instances
  20817. /**
  20818. * Creates a new InstancedMesh object from the mesh model.
  20819. * An instance shares the same properties and the same material than its model.
  20820. * Only these properties of each instance can then be set individually :
  20821. * - position
  20822. * - rotation
  20823. * - rotationQuaternion
  20824. * - setPivotMatrix
  20825. * - scaling
  20826. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20827. * Warning : this method is not supported for Line mesh and LineSystem
  20828. */
  20829. Mesh.prototype.createInstance = function (name) {
  20830. return new BABYLON.InstancedMesh(name, this);
  20831. };
  20832. /**
  20833. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20834. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20835. * This method returns the Mesh.
  20836. */
  20837. Mesh.prototype.synchronizeInstances = function () {
  20838. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20839. var instance = this.instances[instanceIndex];
  20840. instance._syncSubMeshes();
  20841. }
  20842. return this;
  20843. };
  20844. /**
  20845. * Simplify the mesh according to the given array of settings.
  20846. * Function will return immediately and will simplify async. It returns the Mesh.
  20847. * @param settings a collection of simplification settings.
  20848. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20849. * @param type the type of simplification to run.
  20850. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20851. */
  20852. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20853. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20854. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20855. this.getScene().simplificationQueue.addTask({
  20856. settings: settings,
  20857. parallelProcessing: parallelProcessing,
  20858. mesh: this,
  20859. simplificationType: simplificationType,
  20860. successCallback: successCallback
  20861. });
  20862. return this;
  20863. };
  20864. /**
  20865. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20866. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20867. * This should be used together with the simplification to avoid disappearing triangles.
  20868. * Returns the Mesh.
  20869. * @param successCallback an optional success callback to be called after the optimization finished.
  20870. */
  20871. Mesh.prototype.optimizeIndices = function (successCallback) {
  20872. var _this = this;
  20873. var indices = this.getIndices();
  20874. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20875. var vectorPositions = [];
  20876. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20877. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20878. }
  20879. var dupes = [];
  20880. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20881. var realPos = vectorPositions.length - 1 - iteration;
  20882. var testedPosition = vectorPositions[realPos];
  20883. for (var j = 0; j < realPos; ++j) {
  20884. var againstPosition = vectorPositions[j];
  20885. if (testedPosition.equals(againstPosition)) {
  20886. dupes[realPos] = j;
  20887. break;
  20888. }
  20889. }
  20890. }, function () {
  20891. for (var i = 0; i < indices.length; ++i) {
  20892. indices[i] = dupes[indices[i]] || indices[i];
  20893. }
  20894. //indices are now reordered
  20895. var originalSubMeshes = _this.subMeshes.slice(0);
  20896. _this.setIndices(indices);
  20897. _this.subMeshes = originalSubMeshes;
  20898. if (successCallback) {
  20899. successCallback(_this);
  20900. }
  20901. });
  20902. return this;
  20903. };
  20904. Mesh.prototype.serialize = function (serializationObject) {
  20905. serializationObject.name = this.name;
  20906. serializationObject.id = this.id;
  20907. serializationObject.type = this.getClassName();
  20908. if (BABYLON.Tags.HasTags(this)) {
  20909. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20910. }
  20911. serializationObject.position = this.position.asArray();
  20912. if (this.rotationQuaternion) {
  20913. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  20914. }
  20915. else if (this.rotation) {
  20916. serializationObject.rotation = this.rotation.asArray();
  20917. }
  20918. serializationObject.scaling = this.scaling.asArray();
  20919. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20920. serializationObject.isEnabled = this.isEnabled();
  20921. serializationObject.isVisible = this.isVisible;
  20922. serializationObject.infiniteDistance = this.infiniteDistance;
  20923. serializationObject.pickable = this.isPickable;
  20924. serializationObject.receiveShadows = this.receiveShadows;
  20925. serializationObject.billboardMode = this.billboardMode;
  20926. serializationObject.visibility = this.visibility;
  20927. serializationObject.checkCollisions = this.checkCollisions;
  20928. serializationObject.isBlocker = this.isBlocker;
  20929. // Parent
  20930. if (this.parent) {
  20931. serializationObject.parentId = this.parent.id;
  20932. }
  20933. // Geometry
  20934. var geometry = this._geometry;
  20935. if (geometry) {
  20936. var geometryId = geometry.id;
  20937. serializationObject.geometryId = geometryId;
  20938. // SubMeshes
  20939. serializationObject.subMeshes = [];
  20940. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20941. var subMesh = this.subMeshes[subIndex];
  20942. serializationObject.subMeshes.push({
  20943. materialIndex: subMesh.materialIndex,
  20944. verticesStart: subMesh.verticesStart,
  20945. verticesCount: subMesh.verticesCount,
  20946. indexStart: subMesh.indexStart,
  20947. indexCount: subMesh.indexCount
  20948. });
  20949. }
  20950. }
  20951. // Material
  20952. if (this.material) {
  20953. serializationObject.materialId = this.material.id;
  20954. }
  20955. else {
  20956. this.material = null;
  20957. }
  20958. // Morph targets
  20959. if (this.morphTargetManager) {
  20960. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  20961. }
  20962. // Skeleton
  20963. if (this.skeleton) {
  20964. serializationObject.skeletonId = this.skeleton.id;
  20965. }
  20966. // Physics
  20967. //TODO implement correct serialization for physics impostors.
  20968. if (this.getPhysicsImpostor()) {
  20969. var impostor = this.getPhysicsImpostor();
  20970. serializationObject.physicsMass = impostor.getParam("mass");
  20971. serializationObject.physicsFriction = impostor.getParam("friction");
  20972. serializationObject.physicsRestitution = impostor.getParam("mass");
  20973. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  20974. }
  20975. // Metadata
  20976. if (this.metadata) {
  20977. serializationObject.metadata = this.metadata;
  20978. }
  20979. // Instances
  20980. serializationObject.instances = [];
  20981. for (var index = 0; index < this.instances.length; index++) {
  20982. var instance = this.instances[index];
  20983. var serializationInstance = {
  20984. name: instance.name,
  20985. position: instance.position.asArray(),
  20986. scaling: instance.scaling.asArray()
  20987. };
  20988. if (instance.rotationQuaternion) {
  20989. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  20990. }
  20991. else if (instance.rotation) {
  20992. serializationInstance.rotation = instance.rotation.asArray();
  20993. }
  20994. serializationObject.instances.push(serializationInstance);
  20995. // Animations
  20996. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  20997. serializationInstance.ranges = instance.serializeAnimationRanges();
  20998. }
  20999. //
  21000. // Animations
  21001. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21002. serializationObject.ranges = this.serializeAnimationRanges();
  21003. // Layer mask
  21004. serializationObject.layerMask = this.layerMask;
  21005. // Alpha
  21006. serializationObject.alphaIndex = this.alphaIndex;
  21007. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21008. // Overlay
  21009. serializationObject.overlayAlpha = this.overlayAlpha;
  21010. serializationObject.overlayColor = this.overlayColor.asArray();
  21011. serializationObject.renderOverlay = this.renderOverlay;
  21012. // Fog
  21013. serializationObject.applyFog = this.applyFog;
  21014. // Action Manager
  21015. if (this.actionManager) {
  21016. serializationObject.actions = this.actionManager.serialize(this.name);
  21017. }
  21018. };
  21019. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21020. if (!this.geometry) {
  21021. return;
  21022. }
  21023. this._markSubMeshesAsAttributesDirty();
  21024. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21025. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21026. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21027. this.morphTargetManager = undefined;
  21028. return;
  21029. }
  21030. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21031. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21032. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21033. if (morphTarget.hasNormals) {
  21034. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21035. }
  21036. if (morphTarget.hasTangents) {
  21037. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21038. }
  21039. }
  21040. }
  21041. else {
  21042. var index = 0;
  21043. // Positions
  21044. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21045. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21046. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21047. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21048. }
  21049. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21050. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21051. }
  21052. index++;
  21053. }
  21054. }
  21055. };
  21056. // Statics
  21057. /**
  21058. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21059. * The parameter `parsedMesh` is the mesh to be copied.
  21060. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21061. */
  21062. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21063. var mesh;
  21064. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21065. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21066. }
  21067. else {
  21068. mesh = new Mesh(parsedMesh.name, scene);
  21069. }
  21070. mesh.id = parsedMesh.id;
  21071. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21072. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21073. if (parsedMesh.metadata !== undefined) {
  21074. mesh.metadata = parsedMesh.metadata;
  21075. }
  21076. if (parsedMesh.rotationQuaternion) {
  21077. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21078. }
  21079. else if (parsedMesh.rotation) {
  21080. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21081. }
  21082. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21083. if (parsedMesh.localMatrix) {
  21084. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21085. }
  21086. else if (parsedMesh.pivotMatrix) {
  21087. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21088. }
  21089. mesh.setEnabled(parsedMesh.isEnabled);
  21090. mesh.isVisible = parsedMesh.isVisible;
  21091. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21092. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21093. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21094. if (parsedMesh.applyFog !== undefined) {
  21095. mesh.applyFog = parsedMesh.applyFog;
  21096. }
  21097. if (parsedMesh.pickable !== undefined) {
  21098. mesh.isPickable = parsedMesh.pickable;
  21099. }
  21100. if (parsedMesh.alphaIndex !== undefined) {
  21101. mesh.alphaIndex = parsedMesh.alphaIndex;
  21102. }
  21103. mesh.receiveShadows = parsedMesh.receiveShadows;
  21104. mesh.billboardMode = parsedMesh.billboardMode;
  21105. if (parsedMesh.visibility !== undefined) {
  21106. mesh.visibility = parsedMesh.visibility;
  21107. }
  21108. mesh.checkCollisions = parsedMesh.checkCollisions;
  21109. if (parsedMesh.isBlocker !== undefined) {
  21110. mesh.isBlocker = parsedMesh.isBlocker;
  21111. }
  21112. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21113. // freezeWorldMatrix
  21114. if (parsedMesh.freezeWorldMatrix) {
  21115. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21116. }
  21117. // Parent
  21118. if (parsedMesh.parentId) {
  21119. mesh._waitingParentId = parsedMesh.parentId;
  21120. }
  21121. // Actions
  21122. if (parsedMesh.actions !== undefined) {
  21123. mesh._waitingActions = parsedMesh.actions;
  21124. }
  21125. // Overlay
  21126. if (parsedMesh.overlayAlpha !== undefined) {
  21127. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21128. }
  21129. if (parsedMesh.overlayColor !== undefined) {
  21130. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21131. }
  21132. if (parsedMesh.renderOverlay !== undefined) {
  21133. mesh.renderOverlay = parsedMesh.renderOverlay;
  21134. }
  21135. // Geometry
  21136. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21137. if (parsedMesh.delayLoadingFile) {
  21138. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21139. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21140. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21141. if (parsedMesh._binaryInfo) {
  21142. mesh._binaryInfo = parsedMesh._binaryInfo;
  21143. }
  21144. mesh._delayInfo = [];
  21145. if (parsedMesh.hasUVs) {
  21146. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21147. }
  21148. if (parsedMesh.hasUVs2) {
  21149. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21150. }
  21151. if (parsedMesh.hasUVs3) {
  21152. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21153. }
  21154. if (parsedMesh.hasUVs4) {
  21155. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21156. }
  21157. if (parsedMesh.hasUVs5) {
  21158. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21159. }
  21160. if (parsedMesh.hasUVs6) {
  21161. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21162. }
  21163. if (parsedMesh.hasColors) {
  21164. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21165. }
  21166. if (parsedMesh.hasMatricesIndices) {
  21167. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21168. }
  21169. if (parsedMesh.hasMatricesWeights) {
  21170. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21171. }
  21172. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21173. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21174. mesh._checkDelayState();
  21175. }
  21176. }
  21177. else {
  21178. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21179. }
  21180. // Material
  21181. if (parsedMesh.materialId) {
  21182. mesh.setMaterialByID(parsedMesh.materialId);
  21183. }
  21184. else {
  21185. mesh.material = null;
  21186. }
  21187. // Morph targets
  21188. if (parsedMesh.morphTargetManagerId > -1) {
  21189. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21190. }
  21191. // Skeleton
  21192. if (parsedMesh.skeletonId > -1) {
  21193. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21194. if (parsedMesh.numBoneInfluencers) {
  21195. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21196. }
  21197. }
  21198. // Animations
  21199. if (parsedMesh.animations) {
  21200. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21201. var parsedAnimation = parsedMesh.animations[animationIndex];
  21202. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21203. }
  21204. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21205. }
  21206. if (parsedMesh.autoAnimate) {
  21207. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21208. }
  21209. // Layer Mask
  21210. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21211. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21212. }
  21213. else {
  21214. mesh.layerMask = 0x0FFFFFFF;
  21215. }
  21216. // Physics
  21217. if (parsedMesh.physicsImpostor) {
  21218. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21219. mass: parsedMesh.physicsMass,
  21220. friction: parsedMesh.physicsFriction,
  21221. restitution: parsedMesh.physicsRestitution
  21222. }, scene);
  21223. }
  21224. // Instances
  21225. if (parsedMesh.instances) {
  21226. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21227. var parsedInstance = parsedMesh.instances[index];
  21228. var instance = mesh.createInstance(parsedInstance.name);
  21229. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21230. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21231. if (parsedInstance.parentId) {
  21232. instance._waitingParentId = parsedInstance.parentId;
  21233. }
  21234. if (parsedInstance.rotationQuaternion) {
  21235. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21236. }
  21237. else if (parsedInstance.rotation) {
  21238. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21239. }
  21240. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21241. instance.checkCollisions = mesh.checkCollisions;
  21242. if (parsedMesh.animations) {
  21243. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21244. parsedAnimation = parsedMesh.animations[animationIndex];
  21245. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21246. }
  21247. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21248. }
  21249. }
  21250. }
  21251. return mesh;
  21252. };
  21253. /**
  21254. * Creates a ribbon mesh.
  21255. * Please consider using the same method from the MeshBuilder class instead.
  21256. * 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.
  21257. *
  21258. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21259. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21260. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21261. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21262. * 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.
  21263. * 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.
  21264. * 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
  21265. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21266. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21268. */
  21269. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21270. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21271. pathArray: pathArray,
  21272. closeArray: closeArray,
  21273. closePath: closePath,
  21274. offset: offset,
  21275. updatable: updatable,
  21276. sideOrientation: sideOrientation,
  21277. instance: instance
  21278. }, scene);
  21279. };
  21280. /**
  21281. * Creates a plane polygonal mesh. By default, this is a disc.
  21282. * Please consider using the same method from the MeshBuilder class instead.
  21283. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21284. * 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.
  21285. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21286. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21288. */
  21289. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21290. var options = {
  21291. radius: radius,
  21292. tessellation: tessellation,
  21293. sideOrientation: sideOrientation,
  21294. updatable: updatable
  21295. };
  21296. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21297. };
  21298. /**
  21299. * Creates a box mesh.
  21300. * Please consider using the same method from the MeshBuilder class instead.
  21301. * The parameter `size` sets the size (float) of each box side (default 1).
  21302. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21303. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21304. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21305. */
  21306. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21307. var options = {
  21308. size: size,
  21309. sideOrientation: sideOrientation,
  21310. updatable: updatable
  21311. };
  21312. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21313. };
  21314. /**
  21315. * Creates a sphere mesh.
  21316. * Please consider using the same method from the MeshBuilder class instead.
  21317. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21318. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21319. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21320. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21321. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21322. */
  21323. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21324. var options = {
  21325. segments: segments,
  21326. diameterX: diameter,
  21327. diameterY: diameter,
  21328. diameterZ: diameter,
  21329. sideOrientation: sideOrientation,
  21330. updatable: updatable
  21331. };
  21332. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21333. };
  21334. /**
  21335. * Creates a cylinder or a cone mesh.
  21336. * Please consider using the same method from the MeshBuilder class instead.
  21337. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21338. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21339. * 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.
  21340. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21341. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21342. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21343. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21344. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21345. */
  21346. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21347. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21348. if (scene !== undefined) {
  21349. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21350. updatable = scene;
  21351. }
  21352. scene = subdivisions;
  21353. subdivisions = 1;
  21354. }
  21355. var options = {
  21356. height: height,
  21357. diameterTop: diameterTop,
  21358. diameterBottom: diameterBottom,
  21359. tessellation: tessellation,
  21360. subdivisions: subdivisions,
  21361. sideOrientation: sideOrientation,
  21362. updatable: updatable
  21363. };
  21364. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21365. };
  21366. // Torus (Code from SharpDX.org)
  21367. /**
  21368. * Creates a torus mesh.
  21369. * Please consider using the same method from the MeshBuilder class instead.
  21370. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21371. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21372. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21373. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21374. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21375. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21376. */
  21377. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21378. var options = {
  21379. diameter: diameter,
  21380. thickness: thickness,
  21381. tessellation: tessellation,
  21382. sideOrientation: sideOrientation,
  21383. updatable: updatable
  21384. };
  21385. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21386. };
  21387. /**
  21388. * Creates a torus knot mesh.
  21389. * Please consider using the same method from the MeshBuilder class instead.
  21390. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21391. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21392. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21393. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21397. */
  21398. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21399. var options = {
  21400. radius: radius,
  21401. tube: tube,
  21402. radialSegments: radialSegments,
  21403. tubularSegments: tubularSegments,
  21404. p: p,
  21405. q: q,
  21406. sideOrientation: sideOrientation,
  21407. updatable: updatable
  21408. };
  21409. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21410. };
  21411. /**
  21412. * Creates a line mesh.
  21413. * Please consider using the same method from the MeshBuilder class instead.
  21414. * 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.
  21415. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21416. * The parameter `points` is an array successive Vector3.
  21417. * 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
  21418. * When updating an instance, remember that only point positions can change, not the number of points.
  21419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21420. */
  21421. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21422. var options = {
  21423. points: points,
  21424. updatable: updatable,
  21425. instance: instance
  21426. };
  21427. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21428. };
  21429. /**
  21430. * Creates a dashed line mesh.
  21431. * Please consider using the same method from the MeshBuilder class instead.
  21432. * 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.
  21433. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21434. * The parameter `points` is an array successive Vector3.
  21435. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21436. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21437. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21438. * 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
  21439. * When updating an instance, remember that only point positions can change, not the number of points.
  21440. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21441. */
  21442. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21443. var options = {
  21444. points: points,
  21445. dashSize: dashSize,
  21446. gapSize: gapSize,
  21447. dashNb: dashNb,
  21448. updatable: updatable,
  21449. instance: instance
  21450. };
  21451. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21452. };
  21453. /**
  21454. * Creates a polygon mesh.
  21455. * Please consider using the same method from the MeshBuilder class instead.
  21456. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21457. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  21458. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21460. * Remember you can only change the shape positions, not their number when updating a polygon.
  21461. */
  21462. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21463. var options = {
  21464. shape: shape,
  21465. holes: holes,
  21466. updatable: updatable,
  21467. sideOrientation: sideOrientation
  21468. };
  21469. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21470. };
  21471. /**
  21472. * Creates an extruded polygon mesh, with depth in the Y direction.
  21473. * Please consider using the same method from the MeshBuilder class instead.
  21474. */
  21475. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21476. var options = {
  21477. shape: shape,
  21478. holes: holes,
  21479. depth: depth,
  21480. updatable: updatable,
  21481. sideOrientation: sideOrientation
  21482. };
  21483. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21484. };
  21485. /**
  21486. * Creates an extruded shape mesh.
  21487. * 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.
  21488. * Please consider using the same method from the MeshBuilder class instead.
  21489. *
  21490. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21491. * 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
  21492. * extruded along the Z axis.
  21493. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21494. * 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.
  21495. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21496. * 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
  21497. * 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
  21498. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21499. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21500. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21501. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21502. */
  21503. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21504. var options = {
  21505. shape: shape,
  21506. path: path,
  21507. scale: scale,
  21508. rotation: rotation,
  21509. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21510. sideOrientation: sideOrientation,
  21511. instance: instance,
  21512. updatable: updatable
  21513. };
  21514. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21515. };
  21516. /**
  21517. * Creates an custom extruded shape mesh.
  21518. * 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.
  21519. * Please consider using the same method from the MeshBuilder class instead.
  21520. *
  21521. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21522. * 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
  21523. * extruded along the Z axis.
  21524. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21525. * 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
  21526. * and the distance of this point from the begining of the path :
  21527. * ```javascript
  21528. * var rotationFunction = function(i, distance) {
  21529. * // do things
  21530. * return rotationValue; }
  21531. * ```
  21532. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21533. * 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
  21534. * and the distance of this point from the begining of the path :
  21535. * ```javascript
  21536. * var scaleFunction = function(i, distance) {
  21537. * // do things
  21538. * return scaleValue;}
  21539. * ```
  21540. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21541. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21542. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21543. * 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
  21544. * 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
  21545. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21546. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21547. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21548. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21549. */
  21550. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21551. var options = {
  21552. shape: shape,
  21553. path: path,
  21554. scaleFunction: scaleFunction,
  21555. rotationFunction: rotationFunction,
  21556. ribbonCloseArray: ribbonCloseArray,
  21557. ribbonClosePath: ribbonClosePath,
  21558. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21559. sideOrientation: sideOrientation,
  21560. instance: instance,
  21561. updatable: updatable
  21562. };
  21563. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21564. };
  21565. /**
  21566. * Creates lathe mesh.
  21567. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21568. * Please consider using the same method from the MeshBuilder class instead.
  21569. * 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
  21570. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21571. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21572. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21574. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21576. */
  21577. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21578. var options = {
  21579. shape: shape,
  21580. radius: radius,
  21581. tessellation: tessellation,
  21582. sideOrientation: sideOrientation,
  21583. updatable: updatable
  21584. };
  21585. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21586. };
  21587. /**
  21588. * Creates a plane mesh.
  21589. * Please consider using the same method from the MeshBuilder class instead.
  21590. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21591. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21592. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21593. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21594. */
  21595. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21596. var options = {
  21597. size: size,
  21598. width: size,
  21599. height: size,
  21600. sideOrientation: sideOrientation,
  21601. updatable: updatable
  21602. };
  21603. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21604. };
  21605. /**
  21606. * Creates a ground mesh.
  21607. * Please consider using the same method from the MeshBuilder class instead.
  21608. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21609. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21611. */
  21612. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21613. var options = {
  21614. width: width,
  21615. height: height,
  21616. subdivisions: subdivisions,
  21617. updatable: updatable
  21618. };
  21619. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21620. };
  21621. /**
  21622. * Creates a tiled ground mesh.
  21623. * Please consider using the same method from the MeshBuilder class instead.
  21624. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21625. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21626. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21627. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21628. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21629. * numbers of subdivisions on the ground width and height of each tile.
  21630. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21631. */
  21632. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21633. var options = {
  21634. xmin: xmin,
  21635. zmin: zmin,
  21636. xmax: xmax,
  21637. zmax: zmax,
  21638. subdivisions: subdivisions,
  21639. precision: precision,
  21640. updatable: updatable
  21641. };
  21642. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21643. };
  21644. /**
  21645. * Creates a ground mesh from a height map.
  21646. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21647. * Please consider using the same method from the MeshBuilder class instead.
  21648. * The parameter `url` sets the URL of the height map image resource.
  21649. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21650. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21651. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21652. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21653. * 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).
  21654. * This function is passed the newly built mesh :
  21655. * ```javascript
  21656. * function(mesh) { // do things
  21657. * return; }
  21658. * ```
  21659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21660. */
  21661. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21662. var options = {
  21663. width: width,
  21664. height: height,
  21665. subdivisions: subdivisions,
  21666. minHeight: minHeight,
  21667. maxHeight: maxHeight,
  21668. updatable: updatable,
  21669. onReady: onReady
  21670. };
  21671. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21672. };
  21673. /**
  21674. * Creates a tube mesh.
  21675. * 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.
  21676. * Please consider using the same method from the MeshBuilder class instead.
  21677. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21678. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21679. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21680. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21681. * 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.
  21682. * It must return a radius value (positive float) :
  21683. * ```javascript
  21684. * var radiusFunction = function(i, distance) {
  21685. * // do things
  21686. * return radius; }
  21687. * ```
  21688. * 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
  21689. * 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
  21690. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21691. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21693. */
  21694. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21695. var options = {
  21696. path: path,
  21697. radius: radius,
  21698. tessellation: tessellation,
  21699. radiusFunction: radiusFunction,
  21700. arc: 1,
  21701. cap: cap,
  21702. updatable: updatable,
  21703. sideOrientation: sideOrientation,
  21704. instance: instance
  21705. };
  21706. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21707. };
  21708. /**
  21709. * Creates a polyhedron mesh.
  21710. * Please consider using the same method from the MeshBuilder class instead.
  21711. * 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
  21712. * to choose the wanted type.
  21713. * The parameter `size` (positive float, default 1) sets the polygon size.
  21714. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21715. * 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`.
  21716. * 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
  21717. * 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)`).
  21718. * 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
  21719. * 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.
  21720. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21721. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21722. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21723. */
  21724. Mesh.CreatePolyhedron = function (name, options, scene) {
  21725. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21726. };
  21727. /**
  21728. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21729. * Please consider using the same method from the MeshBuilder class instead.
  21730. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21731. * 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`).
  21732. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21733. * 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.
  21734. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21735. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21736. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21737. */
  21738. Mesh.CreateIcoSphere = function (name, options, scene) {
  21739. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21740. };
  21741. /**
  21742. * Creates a decal mesh.
  21743. * Please consider using the same method from the MeshBuilder class instead.
  21744. * 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.
  21745. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21746. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21747. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21748. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21749. */
  21750. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21751. var options = {
  21752. position: position,
  21753. normal: normal,
  21754. size: size,
  21755. angle: angle
  21756. };
  21757. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21758. };
  21759. // Skeletons
  21760. /**
  21761. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21762. */
  21763. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21764. var source;
  21765. if (!this._sourcePositions) {
  21766. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21767. this._sourcePositions = new Float32Array(source);
  21768. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21769. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21770. }
  21771. }
  21772. return this._sourcePositions;
  21773. };
  21774. /**
  21775. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21776. */
  21777. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21778. var source;
  21779. if (!this._sourceNormals) {
  21780. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21781. this._sourceNormals = new Float32Array(source);
  21782. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21783. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21784. }
  21785. }
  21786. return this._sourceNormals;
  21787. };
  21788. /**
  21789. * Updates the vertex buffer by applying transformation from the bones.
  21790. * Returns the Mesh.
  21791. *
  21792. * @param {skeleton} skeleton to apply
  21793. */
  21794. Mesh.prototype.applySkeleton = function (skeleton) {
  21795. if (!this.geometry) {
  21796. return this;
  21797. }
  21798. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21799. return this;
  21800. }
  21801. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21802. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21803. return this;
  21804. }
  21805. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21806. return this;
  21807. }
  21808. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21809. return this;
  21810. }
  21811. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21812. return this;
  21813. }
  21814. if (!this._sourcePositions) {
  21815. var submeshes = this.subMeshes.slice();
  21816. this.setPositionsForCPUSkinning();
  21817. this.subMeshes = submeshes;
  21818. }
  21819. if (!this._sourceNormals) {
  21820. this.setNormalsForCPUSkinning();
  21821. }
  21822. // positionsData checks for not being Float32Array will only pass at most once
  21823. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21824. if (!(positionsData instanceof Float32Array)) {
  21825. positionsData = new Float32Array(positionsData);
  21826. }
  21827. // normalsData checks for not being Float32Array will only pass at most once
  21828. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21829. if (!(normalsData instanceof Float32Array)) {
  21830. normalsData = new Float32Array(normalsData);
  21831. }
  21832. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21833. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21834. var needExtras = this.numBoneInfluencers > 4;
  21835. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21836. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21837. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21838. var tempVector3 = BABYLON.Vector3.Zero();
  21839. var finalMatrix = new BABYLON.Matrix();
  21840. var tempMatrix = new BABYLON.Matrix();
  21841. var matWeightIdx = 0;
  21842. var inf;
  21843. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21844. var weight;
  21845. for (inf = 0; inf < 4; inf++) {
  21846. weight = matricesWeightsData[matWeightIdx + inf];
  21847. if (weight > 0) {
  21848. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21849. finalMatrix.addToSelf(tempMatrix);
  21850. }
  21851. else
  21852. break;
  21853. }
  21854. if (needExtras) {
  21855. for (inf = 0; inf < 4; inf++) {
  21856. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21857. if (weight > 0) {
  21858. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21859. finalMatrix.addToSelf(tempMatrix);
  21860. }
  21861. else
  21862. break;
  21863. }
  21864. }
  21865. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21866. tempVector3.toArray(positionsData, index);
  21867. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21868. tempVector3.toArray(normalsData, index);
  21869. finalMatrix.reset();
  21870. }
  21871. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21872. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21873. return this;
  21874. };
  21875. // Tools
  21876. /**
  21877. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21878. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21879. */
  21880. Mesh.MinMax = function (meshes) {
  21881. var minVector = null;
  21882. var maxVector = null;
  21883. meshes.forEach(function (mesh, index, array) {
  21884. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21885. if (!minVector) {
  21886. minVector = boundingBox.minimumWorld;
  21887. maxVector = boundingBox.maximumWorld;
  21888. }
  21889. else {
  21890. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21891. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21892. }
  21893. });
  21894. return {
  21895. min: minVector,
  21896. max: maxVector
  21897. };
  21898. };
  21899. /**
  21900. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21901. */
  21902. Mesh.Center = function (meshesOrMinMaxVector) {
  21903. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21904. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21905. };
  21906. /**
  21907. * Merge the array of meshes into a single mesh for performance reasons.
  21908. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21909. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21910. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21911. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21912. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  21913. */
  21914. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  21915. if (disposeSource === void 0) { disposeSource = true; }
  21916. var index;
  21917. if (!allow32BitsIndices) {
  21918. var totalVertices = 0;
  21919. // Counting vertices
  21920. for (index = 0; index < meshes.length; index++) {
  21921. if (meshes[index]) {
  21922. totalVertices += meshes[index].getTotalVertices();
  21923. if (totalVertices > 65536) {
  21924. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21925. return null;
  21926. }
  21927. }
  21928. }
  21929. }
  21930. // Merge
  21931. var vertexData;
  21932. var otherVertexData;
  21933. var indiceArray = new Array();
  21934. var source;
  21935. for (index = 0; index < meshes.length; index++) {
  21936. if (meshes[index]) {
  21937. meshes[index].computeWorldMatrix(true);
  21938. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21939. otherVertexData.transform(meshes[index].getWorldMatrix());
  21940. if (vertexData) {
  21941. vertexData.merge(otherVertexData);
  21942. }
  21943. else {
  21944. vertexData = otherVertexData;
  21945. source = meshes[index];
  21946. }
  21947. if (subdivideWithSubMeshes) {
  21948. indiceArray.push(meshes[index].getTotalIndices());
  21949. }
  21950. }
  21951. }
  21952. if (!meshSubclass) {
  21953. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21954. }
  21955. vertexData.applyToMesh(meshSubclass);
  21956. // Setting properties
  21957. meshSubclass.material = source.material;
  21958. meshSubclass.checkCollisions = source.checkCollisions;
  21959. // Cleaning
  21960. if (disposeSource) {
  21961. for (index = 0; index < meshes.length; index++) {
  21962. if (meshes[index]) {
  21963. meshes[index].dispose();
  21964. }
  21965. }
  21966. }
  21967. // Subdivide
  21968. if (subdivideWithSubMeshes) {
  21969. //-- Suppresions du submesh global
  21970. meshSubclass.releaseSubMeshes();
  21971. index = 0;
  21972. var offset = 0;
  21973. //-- aplique la subdivision en fonction du tableau d'indices
  21974. while (index < indiceArray.length) {
  21975. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  21976. offset += indiceArray[index];
  21977. index++;
  21978. }
  21979. }
  21980. return meshSubclass;
  21981. };
  21982. return Mesh;
  21983. }(BABYLON.AbstractMesh));
  21984. // Consts
  21985. Mesh._FRONTSIDE = 0;
  21986. Mesh._BACKSIDE = 1;
  21987. Mesh._DOUBLESIDE = 2;
  21988. Mesh._DEFAULTSIDE = 0;
  21989. Mesh._NO_CAP = 0;
  21990. Mesh._CAP_START = 1;
  21991. Mesh._CAP_END = 2;
  21992. Mesh._CAP_ALL = 3;
  21993. BABYLON.Mesh = Mesh;
  21994. })(BABYLON || (BABYLON = {}));
  21995. //# sourceMappingURL=babylon.mesh.js.map
  21996. var BABYLON;
  21997. (function (BABYLON) {
  21998. var SubMesh = (function () {
  21999. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22000. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22001. this.materialIndex = materialIndex;
  22002. this.verticesStart = verticesStart;
  22003. this.verticesCount = verticesCount;
  22004. this.indexStart = indexStart;
  22005. this.indexCount = indexCount;
  22006. this._renderId = 0;
  22007. this._mesh = mesh;
  22008. this._renderingMesh = renderingMesh || mesh;
  22009. mesh.subMeshes.push(this);
  22010. this._trianglePlanes = [];
  22011. this._id = mesh.subMeshes.length - 1;
  22012. if (createBoundingBox) {
  22013. this.refreshBoundingInfo();
  22014. mesh.computeWorldMatrix(true);
  22015. }
  22016. }
  22017. Object.defineProperty(SubMesh.prototype, "effect", {
  22018. get: function () {
  22019. return this._materialEffect;
  22020. },
  22021. enumerable: true,
  22022. configurable: true
  22023. });
  22024. SubMesh.prototype.setEffect = function (effect, defines) {
  22025. if (this._materialEffect === effect) {
  22026. return;
  22027. }
  22028. this._materialDefines = defines;
  22029. this._materialEffect = effect;
  22030. };
  22031. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22032. get: function () {
  22033. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22034. },
  22035. enumerable: true,
  22036. configurable: true
  22037. });
  22038. /**
  22039. * Returns the submesh BoudingInfo object.
  22040. */
  22041. SubMesh.prototype.getBoundingInfo = function () {
  22042. if (this.IsGlobal) {
  22043. return this._mesh.getBoundingInfo();
  22044. }
  22045. return this._boundingInfo;
  22046. };
  22047. /**
  22048. * Sets the submesh BoundingInfo.
  22049. * Return the SubMesh.
  22050. */
  22051. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22052. this._boundingInfo = boundingInfo;
  22053. return this;
  22054. };
  22055. /**
  22056. * Returns the mesh of the current submesh.
  22057. */
  22058. SubMesh.prototype.getMesh = function () {
  22059. return this._mesh;
  22060. };
  22061. /**
  22062. * Returns the rendering mesh of the submesh.
  22063. */
  22064. SubMesh.prototype.getRenderingMesh = function () {
  22065. return this._renderingMesh;
  22066. };
  22067. /**
  22068. * Returns the submesh material.
  22069. */
  22070. SubMesh.prototype.getMaterial = function () {
  22071. var rootMaterial = this._renderingMesh.material;
  22072. if (rootMaterial && rootMaterial.getSubMaterial) {
  22073. var multiMaterial = rootMaterial;
  22074. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22075. if (this._currentMaterial !== effectiveMaterial) {
  22076. this._currentMaterial = effectiveMaterial;
  22077. if (this._materialDefines) {
  22078. this._materialDefines.markAllAsDirty();
  22079. }
  22080. }
  22081. return effectiveMaterial;
  22082. }
  22083. if (!rootMaterial) {
  22084. return this._mesh.getScene().defaultMaterial;
  22085. }
  22086. return rootMaterial;
  22087. };
  22088. // Methods
  22089. /**
  22090. * Sets a new updated BoundingInfo object to the submesh.
  22091. * Returns the SubMesh.
  22092. */
  22093. SubMesh.prototype.refreshBoundingInfo = function () {
  22094. this._lastColliderWorldVertices = null;
  22095. if (this.IsGlobal) {
  22096. return;
  22097. }
  22098. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22099. if (!data) {
  22100. this._boundingInfo = this._mesh._boundingInfo;
  22101. return;
  22102. }
  22103. var indices = this._renderingMesh.getIndices();
  22104. var extend;
  22105. //is this the only submesh?
  22106. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22107. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22108. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22109. }
  22110. else {
  22111. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22112. }
  22113. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22114. return this;
  22115. };
  22116. SubMesh.prototype._checkCollision = function (collider) {
  22117. return this.getBoundingInfo()._checkCollision(collider);
  22118. };
  22119. /**
  22120. * Updates the submesh BoundingInfo.
  22121. * Returns the Submesh.
  22122. */
  22123. SubMesh.prototype.updateBoundingInfo = function (world) {
  22124. if (!this.getBoundingInfo()) {
  22125. this.refreshBoundingInfo();
  22126. }
  22127. this.getBoundingInfo().update(world);
  22128. return this;
  22129. };
  22130. /**
  22131. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22132. * Boolean returned.
  22133. */
  22134. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22135. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22136. };
  22137. /**
  22138. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22139. * Boolean returned.
  22140. */
  22141. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22142. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22143. };
  22144. /**
  22145. * Renders the submesh.
  22146. * Returns it.
  22147. */
  22148. SubMesh.prototype.render = function (enableAlphaMode) {
  22149. this._renderingMesh.render(this, enableAlphaMode);
  22150. return this;
  22151. };
  22152. /**
  22153. * Returns a new Index Buffer.
  22154. * Type returned : WebGLBuffer.
  22155. */
  22156. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22157. if (!this._linesIndexBuffer) {
  22158. var linesIndices = [];
  22159. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22160. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22161. }
  22162. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22163. this.linesIndexCount = linesIndices.length;
  22164. }
  22165. return this._linesIndexBuffer;
  22166. };
  22167. /**
  22168. * True is the passed Ray intersects the submesh bounding box.
  22169. * Boolean returned.
  22170. */
  22171. SubMesh.prototype.canIntersects = function (ray) {
  22172. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22173. };
  22174. /**
  22175. * Returns an object IntersectionInfo.
  22176. */
  22177. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22178. var intersectInfo = null;
  22179. // LineMesh first as it's also a Mesh...
  22180. if (this._mesh instanceof BABYLON.LinesMesh) {
  22181. var lineMesh = this._mesh;
  22182. // Line test
  22183. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22184. var p0 = positions[indices[index]];
  22185. var p1 = positions[indices[index + 1]];
  22186. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22187. if (length < 0) {
  22188. continue;
  22189. }
  22190. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22191. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22192. if (fastCheck) {
  22193. break;
  22194. }
  22195. }
  22196. }
  22197. }
  22198. else {
  22199. // Triangles test
  22200. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22201. var p0 = positions[indices[index]];
  22202. var p1 = positions[indices[index + 1]];
  22203. var p2 = positions[indices[index + 2]];
  22204. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22205. if (currentIntersectInfo) {
  22206. if (currentIntersectInfo.distance < 0) {
  22207. continue;
  22208. }
  22209. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22210. intersectInfo = currentIntersectInfo;
  22211. intersectInfo.faceId = index / 3;
  22212. if (fastCheck) {
  22213. break;
  22214. }
  22215. }
  22216. }
  22217. }
  22218. }
  22219. return intersectInfo;
  22220. };
  22221. // Clone
  22222. /**
  22223. * Creates a new Submesh from the passed Mesh.
  22224. */
  22225. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22226. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22227. if (!this.IsGlobal) {
  22228. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22229. }
  22230. return result;
  22231. };
  22232. // Dispose
  22233. /**
  22234. * Disposes the Submesh.
  22235. * Returns nothing.
  22236. */
  22237. SubMesh.prototype.dispose = function () {
  22238. if (this._linesIndexBuffer) {
  22239. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22240. this._linesIndexBuffer = null;
  22241. }
  22242. // Remove from mesh
  22243. var index = this._mesh.subMeshes.indexOf(this);
  22244. this._mesh.subMeshes.splice(index, 1);
  22245. };
  22246. // Statics
  22247. /**
  22248. * Creates a new Submesh from the passed parameters :
  22249. * - materialIndex (integer) : the index of the main mesh material.
  22250. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22251. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22252. * - mesh (Mesh) : the main mesh to create the submesh from.
  22253. * - renderingMesh (optional Mesh) : rendering mesh.
  22254. */
  22255. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22256. var minVertexIndex = Number.MAX_VALUE;
  22257. var maxVertexIndex = -Number.MAX_VALUE;
  22258. renderingMesh = renderingMesh || mesh;
  22259. var indices = renderingMesh.getIndices();
  22260. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22261. var vertexIndex = indices[index];
  22262. if (vertexIndex < minVertexIndex)
  22263. minVertexIndex = vertexIndex;
  22264. if (vertexIndex > maxVertexIndex)
  22265. maxVertexIndex = vertexIndex;
  22266. }
  22267. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22268. };
  22269. return SubMesh;
  22270. }());
  22271. BABYLON.SubMesh = SubMesh;
  22272. })(BABYLON || (BABYLON = {}));
  22273. //# sourceMappingURL=babylon.subMesh.js.map
  22274. var BABYLON;
  22275. (function (BABYLON) {
  22276. var EffectFallbacks = (function () {
  22277. function EffectFallbacks() {
  22278. this._defines = {};
  22279. this._currentRank = 32;
  22280. this._maxRank = -1;
  22281. }
  22282. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22283. if (!this._defines[rank]) {
  22284. if (rank < this._currentRank) {
  22285. this._currentRank = rank;
  22286. }
  22287. if (rank > this._maxRank) {
  22288. this._maxRank = rank;
  22289. }
  22290. this._defines[rank] = new Array();
  22291. }
  22292. this._defines[rank].push(define);
  22293. };
  22294. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22295. this._meshRank = rank;
  22296. this._mesh = mesh;
  22297. if (rank < this._currentRank) {
  22298. this._currentRank = rank;
  22299. }
  22300. if (rank > this._maxRank) {
  22301. this._maxRank = rank;
  22302. }
  22303. };
  22304. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22305. get: function () {
  22306. return this._currentRank <= this._maxRank;
  22307. },
  22308. enumerable: true,
  22309. configurable: true
  22310. });
  22311. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22312. // First we try to switch to CPU skinning
  22313. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22314. this._mesh.computeBonesUsingShaders = false;
  22315. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22316. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22317. var scene = this._mesh.getScene();
  22318. for (var index = 0; index < scene.meshes.length; index++) {
  22319. var otherMesh = scene.meshes[index];
  22320. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22321. otherMesh.computeBonesUsingShaders = false;
  22322. }
  22323. }
  22324. }
  22325. else {
  22326. var currentFallbacks = this._defines[this._currentRank];
  22327. if (currentFallbacks) {
  22328. for (var index = 0; index < currentFallbacks.length; index++) {
  22329. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22330. }
  22331. }
  22332. this._currentRank++;
  22333. }
  22334. return currentDefines;
  22335. };
  22336. return EffectFallbacks;
  22337. }());
  22338. BABYLON.EffectFallbacks = EffectFallbacks;
  22339. var EffectCreationOptions = (function () {
  22340. function EffectCreationOptions() {
  22341. }
  22342. return EffectCreationOptions;
  22343. }());
  22344. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22345. var Effect = (function () {
  22346. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22347. var _this = this;
  22348. this.uniqueId = 0;
  22349. this._uniformBuffersNames = {};
  22350. this._isReady = false;
  22351. this._compilationError = "";
  22352. this._valueCache = {};
  22353. this.name = baseName;
  22354. if (attributesNamesOrOptions.attributes) {
  22355. var options = attributesNamesOrOptions;
  22356. this._engine = uniformsNamesOrEngine;
  22357. this._attributesNames = options.attributes;
  22358. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22359. this._samplers = options.samplers;
  22360. this.defines = options.defines;
  22361. this.onError = options.onError;
  22362. this.onCompiled = options.onCompiled;
  22363. this._fallbacks = options.fallbacks;
  22364. this._indexParameters = options.indexParameters;
  22365. if (options.uniformBuffersNames) {
  22366. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22367. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22368. }
  22369. }
  22370. }
  22371. else {
  22372. this._engine = engine;
  22373. this.defines = defines;
  22374. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22375. this._samplers = samplers;
  22376. this._attributesNames = attributesNamesOrOptions;
  22377. this.onError = onError;
  22378. this.onCompiled = onCompiled;
  22379. this._indexParameters = indexParameters;
  22380. this._fallbacks = fallbacks;
  22381. }
  22382. this.uniqueId = Effect._uniqueIdSeed++;
  22383. var vertexSource;
  22384. var fragmentSource;
  22385. if (baseName.vertexElement) {
  22386. vertexSource = document.getElementById(baseName.vertexElement);
  22387. if (!vertexSource) {
  22388. vertexSource = baseName.vertexElement;
  22389. }
  22390. }
  22391. else {
  22392. vertexSource = baseName.vertex || baseName;
  22393. }
  22394. if (baseName.fragmentElement) {
  22395. fragmentSource = document.getElementById(baseName.fragmentElement);
  22396. if (!fragmentSource) {
  22397. fragmentSource = baseName.fragmentElement;
  22398. }
  22399. }
  22400. else {
  22401. fragmentSource = baseName.fragment || baseName;
  22402. }
  22403. this._loadVertexShader(vertexSource, function (vertexCode) {
  22404. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22405. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22406. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22407. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22408. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22409. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22410. });
  22411. });
  22412. });
  22413. });
  22414. });
  22415. });
  22416. }
  22417. Object.defineProperty(Effect.prototype, "key", {
  22418. get: function () {
  22419. return this._key;
  22420. },
  22421. enumerable: true,
  22422. configurable: true
  22423. });
  22424. // Properties
  22425. Effect.prototype.isReady = function () {
  22426. return this._isReady;
  22427. };
  22428. Effect.prototype.getProgram = function () {
  22429. return this._program;
  22430. };
  22431. Effect.prototype.getAttributesNames = function () {
  22432. return this._attributesNames;
  22433. };
  22434. Effect.prototype.getAttributeLocation = function (index) {
  22435. return this._attributes[index];
  22436. };
  22437. Effect.prototype.getAttributeLocationByName = function (name) {
  22438. var index = this._attributesNames.indexOf(name);
  22439. return this._attributes[index];
  22440. };
  22441. Effect.prototype.getAttributesCount = function () {
  22442. return this._attributes.length;
  22443. };
  22444. Effect.prototype.getUniformIndex = function (uniformName) {
  22445. return this._uniformsNames.indexOf(uniformName);
  22446. };
  22447. Effect.prototype.getUniform = function (uniformName) {
  22448. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22449. };
  22450. Effect.prototype.getSamplers = function () {
  22451. return this._samplers;
  22452. };
  22453. Effect.prototype.getCompilationError = function () {
  22454. return this._compilationError;
  22455. };
  22456. Effect.prototype.getVertexShaderSource = function () {
  22457. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22458. };
  22459. Effect.prototype.getFragmentShaderSource = function () {
  22460. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22461. };
  22462. // Methods
  22463. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22464. // DOM element ?
  22465. if (vertex instanceof HTMLElement) {
  22466. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22467. callback(vertexCode);
  22468. return;
  22469. }
  22470. // Base64 encoded ?
  22471. if (vertex.substr(0, 7) === "base64:") {
  22472. var vertexBinary = window.atob(vertex.substr(7));
  22473. callback(vertexBinary);
  22474. return;
  22475. }
  22476. // Is in local store ?
  22477. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22478. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22479. return;
  22480. }
  22481. var vertexShaderUrl;
  22482. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22483. vertexShaderUrl = vertex;
  22484. }
  22485. else {
  22486. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22487. }
  22488. // Vertex shader
  22489. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22490. };
  22491. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22492. // DOM element ?
  22493. if (fragment instanceof HTMLElement) {
  22494. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22495. callback(fragmentCode);
  22496. return;
  22497. }
  22498. // Base64 encoded ?
  22499. if (fragment.substr(0, 7) === "base64:") {
  22500. var fragmentBinary = window.atob(fragment.substr(7));
  22501. callback(fragmentBinary);
  22502. return;
  22503. }
  22504. // Is in local store ?
  22505. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22506. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22507. return;
  22508. }
  22509. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22510. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22511. return;
  22512. }
  22513. var fragmentShaderUrl;
  22514. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22515. fragmentShaderUrl = fragment;
  22516. }
  22517. else {
  22518. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22519. }
  22520. // Fragment shader
  22521. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22522. };
  22523. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22524. // Rebuild shaders source code
  22525. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22526. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22527. vertexCode = prefix + vertexCode;
  22528. fragmentCode = prefix + fragmentCode;
  22529. // Number lines of shaders source code
  22530. var i = 2;
  22531. var regex = /\n/gm;
  22532. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22533. i = 2;
  22534. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22535. // Dump shaders name and formatted source code
  22536. if (this.name.vertexElement) {
  22537. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22538. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22539. }
  22540. else if (this.name.vertex) {
  22541. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22542. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22543. }
  22544. else {
  22545. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22546. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22547. }
  22548. };
  22549. ;
  22550. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22551. var preparedSourceCode = this._processPrecision(sourceCode);
  22552. if (this._engine.webGLVersion == 1) {
  22553. callback(preparedSourceCode);
  22554. return;
  22555. }
  22556. // Already converted
  22557. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22558. callback(preparedSourceCode.replace("#version 300 es", ""));
  22559. return;
  22560. }
  22561. // Remove extensions
  22562. // #extension GL_OES_standard_derivatives : enable
  22563. // #extension GL_EXT_shader_texture_lod : enable
  22564. // #extension GL_EXT_frag_depth : enable
  22565. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22566. var result = preparedSourceCode.replace(regex, "");
  22567. // Migrate to GLSL v300
  22568. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22569. result = result.replace(/attribute[ \t]/g, "in ");
  22570. result = result.replace(/[ \t]attribute/g, " in");
  22571. if (isFragment) {
  22572. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22573. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22574. result = result.replace(/texture2D\(/g, "texture(");
  22575. result = result.replace(/textureCube\(/g, "texture(");
  22576. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22577. result = result.replace(/gl_FragColor/g, "glFragColor");
  22578. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22579. }
  22580. callback(result);
  22581. };
  22582. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22583. var _this = this;
  22584. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22585. var match = regex.exec(sourceCode);
  22586. var returnValue = new String(sourceCode);
  22587. while (match != null) {
  22588. var includeFile = match[1];
  22589. // Uniform declaration
  22590. if (includeFile.indexOf("__decl__") !== -1) {
  22591. includeFile = includeFile.replace(/__decl__/, "");
  22592. if (this._engine.webGLVersion != 1) {
  22593. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22594. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22595. }
  22596. includeFile = includeFile + "Declaration";
  22597. }
  22598. if (Effect.IncludesShadersStore[includeFile]) {
  22599. // Substitution
  22600. var includeContent = Effect.IncludesShadersStore[includeFile];
  22601. if (match[2]) {
  22602. var splits = match[3].split(",");
  22603. for (var index = 0; index < splits.length; index += 2) {
  22604. var source = new RegExp(splits[index], "g");
  22605. var dest = splits[index + 1];
  22606. includeContent = includeContent.replace(source, dest);
  22607. }
  22608. }
  22609. if (match[4]) {
  22610. var indexString = match[5];
  22611. if (indexString.indexOf("..") !== -1) {
  22612. var indexSplits = indexString.split("..");
  22613. var minIndex = parseInt(indexSplits[0]);
  22614. var maxIndex = parseInt(indexSplits[1]);
  22615. var sourceIncludeContent = includeContent.slice(0);
  22616. includeContent = "";
  22617. if (isNaN(maxIndex)) {
  22618. maxIndex = this._indexParameters[indexSplits[1]];
  22619. }
  22620. for (var i = minIndex; i < maxIndex; i++) {
  22621. if (this._engine.webGLVersion === 1) {
  22622. // Ubo replacement
  22623. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22624. return p1 + "{X}";
  22625. });
  22626. }
  22627. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22628. }
  22629. }
  22630. else {
  22631. if (this._engine.webGLVersion === 1) {
  22632. // Ubo replacement
  22633. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22634. return p1 + "{X}";
  22635. });
  22636. }
  22637. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22638. }
  22639. }
  22640. // Replace
  22641. returnValue = returnValue.replace(match[0], includeContent);
  22642. }
  22643. else {
  22644. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22645. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22646. Effect.IncludesShadersStore[includeFile] = fileContent;
  22647. _this._processIncludes(returnValue, callback);
  22648. });
  22649. return;
  22650. }
  22651. match = regex.exec(sourceCode);
  22652. }
  22653. callback(returnValue);
  22654. };
  22655. Effect.prototype._processPrecision = function (source) {
  22656. if (source.indexOf("precision highp float") === -1) {
  22657. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22658. source = "precision mediump float;\n" + source;
  22659. }
  22660. else {
  22661. source = "precision highp float;\n" + source;
  22662. }
  22663. }
  22664. else {
  22665. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22666. source = source.replace("precision highp float", "precision mediump float");
  22667. }
  22668. }
  22669. return source;
  22670. };
  22671. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22672. try {
  22673. var engine = this._engine;
  22674. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22675. if (engine.webGLVersion > 1) {
  22676. for (var name in this._uniformBuffersNames) {
  22677. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  22678. }
  22679. }
  22680. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22681. this._attributes = engine.getAttributes(this._program, attributesNames);
  22682. var index;
  22683. for (index = 0; index < this._samplers.length; index++) {
  22684. var sampler = this.getUniform(this._samplers[index]);
  22685. if (sampler == null) {
  22686. this._samplers.splice(index, 1);
  22687. index--;
  22688. }
  22689. }
  22690. engine.bindSamplers(this);
  22691. this._compilationError = "";
  22692. this._isReady = true;
  22693. if (this.onCompiled) {
  22694. this.onCompiled(this);
  22695. }
  22696. }
  22697. catch (e) {
  22698. this._compilationError = e.message;
  22699. // Let's go through fallbacks then
  22700. BABYLON.Tools.Error("Unable to compile effect:");
  22701. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  22702. return " " + uniform;
  22703. }));
  22704. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  22705. return " " + attribute;
  22706. }));
  22707. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  22708. BABYLON.Tools.Error("Error: " + this._compilationError);
  22709. if (fallbacks && fallbacks.isMoreFallbacks) {
  22710. BABYLON.Tools.Error("Trying next fallback.");
  22711. defines = fallbacks.reduce(defines);
  22712. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22713. }
  22714. else {
  22715. if (this.onError) {
  22716. this.onError(this, this._compilationError);
  22717. }
  22718. }
  22719. }
  22720. };
  22721. Object.defineProperty(Effect.prototype, "isSupported", {
  22722. get: function () {
  22723. return this._compilationError === "";
  22724. },
  22725. enumerable: true,
  22726. configurable: true
  22727. });
  22728. Effect.prototype._bindTexture = function (channel, texture) {
  22729. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22730. };
  22731. Effect.prototype.setTexture = function (channel, texture) {
  22732. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  22733. };
  22734. Effect.prototype.setTextureArray = function (channel, textures) {
  22735. if (this._samplers.indexOf(channel + "Ex") === -1) {
  22736. var initialPos = this._samplers.indexOf(channel);
  22737. for (var index = 1; index < textures.length; index++) {
  22738. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  22739. }
  22740. }
  22741. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  22742. };
  22743. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22744. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22745. };
  22746. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22747. var cache = this._valueCache[uniformName];
  22748. var flag = matrix.updateFlag;
  22749. if (cache !== undefined && cache === flag) {
  22750. return false;
  22751. }
  22752. this._valueCache[uniformName] = flag;
  22753. return true;
  22754. };
  22755. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22756. var cache = this._valueCache[uniformName];
  22757. if (!cache) {
  22758. cache = [x, y];
  22759. this._valueCache[uniformName] = cache;
  22760. return true;
  22761. }
  22762. var changed = false;
  22763. if (cache[0] !== x) {
  22764. cache[0] = x;
  22765. changed = true;
  22766. }
  22767. if (cache[1] !== y) {
  22768. cache[1] = y;
  22769. changed = true;
  22770. }
  22771. return changed;
  22772. };
  22773. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22774. var cache = this._valueCache[uniformName];
  22775. if (!cache) {
  22776. cache = [x, y, z];
  22777. this._valueCache[uniformName] = cache;
  22778. return true;
  22779. }
  22780. var changed = false;
  22781. if (cache[0] !== x) {
  22782. cache[0] = x;
  22783. changed = true;
  22784. }
  22785. if (cache[1] !== y) {
  22786. cache[1] = y;
  22787. changed = true;
  22788. }
  22789. if (cache[2] !== z) {
  22790. cache[2] = z;
  22791. changed = true;
  22792. }
  22793. return changed;
  22794. };
  22795. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22796. var cache = this._valueCache[uniformName];
  22797. if (!cache) {
  22798. cache = [x, y, z, w];
  22799. this._valueCache[uniformName] = cache;
  22800. return true;
  22801. }
  22802. var changed = false;
  22803. if (cache[0] !== x) {
  22804. cache[0] = x;
  22805. changed = true;
  22806. }
  22807. if (cache[1] !== y) {
  22808. cache[1] = y;
  22809. changed = true;
  22810. }
  22811. if (cache[2] !== z) {
  22812. cache[2] = z;
  22813. changed = true;
  22814. }
  22815. if (cache[3] !== w) {
  22816. cache[3] = w;
  22817. changed = true;
  22818. }
  22819. return changed;
  22820. };
  22821. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  22822. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  22823. return;
  22824. }
  22825. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  22826. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  22827. };
  22828. Effect.prototype.bindUniformBlock = function (blockName, index) {
  22829. this._engine.bindUniformBlock(this._program, blockName, index);
  22830. };
  22831. Effect.prototype.setIntArray = function (uniformName, array) {
  22832. this._valueCache[uniformName] = null;
  22833. this._engine.setIntArray(this.getUniform(uniformName), array);
  22834. return this;
  22835. };
  22836. Effect.prototype.setIntArray2 = function (uniformName, array) {
  22837. this._valueCache[uniformName] = null;
  22838. this._engine.setIntArray2(this.getUniform(uniformName), array);
  22839. return this;
  22840. };
  22841. Effect.prototype.setIntArray3 = function (uniformName, array) {
  22842. this._valueCache[uniformName] = null;
  22843. this._engine.setIntArray3(this.getUniform(uniformName), array);
  22844. return this;
  22845. };
  22846. Effect.prototype.setIntArray4 = function (uniformName, array) {
  22847. this._valueCache[uniformName] = null;
  22848. this._engine.setIntArray4(this.getUniform(uniformName), array);
  22849. return this;
  22850. };
  22851. Effect.prototype.setFloatArray = function (uniformName, array) {
  22852. this._valueCache[uniformName] = null;
  22853. this._engine.setFloatArray(this.getUniform(uniformName), array);
  22854. return this;
  22855. };
  22856. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  22857. this._valueCache[uniformName] = null;
  22858. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  22859. return this;
  22860. };
  22861. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  22862. this._valueCache[uniformName] = null;
  22863. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  22864. return this;
  22865. };
  22866. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  22867. this._valueCache[uniformName] = null;
  22868. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  22869. return this;
  22870. };
  22871. Effect.prototype.setArray = function (uniformName, array) {
  22872. this._valueCache[uniformName] = null;
  22873. this._engine.setArray(this.getUniform(uniformName), array);
  22874. return this;
  22875. };
  22876. Effect.prototype.setArray2 = function (uniformName, array) {
  22877. this._valueCache[uniformName] = null;
  22878. this._engine.setArray2(this.getUniform(uniformName), array);
  22879. return this;
  22880. };
  22881. Effect.prototype.setArray3 = function (uniformName, array) {
  22882. this._valueCache[uniformName] = null;
  22883. this._engine.setArray3(this.getUniform(uniformName), array);
  22884. return this;
  22885. };
  22886. Effect.prototype.setArray4 = function (uniformName, array) {
  22887. this._valueCache[uniformName] = null;
  22888. this._engine.setArray4(this.getUniform(uniformName), array);
  22889. return this;
  22890. };
  22891. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22892. if (!matrices) {
  22893. return;
  22894. }
  22895. this._valueCache[uniformName] = null;
  22896. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22897. return this;
  22898. };
  22899. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22900. if (this._cacheMatrix(uniformName, matrix)) {
  22901. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22902. }
  22903. return this;
  22904. };
  22905. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22906. this._valueCache[uniformName] = null;
  22907. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  22908. return this;
  22909. };
  22910. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  22911. this._valueCache[uniformName] = null;
  22912. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  22913. return this;
  22914. };
  22915. Effect.prototype.setFloat = function (uniformName, value) {
  22916. var cache = this._valueCache[uniformName];
  22917. if (cache !== undefined && cache === value)
  22918. return this;
  22919. this._valueCache[uniformName] = value;
  22920. this._engine.setFloat(this.getUniform(uniformName), value);
  22921. return this;
  22922. };
  22923. Effect.prototype.setBool = function (uniformName, bool) {
  22924. var cache = this._valueCache[uniformName];
  22925. if (cache !== undefined && cache === bool)
  22926. return this;
  22927. this._valueCache[uniformName] = bool;
  22928. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  22929. return this;
  22930. };
  22931. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22932. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  22933. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22934. }
  22935. return this;
  22936. };
  22937. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22938. if (this._cacheFloat2(uniformName, x, y)) {
  22939. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22940. }
  22941. return this;
  22942. };
  22943. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22944. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  22945. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22946. }
  22947. return this;
  22948. };
  22949. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22950. if (this._cacheFloat3(uniformName, x, y, z)) {
  22951. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22952. }
  22953. return this;
  22954. };
  22955. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22956. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  22957. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22958. }
  22959. return this;
  22960. };
  22961. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22962. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  22963. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22964. }
  22965. return this;
  22966. };
  22967. Effect.prototype.setColor3 = function (uniformName, color3) {
  22968. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  22969. this._engine.setColor3(this.getUniform(uniformName), color3);
  22970. }
  22971. return this;
  22972. };
  22973. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22974. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  22975. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22976. }
  22977. return this;
  22978. };
  22979. Effect.prototype._recombineShader = function (node) {
  22980. if (node.define) {
  22981. if (node.condition) {
  22982. var defineIndex = this.defines.indexOf("#define " + node.define);
  22983. if (defineIndex === -1) {
  22984. return null;
  22985. }
  22986. var nextComma = this.defines.indexOf("\n", defineIndex);
  22987. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  22988. var condition = defineValue + node.condition;
  22989. if (!eval(condition)) {
  22990. return null;
  22991. }
  22992. }
  22993. else if (node.ndef) {
  22994. if (this.defines.indexOf("#define " + node.define) !== -1) {
  22995. return null;
  22996. }
  22997. }
  22998. else if (this.defines.indexOf("#define " + node.define) === -1) {
  22999. return null;
  23000. }
  23001. }
  23002. var result = "";
  23003. for (var index = 0; index < node.children.length; index++) {
  23004. var line = node.children[index];
  23005. if (line.children) {
  23006. var combined = this._recombineShader(line);
  23007. if (combined !== null) {
  23008. result += combined + "\r\n";
  23009. }
  23010. continue;
  23011. }
  23012. if (line.length > 0) {
  23013. result += line + "\r\n";
  23014. }
  23015. }
  23016. return result;
  23017. };
  23018. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23019. var root = {
  23020. children: []
  23021. };
  23022. var currentNode = root;
  23023. var lines = shaderString.split("\n");
  23024. for (var index = 0; index < lines.length; index++) {
  23025. var line = lines[index].trim();
  23026. // #ifdef
  23027. var pos = line.indexOf("#ifdef ");
  23028. if (pos !== -1) {
  23029. var define = line.substr(pos + 7);
  23030. var newNode = {
  23031. condition: null,
  23032. ndef: false,
  23033. define: define,
  23034. children: [],
  23035. parent: currentNode
  23036. };
  23037. currentNode.children.push(newNode);
  23038. currentNode = newNode;
  23039. continue;
  23040. }
  23041. // #ifndef
  23042. var pos = line.indexOf("#ifndef ");
  23043. if (pos !== -1) {
  23044. var define = line.substr(pos + 8);
  23045. newNode = {
  23046. condition: null,
  23047. define: define,
  23048. ndef: true,
  23049. children: [],
  23050. parent: currentNode
  23051. };
  23052. currentNode.children.push(newNode);
  23053. currentNode = newNode;
  23054. continue;
  23055. }
  23056. // #if
  23057. var pos = line.indexOf("#if ");
  23058. if (pos !== -1) {
  23059. var define = line.substr(pos + 4).trim();
  23060. var conditionPos = define.indexOf(" ");
  23061. newNode = {
  23062. condition: define.substr(conditionPos + 1),
  23063. define: define.substr(0, conditionPos),
  23064. ndef: false,
  23065. children: [],
  23066. parent: currentNode
  23067. };
  23068. currentNode.children.push(newNode);
  23069. currentNode = newNode;
  23070. continue;
  23071. }
  23072. // #endif
  23073. pos = line.indexOf("#endif");
  23074. if (pos !== -1) {
  23075. currentNode = currentNode.parent;
  23076. continue;
  23077. }
  23078. currentNode.children.push(line);
  23079. }
  23080. // Recombine
  23081. return this._recombineShader(root);
  23082. };
  23083. return Effect;
  23084. }());
  23085. Effect._uniqueIdSeed = 0;
  23086. Effect._baseCache = {};
  23087. // Statics
  23088. Effect.ShadersStore = {};
  23089. Effect.IncludesShadersStore = {};
  23090. BABYLON.Effect = Effect;
  23091. })(BABYLON || (BABYLON = {}));
  23092. //# sourceMappingURL=babylon.effect.js.map
  23093. var BABYLON;
  23094. (function (BABYLON) {
  23095. var MaterialHelper = (function () {
  23096. function MaterialHelper() {
  23097. }
  23098. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23099. if (defines._areMiscDirty) {
  23100. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23101. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23102. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23103. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23104. }
  23105. };
  23106. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  23107. var changed = false;
  23108. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23109. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23110. changed = true;
  23111. }
  23112. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  23113. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23114. changed = true;
  23115. }
  23116. if (defines["INSTANCES"] !== useInstances) {
  23117. defines["INSTANCES"] = useInstances;
  23118. changed = true;
  23119. }
  23120. if (changed) {
  23121. defines.markAsUnprocessed();
  23122. }
  23123. };
  23124. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23125. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23126. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23127. return;
  23128. }
  23129. defines._normals = defines._needNormals;
  23130. defines._uvs = defines._needUVs;
  23131. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23132. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23133. defines["TANGENT"] = true;
  23134. }
  23135. if (defines._needUVs) {
  23136. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23137. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23138. }
  23139. else {
  23140. defines["UV1"] = false;
  23141. defines["UV2"] = false;
  23142. }
  23143. if (useVertexColor) {
  23144. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23145. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23146. }
  23147. if (useBones) {
  23148. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23149. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23150. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23151. }
  23152. else {
  23153. defines["NUM_BONE_INFLUENCERS"] = 0;
  23154. defines["BonesPerMesh"] = 0;
  23155. }
  23156. }
  23157. if (useMorphTargets) {
  23158. if (mesh.morphTargetManager) {
  23159. var manager = mesh.morphTargetManager;
  23160. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23161. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23162. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23163. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23164. }
  23165. else {
  23166. defines["MORPHTARGETS_TANGENT"] = false;
  23167. defines["MORPHTARGETS_NORMAL"] = false;
  23168. defines["MORPHTARGETS"] = false;
  23169. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23170. }
  23171. }
  23172. };
  23173. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23174. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23175. if (disableLighting === void 0) { disableLighting = false; }
  23176. if (!defines._areLightsDirty) {
  23177. return defines._needNormals;
  23178. }
  23179. var lightIndex = 0;
  23180. var needNormals = false;
  23181. var needRebuild = false;
  23182. var lightmapMode = false;
  23183. var shadowEnabled = false;
  23184. var specularEnabled = false;
  23185. if (scene.lightsEnabled && !disableLighting) {
  23186. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23187. var light = _a[_i];
  23188. needNormals = true;
  23189. if (defines["LIGHT" + lightIndex] === undefined) {
  23190. needRebuild = true;
  23191. }
  23192. defines["LIGHT" + lightIndex] = true;
  23193. defines["SPOTLIGHT" + lightIndex] = false;
  23194. defines["HEMILIGHT" + lightIndex] = false;
  23195. defines["POINTLIGHT" + lightIndex] = false;
  23196. defines["DIRLIGHT" + lightIndex] = false;
  23197. var type;
  23198. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23199. type = "SPOTLIGHT" + lightIndex;
  23200. }
  23201. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23202. type = "HEMILIGHT" + lightIndex;
  23203. }
  23204. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23205. type = "POINTLIGHT" + lightIndex;
  23206. }
  23207. else {
  23208. type = "DIRLIGHT" + lightIndex;
  23209. }
  23210. defines[type] = true;
  23211. // Specular
  23212. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23213. specularEnabled = true;
  23214. }
  23215. // Shadows
  23216. defines["SHADOW" + lightIndex] = false;
  23217. defines["SHADOWPCF" + lightIndex] = false;
  23218. defines["SHADOWESM" + lightIndex] = false;
  23219. defines["SHADOWCUBE" + lightIndex] = false;
  23220. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23221. var shadowGenerator = light.getShadowGenerator();
  23222. if (shadowGenerator) {
  23223. shadowEnabled = true;
  23224. shadowGenerator.prepareDefines(defines, lightIndex);
  23225. }
  23226. }
  23227. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23228. lightmapMode = true;
  23229. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23230. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23231. }
  23232. else {
  23233. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23234. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23235. }
  23236. lightIndex++;
  23237. if (lightIndex === maxSimultaneousLights)
  23238. break;
  23239. }
  23240. }
  23241. defines["SPECULARTERM"] = specularEnabled;
  23242. defines["SHADOWS"] = shadowEnabled;
  23243. // Resetting all other lights if any
  23244. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23245. if (defines["LIGHT" + index] !== undefined) {
  23246. defines["LIGHT" + index] = false;
  23247. }
  23248. }
  23249. var caps = scene.getEngine().getCaps();
  23250. if (defines["SHADOWFULLFLOAT"] === undefined) {
  23251. needRebuild = true;
  23252. }
  23253. defines["SHADOWFULLFLOAT"] = (shadowEnabled && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  23254. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23255. if (needRebuild) {
  23256. defines.rebuild();
  23257. }
  23258. return needNormals;
  23259. };
  23260. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23261. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23262. var uniformsList, uniformBuffersList, samplersList, defines;
  23263. if (uniformsListOrOptions.uniformsNames) {
  23264. var options = uniformsListOrOptions;
  23265. uniformsList = options.uniformsNames;
  23266. uniformBuffersList = options.uniformBuffersNames;
  23267. samplersList = options.samplers;
  23268. defines = options.defines;
  23269. maxSimultaneousLights = options.maxSimultaneousLights;
  23270. }
  23271. else {
  23272. uniformsList = uniformsListOrOptions;
  23273. }
  23274. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23275. if (!defines["LIGHT" + lightIndex]) {
  23276. break;
  23277. }
  23278. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23279. if (uniformBuffersList) {
  23280. uniformBuffersList.push("Light" + lightIndex);
  23281. }
  23282. samplersList.push("shadowSampler" + lightIndex);
  23283. }
  23284. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23285. uniformsList.push("morphTargetInfluences");
  23286. }
  23287. };
  23288. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23289. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23290. if (!defines["SHADOWS"]) {
  23291. return;
  23292. }
  23293. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23294. if (!defines["LIGHT" + lightIndex]) {
  23295. break;
  23296. }
  23297. if (lightIndex > 0) {
  23298. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23299. }
  23300. if (defines["SHADOW" + lightIndex]) {
  23301. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23302. }
  23303. if (defines["SHADOWPCF" + lightIndex]) {
  23304. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23305. }
  23306. if (defines["SHADOWESM" + lightIndex]) {
  23307. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23308. }
  23309. }
  23310. };
  23311. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23312. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23313. if (influencers > 0) {
  23314. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23315. var manager = mesh.morphTargetManager;
  23316. var normal = manager.supportsNormals && defines["NORMAL"];
  23317. var tangent = manager.supportsTangents && defines["TANGENT"];
  23318. for (var index = 0; index < influencers; index++) {
  23319. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23320. if (normal) {
  23321. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23322. }
  23323. if (tangent) {
  23324. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23325. }
  23326. if (attribs.length > maxAttributesCount) {
  23327. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23328. }
  23329. }
  23330. }
  23331. };
  23332. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23333. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23334. fallbacks.addCPUSkinningFallback(0, mesh);
  23335. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23336. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23337. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23338. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23339. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23340. }
  23341. }
  23342. };
  23343. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23344. if (defines["INSTANCES"]) {
  23345. attribs.push("world0");
  23346. attribs.push("world1");
  23347. attribs.push("world2");
  23348. attribs.push("world3");
  23349. }
  23350. };
  23351. // Bindings
  23352. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23353. if (light.shadowEnabled && mesh.receiveShadows) {
  23354. var shadowGenerator = light.getShadowGenerator();
  23355. if (shadowGenerator) {
  23356. depthValuesAlreadySet = shadowGenerator.bindShadowLight(lightIndex, effect, depthValuesAlreadySet);
  23357. }
  23358. }
  23359. return depthValuesAlreadySet;
  23360. };
  23361. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23362. light.transferToEffect(effect, lightIndex + "");
  23363. };
  23364. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23365. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23366. var lightIndex = 0;
  23367. var depthValuesAlreadySet = false;
  23368. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23369. var light = _a[_i];
  23370. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23371. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23372. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23373. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  23374. if (defines["SPECULARTERM"]) {
  23375. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23376. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23377. }
  23378. // Shadows
  23379. if (scene.shadowsEnabled) {
  23380. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  23381. }
  23382. light._uniformBuffer.update();
  23383. lightIndex++;
  23384. if (lightIndex === maxSimultaneousLights)
  23385. break;
  23386. }
  23387. };
  23388. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23389. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23390. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23391. effect.setColor3("vFogColor", scene.fogColor);
  23392. }
  23393. };
  23394. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23395. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23396. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23397. if (matrices) {
  23398. effect.setMatrices("mBones", matrices);
  23399. }
  23400. }
  23401. };
  23402. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23403. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23404. return;
  23405. }
  23406. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23407. };
  23408. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23409. if (defines["LOGARITHMICDEPTH"]) {
  23410. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23411. }
  23412. };
  23413. MaterialHelper.BindClipPlane = function (effect, scene) {
  23414. if (scene.clipPlane) {
  23415. var clipPlane = scene.clipPlane;
  23416. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23417. }
  23418. };
  23419. return MaterialHelper;
  23420. }());
  23421. BABYLON.MaterialHelper = MaterialHelper;
  23422. })(BABYLON || (BABYLON = {}));
  23423. //# sourceMappingURL=babylon.materialHelper.js.map
  23424. var BABYLON;
  23425. (function (BABYLON) {
  23426. var MaterialDefines = (function () {
  23427. function MaterialDefines() {
  23428. this._isDirty = true;
  23429. this._areLightsDirty = true;
  23430. this._areAttributesDirty = true;
  23431. this._areTexturesDirty = true;
  23432. this._areFresnelDirty = true;
  23433. this._areMiscDirty = true;
  23434. this._normals = false;
  23435. this._uvs = false;
  23436. this._needNormals = false;
  23437. this._needUVs = false;
  23438. }
  23439. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23440. get: function () {
  23441. return this._isDirty;
  23442. },
  23443. enumerable: true,
  23444. configurable: true
  23445. });
  23446. MaterialDefines.prototype.markAsProcessed = function () {
  23447. this._isDirty = false;
  23448. this._areAttributesDirty = false;
  23449. this._areTexturesDirty = false;
  23450. this._areFresnelDirty = false;
  23451. this._areLightsDirty = false;
  23452. this._areMiscDirty = false;
  23453. };
  23454. MaterialDefines.prototype.markAsUnprocessed = function () {
  23455. this._isDirty = true;
  23456. };
  23457. MaterialDefines.prototype.markAllAsDirty = function () {
  23458. this._areTexturesDirty = true;
  23459. this._areAttributesDirty = true;
  23460. this._areLightsDirty = true;
  23461. this._areFresnelDirty = true;
  23462. this._areMiscDirty = true;
  23463. this._isDirty = true;
  23464. };
  23465. MaterialDefines.prototype.markAsLightDirty = function () {
  23466. this._areLightsDirty = true;
  23467. this._isDirty = true;
  23468. };
  23469. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23470. this._areAttributesDirty = true;
  23471. this._isDirty = true;
  23472. };
  23473. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23474. this._areTexturesDirty = true;
  23475. this._isDirty = true;
  23476. };
  23477. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23478. this._areFresnelDirty = true;
  23479. this._isDirty = true;
  23480. };
  23481. MaterialDefines.prototype.markAsMiscDirty = function () {
  23482. this._areMiscDirty = true;
  23483. this._isDirty = true;
  23484. };
  23485. MaterialDefines.prototype.rebuild = function () {
  23486. if (this._keys) {
  23487. delete this._keys;
  23488. }
  23489. this._keys = [];
  23490. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23491. var key = _a[_i];
  23492. if (key[0] === "_") {
  23493. continue;
  23494. }
  23495. this._keys.push(key);
  23496. }
  23497. };
  23498. MaterialDefines.prototype.isEqual = function (other) {
  23499. if (this._keys.length !== other._keys.length) {
  23500. return false;
  23501. }
  23502. for (var index = 0; index < this._keys.length; index++) {
  23503. var prop = this._keys[index];
  23504. if (this[prop] !== other[prop]) {
  23505. return false;
  23506. }
  23507. }
  23508. return true;
  23509. };
  23510. MaterialDefines.prototype.cloneTo = function (other) {
  23511. if (this._keys.length !== other._keys.length) {
  23512. other._keys = this._keys.slice(0);
  23513. }
  23514. for (var index = 0; index < this._keys.length; index++) {
  23515. var prop = this._keys[index];
  23516. other[prop] = this[prop];
  23517. }
  23518. };
  23519. MaterialDefines.prototype.reset = function () {
  23520. for (var index = 0; index < this._keys.length; index++) {
  23521. var prop = this._keys[index];
  23522. if (typeof (this[prop]) === "number") {
  23523. this[prop] = 0;
  23524. }
  23525. else {
  23526. this[prop] = false;
  23527. }
  23528. }
  23529. };
  23530. MaterialDefines.prototype.toString = function () {
  23531. var result = "";
  23532. for (var index = 0; index < this._keys.length; index++) {
  23533. var prop = this._keys[index];
  23534. var value = this[prop];
  23535. if (typeof (value) === "number") {
  23536. result += "#define " + prop + " " + this[prop] + "\n";
  23537. }
  23538. else if (value) {
  23539. result += "#define " + prop + "\n";
  23540. }
  23541. }
  23542. return result;
  23543. };
  23544. return MaterialDefines;
  23545. }());
  23546. BABYLON.MaterialDefines = MaterialDefines;
  23547. var Material = (function () {
  23548. function Material(name, scene, doNotAdd) {
  23549. this.checkReadyOnEveryCall = false;
  23550. this.checkReadyOnlyOnce = false;
  23551. this.state = "";
  23552. this.alpha = 1.0;
  23553. this._backFaceCulling = true;
  23554. this.doNotSerialize = false;
  23555. this.storeEffectOnSubMeshes = false;
  23556. /**
  23557. * An event triggered when the material is disposed.
  23558. * @type {BABYLON.Observable}
  23559. */
  23560. this.onDisposeObservable = new BABYLON.Observable();
  23561. /**
  23562. * An event triggered when the material is bound.
  23563. * @type {BABYLON.Observable}
  23564. */
  23565. this.onBindObservable = new BABYLON.Observable();
  23566. /**
  23567. * An event triggered when the material is unbound.
  23568. * @type {BABYLON.Observable}
  23569. */
  23570. this.onUnBindObservable = new BABYLON.Observable();
  23571. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23572. this.disableDepthWrite = false;
  23573. this._fogEnabled = true;
  23574. this.pointSize = 1.0;
  23575. this.zOffset = 0;
  23576. this._wasPreviouslyReady = false;
  23577. this._fillMode = Material.TriangleFillMode;
  23578. this.name = name;
  23579. this.id = name;
  23580. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23581. if (this._scene.useRightHandedSystem) {
  23582. this.sideOrientation = Material.ClockWiseSideOrientation;
  23583. }
  23584. else {
  23585. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23586. }
  23587. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23588. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23589. if (!doNotAdd) {
  23590. this._scene.materials.push(this);
  23591. }
  23592. }
  23593. Object.defineProperty(Material, "TriangleFillMode", {
  23594. get: function () {
  23595. return Material._TriangleFillMode;
  23596. },
  23597. enumerable: true,
  23598. configurable: true
  23599. });
  23600. Object.defineProperty(Material, "WireFrameFillMode", {
  23601. get: function () {
  23602. return Material._WireFrameFillMode;
  23603. },
  23604. enumerable: true,
  23605. configurable: true
  23606. });
  23607. Object.defineProperty(Material, "PointFillMode", {
  23608. get: function () {
  23609. return Material._PointFillMode;
  23610. },
  23611. enumerable: true,
  23612. configurable: true
  23613. });
  23614. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23615. get: function () {
  23616. return Material._ClockWiseSideOrientation;
  23617. },
  23618. enumerable: true,
  23619. configurable: true
  23620. });
  23621. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23622. get: function () {
  23623. return Material._CounterClockWiseSideOrientation;
  23624. },
  23625. enumerable: true,
  23626. configurable: true
  23627. });
  23628. Object.defineProperty(Material, "TextureDirtyFlag", {
  23629. get: function () {
  23630. return Material._TextureDirtyFlag;
  23631. },
  23632. enumerable: true,
  23633. configurable: true
  23634. });
  23635. Object.defineProperty(Material, "LightDirtyFlag", {
  23636. get: function () {
  23637. return Material._LightDirtyFlag;
  23638. },
  23639. enumerable: true,
  23640. configurable: true
  23641. });
  23642. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23643. get: function () {
  23644. return Material._FresnelDirtyFlag;
  23645. },
  23646. enumerable: true,
  23647. configurable: true
  23648. });
  23649. Object.defineProperty(Material, "AttributesDirtyFlag", {
  23650. get: function () {
  23651. return Material._AttributesDirtyFlag;
  23652. },
  23653. enumerable: true,
  23654. configurable: true
  23655. });
  23656. Object.defineProperty(Material, "MiscDirtyFlag", {
  23657. get: function () {
  23658. return Material._MiscDirtyFlag;
  23659. },
  23660. enumerable: true,
  23661. configurable: true
  23662. });
  23663. Object.defineProperty(Material.prototype, "backFaceCulling", {
  23664. get: function () {
  23665. return this._backFaceCulling;
  23666. },
  23667. set: function (value) {
  23668. if (this._backFaceCulling === value) {
  23669. return;
  23670. }
  23671. this._backFaceCulling = value;
  23672. this.markAsDirty(Material.TextureDirtyFlag);
  23673. },
  23674. enumerable: true,
  23675. configurable: true
  23676. });
  23677. Object.defineProperty(Material.prototype, "onDispose", {
  23678. set: function (callback) {
  23679. if (this._onDisposeObserver) {
  23680. this.onDisposeObservable.remove(this._onDisposeObserver);
  23681. }
  23682. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23683. },
  23684. enumerable: true,
  23685. configurable: true
  23686. });
  23687. Object.defineProperty(Material.prototype, "onBind", {
  23688. set: function (callback) {
  23689. if (this._onBindObserver) {
  23690. this.onBindObservable.remove(this._onBindObserver);
  23691. }
  23692. this._onBindObserver = this.onBindObservable.add(callback);
  23693. },
  23694. enumerable: true,
  23695. configurable: true
  23696. });
  23697. Object.defineProperty(Material.prototype, "fogEnabled", {
  23698. get: function () {
  23699. return this._fogEnabled;
  23700. },
  23701. set: function (value) {
  23702. if (this._fogEnabled === value) {
  23703. return;
  23704. }
  23705. this._fogEnabled = value;
  23706. this.markAsDirty(Material.MiscDirtyFlag);
  23707. },
  23708. enumerable: true,
  23709. configurable: true
  23710. });
  23711. Object.defineProperty(Material.prototype, "wireframe", {
  23712. get: function () {
  23713. return this._fillMode === Material.WireFrameFillMode;
  23714. },
  23715. set: function (value) {
  23716. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23717. },
  23718. enumerable: true,
  23719. configurable: true
  23720. });
  23721. Object.defineProperty(Material.prototype, "pointsCloud", {
  23722. get: function () {
  23723. return this._fillMode === Material.PointFillMode;
  23724. },
  23725. set: function (value) {
  23726. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23727. },
  23728. enumerable: true,
  23729. configurable: true
  23730. });
  23731. Object.defineProperty(Material.prototype, "fillMode", {
  23732. get: function () {
  23733. return this._fillMode;
  23734. },
  23735. set: function (value) {
  23736. if (this._fillMode === value) {
  23737. return;
  23738. }
  23739. this._fillMode = value;
  23740. this.markAsDirty(Material.MiscDirtyFlag);
  23741. },
  23742. enumerable: true,
  23743. configurable: true
  23744. });
  23745. /**
  23746. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23747. * subclasses should override adding information pertainent to themselves
  23748. */
  23749. Material.prototype.toString = function (fullDetails) {
  23750. var ret = "Name: " + this.name;
  23751. if (fullDetails) {
  23752. }
  23753. return ret;
  23754. };
  23755. /**
  23756. * Child classes can use it to update shaders
  23757. */
  23758. Material.prototype.markAsDirty = function (flag) {
  23759. };
  23760. Material.prototype.getClassName = function () {
  23761. return "Material";
  23762. };
  23763. Object.defineProperty(Material.prototype, "isFrozen", {
  23764. get: function () {
  23765. return this.checkReadyOnlyOnce;
  23766. },
  23767. enumerable: true,
  23768. configurable: true
  23769. });
  23770. Material.prototype.freeze = function () {
  23771. this.checkReadyOnlyOnce = true;
  23772. };
  23773. Material.prototype.unfreeze = function () {
  23774. this.checkReadyOnlyOnce = false;
  23775. };
  23776. Material.prototype.isReady = function (mesh, useInstances) {
  23777. return true;
  23778. };
  23779. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  23780. return false;
  23781. };
  23782. Material.prototype.getEffect = function () {
  23783. return this._effect;
  23784. };
  23785. Material.prototype.getScene = function () {
  23786. return this._scene;
  23787. };
  23788. Material.prototype.needAlphaBlending = function () {
  23789. return (this.alpha < 1.0);
  23790. };
  23791. Material.prototype.needAlphaTesting = function () {
  23792. return false;
  23793. };
  23794. Material.prototype.getAlphaTestTexture = function () {
  23795. return null;
  23796. };
  23797. Material.prototype.markDirty = function () {
  23798. this._wasPreviouslyReady = false;
  23799. };
  23800. Material.prototype._preBind = function (effect) {
  23801. var engine = this._scene.getEngine();
  23802. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  23803. engine.enableEffect(effect ? effect : this._effect);
  23804. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  23805. };
  23806. Material.prototype.bind = function (world, mesh) {
  23807. };
  23808. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  23809. };
  23810. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23811. };
  23812. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  23813. sceneUbo.bindToEffect(effect, "Scene");
  23814. };
  23815. Material.prototype.bindView = function (effect) {
  23816. if (!this._useUBO) {
  23817. effect.setMatrix("view", this.getScene().getViewMatrix());
  23818. }
  23819. else {
  23820. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23821. }
  23822. };
  23823. Material.prototype.bindViewProjection = function (effect) {
  23824. if (!this._useUBO) {
  23825. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23826. }
  23827. else {
  23828. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23829. }
  23830. };
  23831. Material.prototype._afterBind = function (mesh) {
  23832. this._scene._cachedMaterial = this;
  23833. this.onBindObservable.notifyObservers(mesh);
  23834. if (this.disableDepthWrite) {
  23835. var engine = this._scene.getEngine();
  23836. this._cachedDepthWriteState = engine.getDepthWrite();
  23837. engine.setDepthWrite(false);
  23838. }
  23839. };
  23840. Material.prototype.unbind = function () {
  23841. this.onUnBindObservable.notifyObservers(this);
  23842. if (this.disableDepthWrite) {
  23843. var engine = this._scene.getEngine();
  23844. engine.setDepthWrite(this._cachedDepthWriteState);
  23845. }
  23846. };
  23847. Material.prototype.clone = function (name) {
  23848. return null;
  23849. };
  23850. Material.prototype.getBindedMeshes = function () {
  23851. var result = new Array();
  23852. for (var index = 0; index < this._scene.meshes.length; index++) {
  23853. var mesh = this._scene.meshes[index];
  23854. if (mesh.material === this) {
  23855. result.push(mesh);
  23856. }
  23857. }
  23858. return result;
  23859. };
  23860. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23861. // Animations
  23862. this.getScene().stopAnimation(this);
  23863. // Remove from scene
  23864. var index = this._scene.materials.indexOf(this);
  23865. if (index >= 0) {
  23866. this._scene.materials.splice(index, 1);
  23867. }
  23868. // Remove from meshes
  23869. for (index = 0; index < this._scene.meshes.length; index++) {
  23870. var mesh = this._scene.meshes[index];
  23871. if (mesh.material === this) {
  23872. mesh.material = null;
  23873. if (mesh.geometry) {
  23874. var geometry = mesh.geometry;
  23875. if (this.storeEffectOnSubMeshes) {
  23876. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  23877. var subMesh = _a[_i];
  23878. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  23879. }
  23880. }
  23881. else {
  23882. geometry._releaseVertexArrayObject(this._effect);
  23883. }
  23884. }
  23885. }
  23886. }
  23887. this._uniformBuffer.dispose();
  23888. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  23889. if (forceDisposeEffect && this._effect) {
  23890. if (this.storeEffectOnSubMeshes) {
  23891. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23892. var subMesh = _c[_b];
  23893. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  23894. }
  23895. }
  23896. else {
  23897. this._scene.getEngine()._releaseEffect(this._effect);
  23898. }
  23899. this._effect = null;
  23900. }
  23901. // Callback
  23902. this.onDisposeObservable.notifyObservers(this);
  23903. this.onDisposeObservable.clear();
  23904. this.onBindObservable.clear();
  23905. this.onUnBindObservable.clear();
  23906. };
  23907. Material.prototype.serialize = function () {
  23908. return BABYLON.SerializationHelper.Serialize(this);
  23909. };
  23910. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  23911. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  23912. multiMaterial.id = parsedMultiMaterial.id;
  23913. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  23914. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  23915. var subMatId = parsedMultiMaterial.materials[matIndex];
  23916. if (subMatId) {
  23917. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  23918. }
  23919. else {
  23920. multiMaterial.subMaterials.push(null);
  23921. }
  23922. }
  23923. return multiMaterial;
  23924. };
  23925. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  23926. if (!parsedMaterial.customType) {
  23927. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  23928. }
  23929. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && !parsedMaterial.overloadedAlbedo) {
  23930. parsedMaterial.customType === "BABYLON.legacyPBRMaterial";
  23931. if (!BABYLON.legacyPBRMaterial) {
  23932. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  23933. return;
  23934. }
  23935. }
  23936. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  23937. return materialType.Parse(parsedMaterial, scene, rootUrl);
  23938. ;
  23939. };
  23940. return Material;
  23941. }());
  23942. Material._TriangleFillMode = 0;
  23943. Material._WireFrameFillMode = 1;
  23944. Material._PointFillMode = 2;
  23945. Material._ClockWiseSideOrientation = 0;
  23946. Material._CounterClockWiseSideOrientation = 1;
  23947. Material._TextureDirtyFlag = 1;
  23948. Material._LightDirtyFlag = 2;
  23949. Material._FresnelDirtyFlag = 4;
  23950. Material._AttributesDirtyFlag = 8;
  23951. Material._MiscDirtyFlag = 16;
  23952. __decorate([
  23953. BABYLON.serialize()
  23954. ], Material.prototype, "id", void 0);
  23955. __decorate([
  23956. BABYLON.serialize()
  23957. ], Material.prototype, "name", void 0);
  23958. __decorate([
  23959. BABYLON.serialize()
  23960. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  23961. __decorate([
  23962. BABYLON.serialize()
  23963. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  23964. __decorate([
  23965. BABYLON.serialize()
  23966. ], Material.prototype, "state", void 0);
  23967. __decorate([
  23968. BABYLON.serialize()
  23969. ], Material.prototype, "alpha", void 0);
  23970. __decorate([
  23971. BABYLON.serialize("backFaceCulling")
  23972. ], Material.prototype, "_backFaceCulling", void 0);
  23973. __decorate([
  23974. BABYLON.serialize()
  23975. ], Material.prototype, "sideOrientation", void 0);
  23976. __decorate([
  23977. BABYLON.serialize()
  23978. ], Material.prototype, "alphaMode", void 0);
  23979. __decorate([
  23980. BABYLON.serialize()
  23981. ], Material.prototype, "disableDepthWrite", void 0);
  23982. __decorate([
  23983. BABYLON.serialize("fogEnabled")
  23984. ], Material.prototype, "_fogEnabled", void 0);
  23985. __decorate([
  23986. BABYLON.serialize()
  23987. ], Material.prototype, "pointSize", void 0);
  23988. __decorate([
  23989. BABYLON.serialize()
  23990. ], Material.prototype, "zOffset", void 0);
  23991. __decorate([
  23992. BABYLON.serialize()
  23993. ], Material.prototype, "wireframe", null);
  23994. __decorate([
  23995. BABYLON.serialize()
  23996. ], Material.prototype, "pointsCloud", null);
  23997. __decorate([
  23998. BABYLON.serialize()
  23999. ], Material.prototype, "fillMode", null);
  24000. BABYLON.Material = Material;
  24001. })(BABYLON || (BABYLON = {}));
  24002. //# sourceMappingURL=babylon.material.js.map
  24003. var BABYLON;
  24004. (function (BABYLON) {
  24005. var UniformBuffer = (function () {
  24006. /**
  24007. * Uniform buffer objects.
  24008. *
  24009. * Handles blocks of uniform on the GPU.
  24010. *
  24011. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24012. *
  24013. * For more information, please refer to :
  24014. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24015. */
  24016. function UniformBuffer(engine, data, dynamic) {
  24017. this._engine = engine;
  24018. this._noUBO = engine.webGLVersion === 1;
  24019. this._dynamic = dynamic;
  24020. this._data = data || [];
  24021. this._uniformLocations = {};
  24022. this._uniformSizes = {};
  24023. this._uniformLocationPointer = 0;
  24024. this._needSync = false;
  24025. if (this._noUBO) {
  24026. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24027. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24028. this.updateFloat = this._updateFloatForEffect;
  24029. this.updateFloat2 = this._updateFloat2ForEffect;
  24030. this.updateFloat3 = this._updateFloat3ForEffect;
  24031. this.updateFloat4 = this._updateFloat4ForEffect;
  24032. this.updateMatrix = this._updateMatrixForEffect;
  24033. this.updateVector3 = this._updateVector3ForEffect;
  24034. this.updateVector4 = this._updateVector4ForEffect;
  24035. this.updateColor3 = this._updateColor3ForEffect;
  24036. this.updateColor4 = this._updateColor4ForEffect;
  24037. }
  24038. else {
  24039. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24040. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24041. this.updateFloat = this._updateFloatForUniform;
  24042. this.updateFloat2 = this._updateFloat2ForUniform;
  24043. this.updateFloat3 = this._updateFloat3ForUniform;
  24044. this.updateFloat4 = this._updateFloat4ForUniform;
  24045. this.updateMatrix = this._updateMatrixForUniform;
  24046. this.updateVector3 = this._updateVector3ForUniform;
  24047. this.updateVector4 = this._updateVector4ForUniform;
  24048. this.updateColor3 = this._updateColor3ForUniform;
  24049. this.updateColor4 = this._updateColor4ForUniform;
  24050. }
  24051. }
  24052. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24053. // Properties
  24054. /**
  24055. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24056. * or just falling back on setUniformXXX calls.
  24057. */
  24058. get: function () {
  24059. return !this._noUBO;
  24060. },
  24061. enumerable: true,
  24062. configurable: true
  24063. });
  24064. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24065. /**
  24066. * Indicates if the WebGL underlying uniform buffer is in sync
  24067. * with the javascript cache data.
  24068. */
  24069. get: function () {
  24070. return !this._needSync;
  24071. },
  24072. enumerable: true,
  24073. configurable: true
  24074. });
  24075. /**
  24076. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24077. * Also, a dynamic UniformBuffer will disable cache verification and always
  24078. * update the underlying WebGL uniform buffer to the GPU.
  24079. */
  24080. UniformBuffer.prototype.isDynamic = function () {
  24081. return this._dynamic;
  24082. };
  24083. /**
  24084. * The data cache on JS side.
  24085. */
  24086. UniformBuffer.prototype.getData = function () {
  24087. return this._bufferData;
  24088. };
  24089. /**
  24090. * The underlying WebGL Uniform buffer.
  24091. */
  24092. UniformBuffer.prototype.getBuffer = function () {
  24093. return this._buffer;
  24094. };
  24095. /**
  24096. * std140 layout specifies how to align data within an UBO structure.
  24097. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24098. * for specs.
  24099. */
  24100. UniformBuffer.prototype._fillAlignment = function (size) {
  24101. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24102. // and 4x4 matrices
  24103. // TODO : change if other types are used
  24104. var alignment;
  24105. if (size <= 2) {
  24106. alignment = size;
  24107. }
  24108. else {
  24109. alignment = 4;
  24110. }
  24111. if ((this._uniformLocationPointer % alignment) !== 0) {
  24112. var oldPointer = this._uniformLocationPointer;
  24113. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24114. var diff = this._uniformLocationPointer - oldPointer;
  24115. for (var i = 0; i < diff; i++) {
  24116. this._data.push(0);
  24117. }
  24118. }
  24119. };
  24120. /**
  24121. * Adds an uniform in the buffer.
  24122. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24123. * for the layout to be correct !
  24124. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24125. * @param {number|number[]} size Data size, or data directly.
  24126. */
  24127. UniformBuffer.prototype.addUniform = function (name, size) {
  24128. if (this._noUBO) {
  24129. return;
  24130. }
  24131. if (this._uniformLocations[name] !== undefined) {
  24132. // Already existing uniform
  24133. return;
  24134. }
  24135. // This function must be called in the order of the shader layout !
  24136. // size can be the size of the uniform, or data directly
  24137. var data;
  24138. if (size instanceof Array) {
  24139. data = size;
  24140. size = data.length;
  24141. }
  24142. else {
  24143. size = size;
  24144. data = [];
  24145. // Fill with zeros
  24146. for (var i = 0; i < size; i++) {
  24147. data.push(0);
  24148. }
  24149. }
  24150. this._fillAlignment(size);
  24151. this._uniformSizes[name] = size;
  24152. this._uniformLocations[name] = this._uniformLocationPointer;
  24153. this._uniformLocationPointer += size;
  24154. for (var i = 0; i < size; i++) {
  24155. this._data.push(data[i]);
  24156. }
  24157. this._needSync = true;
  24158. };
  24159. /**
  24160. * Wrapper for addUniform.
  24161. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24162. * @param {Matrix} mat A 4x4 matrix.
  24163. */
  24164. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24165. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24166. };
  24167. /**
  24168. * Wrapper for addUniform.
  24169. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24170. * @param {number} x
  24171. * @param {number} y
  24172. */
  24173. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24174. var temp = [x, y];
  24175. this.addUniform(name, temp);
  24176. };
  24177. /**
  24178. * Wrapper for addUniform.
  24179. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24180. * @param {number} x
  24181. * @param {number} y
  24182. * @param {number} z
  24183. */
  24184. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24185. var temp = [x, y, z];
  24186. this.addUniform(name, temp);
  24187. };
  24188. /**
  24189. * Wrapper for addUniform.
  24190. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24191. * @param {Color3} color
  24192. */
  24193. UniformBuffer.prototype.addColor3 = function (name, color) {
  24194. var temp = [];
  24195. color.toArray(temp);
  24196. this.addUniform(name, temp);
  24197. };
  24198. /**
  24199. * Wrapper for addUniform.
  24200. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24201. * @param {Color3} color
  24202. * @param {number} alpha
  24203. */
  24204. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24205. var temp = [];
  24206. color.toArray(temp);
  24207. temp.push(alpha);
  24208. this.addUniform(name, temp);
  24209. };
  24210. /**
  24211. * Wrapper for addUniform.
  24212. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24213. * @param {Vector3} vector
  24214. */
  24215. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24216. var temp = [];
  24217. vector.toArray(temp);
  24218. this.addUniform(name, temp);
  24219. };
  24220. /**
  24221. * Wrapper for addUniform.
  24222. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24223. */
  24224. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24225. this.addUniform(name, 12);
  24226. };
  24227. /**
  24228. * Wrapper for addUniform.
  24229. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24230. */
  24231. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24232. this.addUniform(name, 8);
  24233. };
  24234. /**
  24235. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24236. */
  24237. UniformBuffer.prototype.create = function () {
  24238. if (this._noUBO) {
  24239. return;
  24240. }
  24241. if (this._buffer) {
  24242. return; // nothing to do
  24243. }
  24244. // See spec, alignment must be filled as a vec4
  24245. this._fillAlignment(4);
  24246. this._bufferData = new Float32Array(this._data);
  24247. if (this._dynamic) {
  24248. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24249. }
  24250. else {
  24251. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24252. }
  24253. this._needSync = true;
  24254. };
  24255. /**
  24256. * Updates the WebGL Uniform Buffer on the GPU.
  24257. * If the `dynamic` flag is set to true, no cache comparison is done.
  24258. * Otherwise, the buffer will be updated only if the cache differs.
  24259. */
  24260. UniformBuffer.prototype.update = function () {
  24261. if (!this._buffer) {
  24262. this.create();
  24263. return;
  24264. }
  24265. if (!this._dynamic && !this._needSync) {
  24266. return;
  24267. }
  24268. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24269. this._needSync = false;
  24270. };
  24271. /**
  24272. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24273. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24274. * @param {number[]|Float32Array} data Flattened data
  24275. * @param {number} size Size of the data.
  24276. */
  24277. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24278. var location = this._uniformLocations[uniformName];
  24279. if (location === undefined) {
  24280. if (this._buffer) {
  24281. // Cannot add an uniform if the buffer is already created
  24282. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24283. return;
  24284. }
  24285. this.addUniform(uniformName, size);
  24286. location = this._uniformLocations[uniformName];
  24287. }
  24288. if (!this._buffer) {
  24289. this.create();
  24290. }
  24291. if (!this._dynamic) {
  24292. // Cache for static uniform buffers
  24293. var changed = false;
  24294. for (var i = 0; i < size; i++) {
  24295. if (this._bufferData[location + i] !== data[i]) {
  24296. changed = true;
  24297. this._bufferData[location + i] = data[i];
  24298. }
  24299. }
  24300. this._needSync = this._needSync || changed;
  24301. }
  24302. else {
  24303. // No cache for dynamic
  24304. for (var i = 0; i < size; i++) {
  24305. this._bufferData[location + i] = data[i];
  24306. }
  24307. }
  24308. };
  24309. // Update methods
  24310. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24311. // To match std140, matrix must be realigned
  24312. for (var i = 0; i < 3; i++) {
  24313. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24314. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24315. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24316. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24317. }
  24318. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24319. };
  24320. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24321. this._currentEffect.setMatrix3x3(name, matrix);
  24322. };
  24323. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24324. this._currentEffect.setMatrix2x2(name, matrix);
  24325. };
  24326. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24327. // To match std140, matrix must be realigned
  24328. for (var i = 0; i < 2; i++) {
  24329. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24330. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24331. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24332. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24333. }
  24334. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24335. };
  24336. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24337. this._currentEffect.setFloat(name, x);
  24338. };
  24339. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24340. UniformBuffer._tempBuffer[0] = x;
  24341. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24342. };
  24343. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y) {
  24344. this._currentEffect.setFloat2(name, x, y);
  24345. };
  24346. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y) {
  24347. UniformBuffer._tempBuffer[0] = x;
  24348. UniformBuffer._tempBuffer[1] = y;
  24349. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24350. };
  24351. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24352. if (suffix === void 0) { suffix = ""; }
  24353. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24354. };
  24355. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24356. if (suffix === void 0) { suffix = ""; }
  24357. UniformBuffer._tempBuffer[0] = x;
  24358. UniformBuffer._tempBuffer[1] = y;
  24359. UniformBuffer._tempBuffer[2] = z;
  24360. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24361. };
  24362. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24363. if (suffix === void 0) { suffix = ""; }
  24364. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24365. };
  24366. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24367. if (suffix === void 0) { suffix = ""; }
  24368. UniformBuffer._tempBuffer[0] = x;
  24369. UniformBuffer._tempBuffer[1] = y;
  24370. UniformBuffer._tempBuffer[2] = z;
  24371. UniformBuffer._tempBuffer[3] = w;
  24372. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24373. };
  24374. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24375. this._currentEffect.setMatrix(name, mat);
  24376. };
  24377. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24378. this.updateUniform(name, mat.toArray(), 16);
  24379. };
  24380. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24381. this._currentEffect.setVector3(name, vector);
  24382. };
  24383. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24384. vector.toArray(UniformBuffer._tempBuffer);
  24385. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24386. };
  24387. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24388. this._currentEffect.setVector4(name, vector);
  24389. };
  24390. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24391. vector.toArray(UniformBuffer._tempBuffer);
  24392. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24393. };
  24394. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24395. if (suffix === void 0) { suffix = ""; }
  24396. this._currentEffect.setColor3(name + suffix, color);
  24397. };
  24398. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24399. if (suffix === void 0) { suffix = ""; }
  24400. color.toArray(UniformBuffer._tempBuffer);
  24401. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24402. };
  24403. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24404. if (suffix === void 0) { suffix = ""; }
  24405. this._currentEffect.setColor4(name + suffix, color, alpha);
  24406. };
  24407. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24408. if (suffix === void 0) { suffix = ""; }
  24409. color.toArray(UniformBuffer._tempBuffer);
  24410. UniformBuffer._tempBuffer[3] = alpha;
  24411. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24412. };
  24413. /**
  24414. * Sets a sampler uniform on the effect.
  24415. * @param {string} name Name of the sampler.
  24416. * @param {Texture} texture
  24417. */
  24418. UniformBuffer.prototype.setTexture = function (name, texture) {
  24419. this._currentEffect.setTexture(name, texture);
  24420. };
  24421. /**
  24422. * Directly updates the value of the uniform in the cache AND on the GPU.
  24423. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24424. * @param {number[]|Float32Array} data Flattened data
  24425. */
  24426. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24427. this.updateUniform(uniformName, data, data.length);
  24428. this.update();
  24429. };
  24430. /**
  24431. * Binds this uniform buffer to an effect.
  24432. * @param {Effect} effect
  24433. * @param {string} name Name of the uniform block in the shader.
  24434. */
  24435. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24436. this._currentEffect = effect;
  24437. if (this._noUBO) {
  24438. return;
  24439. }
  24440. effect.bindUniformBuffer(this._buffer, name);
  24441. };
  24442. /**
  24443. * Disposes the uniform buffer.
  24444. */
  24445. UniformBuffer.prototype.dispose = function () {
  24446. if (!this._buffer) {
  24447. return;
  24448. }
  24449. if (this._engine._releaseBuffer(this._buffer)) {
  24450. this._buffer = null;
  24451. }
  24452. };
  24453. return UniformBuffer;
  24454. }());
  24455. // Pool for avoiding memory leaks
  24456. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24457. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24458. BABYLON.UniformBuffer = UniformBuffer;
  24459. })(BABYLON || (BABYLON = {}));
  24460. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24461. var BABYLON;
  24462. (function (BABYLON) {
  24463. var PushMaterial = (function (_super) {
  24464. __extends(PushMaterial, _super);
  24465. function PushMaterial(name, scene) {
  24466. var _this = _super.call(this, name, scene) || this;
  24467. _this.storeEffectOnSubMeshes = true;
  24468. return _this;
  24469. }
  24470. PushMaterial.prototype.getEffect = function () {
  24471. return this._activeEffect;
  24472. };
  24473. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24474. if (!mesh) {
  24475. return false;
  24476. }
  24477. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24478. return true;
  24479. }
  24480. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24481. };
  24482. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24483. this._activeEffect.setMatrix("world", world);
  24484. };
  24485. PushMaterial.prototype.bind = function (world, mesh) {
  24486. if (!mesh) {
  24487. return;
  24488. }
  24489. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24490. };
  24491. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24492. _super.prototype._afterBind.call(this, mesh);
  24493. this.getScene()._cachedEffect = effect;
  24494. };
  24495. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24496. if (visibility === void 0) { visibility = 0; }
  24497. return scene.isCachedMaterialValid(this, effect, visibility);
  24498. };
  24499. PushMaterial.prototype.markAsDirty = function (flag) {
  24500. if (flag & BABYLON.Material.TextureDirtyFlag) {
  24501. this._markAllSubMeshesAsTexturesDirty();
  24502. }
  24503. if (flag & BABYLON.Material.LightDirtyFlag) {
  24504. this._markAllSubMeshesAsLightsDirty();
  24505. }
  24506. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  24507. this._markAllSubMeshesAsFresnelDirty();
  24508. }
  24509. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  24510. this._markAllSubMeshesAsAttributesDirty();
  24511. }
  24512. if (flag & BABYLON.Material.MiscDirtyFlag) {
  24513. this._markAllSubMeshesAsMiscDirty();
  24514. }
  24515. };
  24516. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  24517. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24518. var mesh = _a[_i];
  24519. if (!mesh.subMeshes) {
  24520. continue;
  24521. }
  24522. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24523. var subMesh = _c[_b];
  24524. if (subMesh.getMaterial() !== this) {
  24525. continue;
  24526. }
  24527. if (!subMesh._materialDefines) {
  24528. return;
  24529. }
  24530. func(subMesh._materialDefines);
  24531. }
  24532. }
  24533. };
  24534. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24535. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24536. };
  24537. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24538. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24539. };
  24540. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  24541. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24542. };
  24543. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24544. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24545. };
  24546. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  24547. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24548. };
  24549. return PushMaterial;
  24550. }(BABYLON.Material));
  24551. BABYLON.PushMaterial = PushMaterial;
  24552. })(BABYLON || (BABYLON = {}));
  24553. //# sourceMappingURL=babylon.pushMaterial.js.map
  24554. var BABYLON;
  24555. (function (BABYLON) {
  24556. var VertexData = (function () {
  24557. function VertexData() {
  24558. }
  24559. VertexData.prototype.set = function (data, kind) {
  24560. switch (kind) {
  24561. case BABYLON.VertexBuffer.PositionKind:
  24562. this.positions = data;
  24563. break;
  24564. case BABYLON.VertexBuffer.NormalKind:
  24565. this.normals = data;
  24566. break;
  24567. case BABYLON.VertexBuffer.TangentKind:
  24568. this.tangents = data;
  24569. break;
  24570. case BABYLON.VertexBuffer.UVKind:
  24571. this.uvs = data;
  24572. break;
  24573. case BABYLON.VertexBuffer.UV2Kind:
  24574. this.uvs2 = data;
  24575. break;
  24576. case BABYLON.VertexBuffer.UV3Kind:
  24577. this.uvs3 = data;
  24578. break;
  24579. case BABYLON.VertexBuffer.UV4Kind:
  24580. this.uvs4 = data;
  24581. break;
  24582. case BABYLON.VertexBuffer.UV5Kind:
  24583. this.uvs5 = data;
  24584. break;
  24585. case BABYLON.VertexBuffer.UV6Kind:
  24586. this.uvs6 = data;
  24587. break;
  24588. case BABYLON.VertexBuffer.ColorKind:
  24589. this.colors = data;
  24590. break;
  24591. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24592. this.matricesIndices = data;
  24593. break;
  24594. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24595. this.matricesWeights = data;
  24596. break;
  24597. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24598. this.matricesIndicesExtra = data;
  24599. break;
  24600. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24601. this.matricesWeightsExtra = data;
  24602. break;
  24603. }
  24604. };
  24605. /**
  24606. * Associates the vertexData to the passed Mesh.
  24607. * Sets it as updatable or not (default `false`).
  24608. * Returns the VertexData.
  24609. */
  24610. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24611. this._applyTo(mesh, updatable);
  24612. return this;
  24613. };
  24614. /**
  24615. * Associates the vertexData to the passed Geometry.
  24616. * Sets it as updatable or not (default `false`).
  24617. * Returns the VertexData.
  24618. */
  24619. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24620. this._applyTo(geometry, updatable);
  24621. return this;
  24622. };
  24623. /**
  24624. * Updates the associated mesh.
  24625. * Returns the VertexData.
  24626. */
  24627. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24628. this._update(mesh);
  24629. return this;
  24630. };
  24631. /**
  24632. * Updates the associated geometry.
  24633. * Returns the VertexData.
  24634. */
  24635. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24636. this._update(geometry);
  24637. return this;
  24638. };
  24639. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24640. if (this.positions) {
  24641. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24642. }
  24643. if (this.normals) {
  24644. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24645. }
  24646. if (this.tangents) {
  24647. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  24648. }
  24649. if (this.uvs) {
  24650. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24651. }
  24652. if (this.uvs2) {
  24653. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24654. }
  24655. if (this.uvs3) {
  24656. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24657. }
  24658. if (this.uvs4) {
  24659. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24660. }
  24661. if (this.uvs5) {
  24662. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24663. }
  24664. if (this.uvs6) {
  24665. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24666. }
  24667. if (this.colors) {
  24668. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24669. }
  24670. if (this.matricesIndices) {
  24671. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24672. }
  24673. if (this.matricesWeights) {
  24674. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24675. }
  24676. if (this.matricesIndicesExtra) {
  24677. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24678. }
  24679. if (this.matricesWeightsExtra) {
  24680. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24681. }
  24682. if (this.indices) {
  24683. meshOrGeometry.setIndices(this.indices);
  24684. }
  24685. return this;
  24686. };
  24687. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24688. if (this.positions) {
  24689. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24690. }
  24691. if (this.normals) {
  24692. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24693. }
  24694. if (this.tangents) {
  24695. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  24696. }
  24697. if (this.uvs) {
  24698. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24699. }
  24700. if (this.uvs2) {
  24701. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24702. }
  24703. if (this.uvs3) {
  24704. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24705. }
  24706. if (this.uvs4) {
  24707. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24708. }
  24709. if (this.uvs5) {
  24710. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24711. }
  24712. if (this.uvs6) {
  24713. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24714. }
  24715. if (this.colors) {
  24716. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24717. }
  24718. if (this.matricesIndices) {
  24719. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24720. }
  24721. if (this.matricesWeights) {
  24722. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24723. }
  24724. if (this.matricesIndicesExtra) {
  24725. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24726. }
  24727. if (this.matricesWeightsExtra) {
  24728. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24729. }
  24730. if (this.indices) {
  24731. meshOrGeometry.setIndices(this.indices);
  24732. }
  24733. return this;
  24734. };
  24735. /**
  24736. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  24737. * Returns the VertexData.
  24738. */
  24739. VertexData.prototype.transform = function (matrix) {
  24740. var transformed = BABYLON.Vector3.Zero();
  24741. var index;
  24742. if (this.positions) {
  24743. var position = BABYLON.Vector3.Zero();
  24744. for (index = 0; index < this.positions.length; index += 3) {
  24745. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24746. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24747. this.positions[index] = transformed.x;
  24748. this.positions[index + 1] = transformed.y;
  24749. this.positions[index + 2] = transformed.z;
  24750. }
  24751. }
  24752. if (this.normals) {
  24753. var normal = BABYLON.Vector3.Zero();
  24754. for (index = 0; index < this.normals.length; index += 3) {
  24755. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24756. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24757. this.normals[index] = transformed.x;
  24758. this.normals[index + 1] = transformed.y;
  24759. this.normals[index + 2] = transformed.z;
  24760. }
  24761. }
  24762. if (this.tangents) {
  24763. var tangent = BABYLON.Vector4.Zero();
  24764. var tangentTransformed = BABYLON.Vector4.Zero();
  24765. for (index = 0; index < this.tangents.length; index += 4) {
  24766. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  24767. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  24768. this.tangents[index] = tangentTransformed.x;
  24769. this.tangents[index + 1] = tangentTransformed.y;
  24770. this.tangents[index + 2] = tangentTransformed.z;
  24771. this.tangents[index + 3] = tangentTransformed.w;
  24772. }
  24773. }
  24774. return this;
  24775. };
  24776. /**
  24777. * Merges the passed VertexData into the current one.
  24778. * Returns the modified VertexData.
  24779. */
  24780. VertexData.prototype.merge = function (other) {
  24781. if (other.indices) {
  24782. if (!this.indices) {
  24783. this.indices = [];
  24784. }
  24785. var offset = this.positions ? this.positions.length / 3 : 0;
  24786. for (var index = 0; index < other.indices.length; index++) {
  24787. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  24788. this.indices.push(other.indices[index] + offset);
  24789. }
  24790. }
  24791. this.positions = this._mergeElement(this.positions, other.positions);
  24792. this.normals = this._mergeElement(this.normals, other.normals);
  24793. this.tangents = this._mergeElement(this.tangents, other.tangents);
  24794. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24795. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24796. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24797. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24798. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24799. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24800. this.colors = this._mergeElement(this.colors, other.colors);
  24801. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24802. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24803. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24804. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24805. return this;
  24806. };
  24807. VertexData.prototype._mergeElement = function (source, other) {
  24808. if (!other)
  24809. return source;
  24810. if (!source)
  24811. return other;
  24812. var len = other.length + source.length;
  24813. var isSrcTypedArray = source instanceof Float32Array;
  24814. var isOthTypedArray = other instanceof Float32Array;
  24815. // use non-loop method when the source is Float32Array
  24816. if (isSrcTypedArray) {
  24817. var ret32 = new Float32Array(len);
  24818. ret32.set(source);
  24819. ret32.set(other, source.length);
  24820. return ret32;
  24821. // source is number[], when other is also use concat
  24822. }
  24823. else if (!isOthTypedArray) {
  24824. return source.concat(other);
  24825. // source is a number[], but other is a Float32Array, loop required
  24826. }
  24827. else {
  24828. var ret = source.slice(0); // copy source to a separate array
  24829. for (var i = 0, len = other.length; i < len; i++) {
  24830. ret.push(other[i]);
  24831. }
  24832. return ret;
  24833. }
  24834. };
  24835. /**
  24836. * Serializes the VertexData.
  24837. * Returns a serialized object.
  24838. */
  24839. VertexData.prototype.serialize = function () {
  24840. var serializationObject = this.serialize();
  24841. if (this.positions) {
  24842. serializationObject.positions = this.positions;
  24843. }
  24844. if (this.normals) {
  24845. serializationObject.normals = this.normals;
  24846. }
  24847. if (this.tangents) {
  24848. serializationObject.tangents = this.tangents;
  24849. }
  24850. if (this.uvs) {
  24851. serializationObject.uvs = this.uvs;
  24852. }
  24853. if (this.uvs2) {
  24854. serializationObject.uvs2 = this.uvs2;
  24855. }
  24856. if (this.uvs3) {
  24857. serializationObject.uvs3 = this.uvs3;
  24858. }
  24859. if (this.uvs4) {
  24860. serializationObject.uvs4 = this.uvs4;
  24861. }
  24862. if (this.uvs5) {
  24863. serializationObject.uvs5 = this.uvs5;
  24864. }
  24865. if (this.uvs6) {
  24866. serializationObject.uvs6 = this.uvs6;
  24867. }
  24868. if (this.colors) {
  24869. serializationObject.colors = this.colors;
  24870. }
  24871. if (this.matricesIndices) {
  24872. serializationObject.matricesIndices = this.matricesIndices;
  24873. serializationObject.matricesIndices._isExpanded = true;
  24874. }
  24875. if (this.matricesWeights) {
  24876. serializationObject.matricesWeights = this.matricesWeights;
  24877. }
  24878. if (this.matricesIndicesExtra) {
  24879. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24880. serializationObject.matricesIndicesExtra._isExpanded = true;
  24881. }
  24882. if (this.matricesWeightsExtra) {
  24883. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24884. }
  24885. serializationObject.indices = this.indices;
  24886. return serializationObject;
  24887. };
  24888. // Statics
  24889. /**
  24890. * Returns the object VertexData associated to the passed mesh.
  24891. */
  24892. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  24893. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  24894. };
  24895. /**
  24896. * Returns the object VertexData associated to the passed geometry.
  24897. */
  24898. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  24899. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  24900. };
  24901. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  24902. var result = new VertexData();
  24903. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24904. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  24905. }
  24906. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24907. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  24908. }
  24909. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24910. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  24911. }
  24912. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24913. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  24914. }
  24915. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24916. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  24917. }
  24918. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24919. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  24920. }
  24921. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24922. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  24923. }
  24924. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24925. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  24926. }
  24927. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24928. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  24929. }
  24930. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24931. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  24932. }
  24933. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24934. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  24935. }
  24936. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24937. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  24938. }
  24939. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24940. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  24941. }
  24942. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24943. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  24944. }
  24945. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24946. return result;
  24947. };
  24948. /**
  24949. * Creates the vertexData of the Ribbon.
  24950. */
  24951. VertexData.CreateRibbon = function (options) {
  24952. var pathArray = options.pathArray;
  24953. var closeArray = options.closeArray || false;
  24954. var closePath = options.closePath || false;
  24955. var invertUV = options.invertUV || false;
  24956. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24957. var offset = options.offset || defaultOffset;
  24958. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24959. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24960. var customUV = options.uvs;
  24961. var customColors = options.colors;
  24962. var positions = [];
  24963. var indices = [];
  24964. var normals = [];
  24965. var uvs = [];
  24966. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24967. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24968. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24969. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24970. var minlg; // minimal length among all paths from pathArray
  24971. var lg = []; // array of path lengths : nb of vertex per path
  24972. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24973. var p; // path iterator
  24974. var i; // point iterator
  24975. var j; // point iterator
  24976. // if single path in pathArray
  24977. if (pathArray.length < 2) {
  24978. var ar1 = [];
  24979. var ar2 = [];
  24980. for (i = 0; i < pathArray[0].length - offset; i++) {
  24981. ar1.push(pathArray[0][i]);
  24982. ar2.push(pathArray[0][i + offset]);
  24983. }
  24984. pathArray = [ar1, ar2];
  24985. }
  24986. // positions and horizontal distances (u)
  24987. var idc = 0;
  24988. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  24989. var path;
  24990. var l;
  24991. minlg = pathArray[0].length;
  24992. var vectlg;
  24993. var dist;
  24994. for (p = 0; p < pathArray.length; p++) {
  24995. uTotalDistance[p] = 0;
  24996. us[p] = [0];
  24997. path = pathArray[p];
  24998. l = path.length;
  24999. minlg = (minlg < l) ? minlg : l;
  25000. j = 0;
  25001. while (j < l) {
  25002. positions.push(path[j].x, path[j].y, path[j].z);
  25003. if (j > 0) {
  25004. vectlg = path[j].subtract(path[j - 1]).length();
  25005. dist = vectlg + uTotalDistance[p];
  25006. us[p].push(dist);
  25007. uTotalDistance[p] = dist;
  25008. }
  25009. j++;
  25010. }
  25011. if (closePath) {
  25012. j--;
  25013. positions.push(path[0].x, path[0].y, path[0].z);
  25014. vectlg = path[j].subtract(path[0]).length();
  25015. dist = vectlg + uTotalDistance[p];
  25016. us[p].push(dist);
  25017. uTotalDistance[p] = dist;
  25018. }
  25019. lg[p] = l + closePathCorr;
  25020. idx[p] = idc;
  25021. idc += (l + closePathCorr);
  25022. }
  25023. // vertical distances (v)
  25024. var path1;
  25025. var path2;
  25026. var vertex1;
  25027. var vertex2;
  25028. for (i = 0; i < minlg + closePathCorr; i++) {
  25029. vTotalDistance[i] = 0;
  25030. vs[i] = [0];
  25031. for (p = 0; p < pathArray.length - 1; p++) {
  25032. path1 = pathArray[p];
  25033. path2 = pathArray[p + 1];
  25034. if (i === minlg) {
  25035. vertex1 = path1[0];
  25036. vertex2 = path2[0];
  25037. }
  25038. else {
  25039. vertex1 = path1[i];
  25040. vertex2 = path2[i];
  25041. }
  25042. vectlg = vertex2.subtract(vertex1).length();
  25043. dist = vectlg + vTotalDistance[i];
  25044. vs[i].push(dist);
  25045. vTotalDistance[i] = dist;
  25046. }
  25047. if (closeArray) {
  25048. path1 = pathArray[p];
  25049. path2 = pathArray[0];
  25050. if (i === minlg) {
  25051. vertex2 = path2[0];
  25052. }
  25053. vectlg = vertex2.subtract(vertex1).length();
  25054. dist = vectlg + vTotalDistance[i];
  25055. vTotalDistance[i] = dist;
  25056. }
  25057. }
  25058. // uvs
  25059. var u;
  25060. var v;
  25061. if (customUV) {
  25062. for (p = 0; p < customUV.length; p++) {
  25063. uvs.push(customUV[p].x, customUV[p].y);
  25064. }
  25065. }
  25066. else {
  25067. for (p = 0; p < pathArray.length; p++) {
  25068. for (i = 0; i < minlg + closePathCorr; i++) {
  25069. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25070. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25071. if (invertUV) {
  25072. uvs.push(v, u);
  25073. }
  25074. else {
  25075. uvs.push(u, v);
  25076. }
  25077. }
  25078. }
  25079. }
  25080. // indices
  25081. p = 0; // path index
  25082. var pi = 0; // positions array index
  25083. var l1 = lg[p] - 1; // path1 length
  25084. var l2 = lg[p + 1] - 1; // path2 length
  25085. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25086. var shft = idx[1] - idx[0]; // shift
  25087. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25088. while (pi <= min && p < path1nb) {
  25089. // 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
  25090. indices.push(pi, pi + shft, pi + 1);
  25091. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25092. pi += 1;
  25093. if (pi === min) {
  25094. p++;
  25095. if (p === lg.length - 1) {
  25096. shft = idx[0] - idx[p];
  25097. l1 = lg[p] - 1;
  25098. l2 = lg[0] - 1;
  25099. }
  25100. else {
  25101. shft = idx[p + 1] - idx[p];
  25102. l1 = lg[p] - 1;
  25103. l2 = lg[p + 1] - 1;
  25104. }
  25105. pi = idx[p];
  25106. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25107. }
  25108. }
  25109. // normals
  25110. VertexData.ComputeNormals(positions, indices, normals);
  25111. if (closePath) {
  25112. var indexFirst = 0;
  25113. var indexLast = 0;
  25114. for (p = 0; p < pathArray.length; p++) {
  25115. indexFirst = idx[p] * 3;
  25116. if (p + 1 < pathArray.length) {
  25117. indexLast = (idx[p + 1] - 1) * 3;
  25118. }
  25119. else {
  25120. indexLast = normals.length - 3;
  25121. }
  25122. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25123. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25124. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25125. normals[indexLast] = normals[indexFirst];
  25126. normals[indexLast + 1] = normals[indexFirst + 1];
  25127. normals[indexLast + 2] = normals[indexFirst + 2];
  25128. }
  25129. }
  25130. // sides
  25131. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25132. // Colors
  25133. if (customColors) {
  25134. var colors = new Float32Array(customColors.length * 4);
  25135. for (var c = 0; c < customColors.length; c++) {
  25136. colors[c * 4] = customColors[c].r;
  25137. colors[c * 4 + 1] = customColors[c].g;
  25138. colors[c * 4 + 2] = customColors[c].b;
  25139. colors[c * 4 + 3] = customColors[c].a;
  25140. }
  25141. }
  25142. // Result
  25143. var vertexData = new VertexData();
  25144. var positions32 = new Float32Array(positions);
  25145. var normals32 = new Float32Array(normals);
  25146. var uvs32 = new Float32Array(uvs);
  25147. vertexData.indices = indices;
  25148. vertexData.positions = positions32;
  25149. vertexData.normals = normals32;
  25150. vertexData.uvs = uvs32;
  25151. if (customColors) {
  25152. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25153. }
  25154. if (closePath) {
  25155. vertexData._idx = idx;
  25156. }
  25157. return vertexData;
  25158. };
  25159. /**
  25160. * Creates the VertexData of the Box.
  25161. */
  25162. VertexData.CreateBox = function (options) {
  25163. var normalsSource = [
  25164. new BABYLON.Vector3(0, 0, 1),
  25165. new BABYLON.Vector3(0, 0, -1),
  25166. new BABYLON.Vector3(1, 0, 0),
  25167. new BABYLON.Vector3(-1, 0, 0),
  25168. new BABYLON.Vector3(0, 1, 0),
  25169. new BABYLON.Vector3(0, -1, 0)
  25170. ];
  25171. var indices = [];
  25172. var positions = [];
  25173. var normals = [];
  25174. var uvs = [];
  25175. var width = options.width || options.size || 1;
  25176. var height = options.height || options.size || 1;
  25177. var depth = options.depth || options.size || 1;
  25178. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25179. var faceUV = options.faceUV || new Array(6);
  25180. var faceColors = options.faceColors;
  25181. var colors = [];
  25182. // default face colors and UV if undefined
  25183. for (var f = 0; f < 6; f++) {
  25184. if (faceUV[f] === undefined) {
  25185. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25186. }
  25187. if (faceColors && faceColors[f] === undefined) {
  25188. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25189. }
  25190. }
  25191. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25192. // Create each face in turn.
  25193. for (var index = 0; index < normalsSource.length; index++) {
  25194. var normal = normalsSource[index];
  25195. // Get two vectors perpendicular to the face normal and to each other.
  25196. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25197. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25198. // Six indices (two triangles) per face.
  25199. var verticesLength = positions.length / 3;
  25200. indices.push(verticesLength);
  25201. indices.push(verticesLength + 1);
  25202. indices.push(verticesLength + 2);
  25203. indices.push(verticesLength);
  25204. indices.push(verticesLength + 2);
  25205. indices.push(verticesLength + 3);
  25206. // Four vertices per face.
  25207. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25208. positions.push(vertex.x, vertex.y, vertex.z);
  25209. normals.push(normal.x, normal.y, normal.z);
  25210. uvs.push(faceUV[index].z, faceUV[index].w);
  25211. if (faceColors) {
  25212. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25213. }
  25214. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25215. positions.push(vertex.x, vertex.y, vertex.z);
  25216. normals.push(normal.x, normal.y, normal.z);
  25217. uvs.push(faceUV[index].x, faceUV[index].w);
  25218. if (faceColors) {
  25219. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25220. }
  25221. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25222. positions.push(vertex.x, vertex.y, vertex.z);
  25223. normals.push(normal.x, normal.y, normal.z);
  25224. uvs.push(faceUV[index].x, faceUV[index].y);
  25225. if (faceColors) {
  25226. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25227. }
  25228. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25229. positions.push(vertex.x, vertex.y, vertex.z);
  25230. normals.push(normal.x, normal.y, normal.z);
  25231. uvs.push(faceUV[index].z, faceUV[index].y);
  25232. if (faceColors) {
  25233. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25234. }
  25235. }
  25236. // sides
  25237. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25238. // Result
  25239. var vertexData = new VertexData();
  25240. vertexData.indices = indices;
  25241. vertexData.positions = positions;
  25242. vertexData.normals = normals;
  25243. vertexData.uvs = uvs;
  25244. if (faceColors) {
  25245. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25246. vertexData.colors = totalColors;
  25247. }
  25248. return vertexData;
  25249. };
  25250. /**
  25251. * Creates the VertexData of the Sphere.
  25252. */
  25253. VertexData.CreateSphere = function (options) {
  25254. var segments = options.segments || 32;
  25255. var diameterX = options.diameterX || options.diameter || 1;
  25256. var diameterY = options.diameterY || options.diameter || 1;
  25257. var diameterZ = options.diameterZ || options.diameter || 1;
  25258. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25259. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25260. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25261. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25262. var totalZRotationSteps = 2 + segments;
  25263. var totalYRotationSteps = 2 * totalZRotationSteps;
  25264. var indices = [];
  25265. var positions = [];
  25266. var normals = [];
  25267. var uvs = [];
  25268. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25269. var normalizedZ = zRotationStep / totalZRotationSteps;
  25270. var angleZ = normalizedZ * Math.PI * slice;
  25271. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25272. var normalizedY = yRotationStep / totalYRotationSteps;
  25273. var angleY = normalizedY * Math.PI * 2 * arc;
  25274. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25275. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25276. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25277. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25278. var vertex = complete.multiply(radius);
  25279. var normal = complete.divide(radius).normalize();
  25280. positions.push(vertex.x, vertex.y, vertex.z);
  25281. normals.push(normal.x, normal.y, normal.z);
  25282. uvs.push(normalizedY, normalizedZ);
  25283. }
  25284. if (zRotationStep > 0) {
  25285. var verticesCount = positions.length / 3;
  25286. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25287. indices.push((firstIndex));
  25288. indices.push((firstIndex + 1));
  25289. indices.push(firstIndex + totalYRotationSteps + 1);
  25290. indices.push((firstIndex + totalYRotationSteps + 1));
  25291. indices.push((firstIndex + 1));
  25292. indices.push((firstIndex + totalYRotationSteps + 2));
  25293. }
  25294. }
  25295. }
  25296. // Sides
  25297. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25298. // Result
  25299. var vertexData = new VertexData();
  25300. vertexData.indices = indices;
  25301. vertexData.positions = positions;
  25302. vertexData.normals = normals;
  25303. vertexData.uvs = uvs;
  25304. return vertexData;
  25305. };
  25306. /**
  25307. * Creates the VertexData of the Cylinder or Cone.
  25308. */
  25309. VertexData.CreateCylinder = function (options) {
  25310. var height = options.height || 2;
  25311. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25312. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25313. var tessellation = options.tessellation || 24;
  25314. var subdivisions = options.subdivisions || 1;
  25315. var hasRings = options.hasRings;
  25316. var enclose = options.enclose;
  25317. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25318. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25319. var faceUV = options.faceUV || new Array(3);
  25320. var faceColors = options.faceColors;
  25321. // default face colors and UV if undefined
  25322. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25323. var ringNb = (hasRings) ? subdivisions : 1;
  25324. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25325. var f;
  25326. for (f = 0; f < surfaceNb; f++) {
  25327. if (faceColors && faceColors[f] === undefined) {
  25328. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25329. }
  25330. }
  25331. for (f = 0; f < surfaceNb; f++) {
  25332. if (faceUV && faceUV[f] === undefined) {
  25333. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25334. }
  25335. }
  25336. var indices = [];
  25337. var positions = [];
  25338. var normals = [];
  25339. var uvs = [];
  25340. var colors = [];
  25341. var angle_step = Math.PI * 2 * arc / tessellation;
  25342. var angle;
  25343. var h;
  25344. var radius;
  25345. var tan = (diameterBottom - diameterTop) / 2 / height;
  25346. var ringVertex = BABYLON.Vector3.Zero();
  25347. var ringNormal = BABYLON.Vector3.Zero();
  25348. var ringFirstVertex = BABYLON.Vector3.Zero();
  25349. var ringFirstNormal = BABYLON.Vector3.Zero();
  25350. var quadNormal = BABYLON.Vector3.Zero();
  25351. var Y = BABYLON.Axis.Y;
  25352. // positions, normals, uvs
  25353. var i;
  25354. var j;
  25355. var r;
  25356. var ringIdx = 1;
  25357. var s = 1; // surface index
  25358. var cs = 0;
  25359. var v = 0;
  25360. for (i = 0; i <= subdivisions; i++) {
  25361. h = i / subdivisions;
  25362. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25363. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25364. for (r = 0; r < ringIdx; r++) {
  25365. if (hasRings) {
  25366. s += r;
  25367. }
  25368. if (enclose) {
  25369. s += 2 * r;
  25370. }
  25371. for (j = 0; j <= tessellation; j++) {
  25372. angle = j * angle_step;
  25373. // position
  25374. ringVertex.x = Math.cos(-angle) * radius;
  25375. ringVertex.y = -height / 2 + h * height;
  25376. ringVertex.z = Math.sin(-angle) * radius;
  25377. // normal
  25378. if (diameterTop === 0 && i === subdivisions) {
  25379. // if no top cap, reuse former normals
  25380. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25381. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25382. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25383. }
  25384. else {
  25385. ringNormal.x = ringVertex.x;
  25386. ringNormal.z = ringVertex.z;
  25387. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25388. ringNormal.normalize();
  25389. }
  25390. // keep first ring vertex values for enclose
  25391. if (j === 0) {
  25392. ringFirstVertex.copyFrom(ringVertex);
  25393. ringFirstNormal.copyFrom(ringNormal);
  25394. }
  25395. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25396. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25397. if (hasRings) {
  25398. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25399. }
  25400. else {
  25401. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25402. }
  25403. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25404. if (faceColors) {
  25405. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25406. }
  25407. }
  25408. // if enclose, add four vertices and their dedicated normals
  25409. if (arc !== 1 && enclose) {
  25410. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25411. positions.push(0, ringVertex.y, 0);
  25412. positions.push(0, ringVertex.y, 0);
  25413. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25414. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25415. quadNormal.normalize();
  25416. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25417. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25418. quadNormal.normalize();
  25419. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25420. if (hasRings) {
  25421. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25422. }
  25423. else {
  25424. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25425. }
  25426. uvs.push(faceUV[s + 1].x, v);
  25427. uvs.push(faceUV[s + 1].z, v);
  25428. if (hasRings) {
  25429. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25430. }
  25431. else {
  25432. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25433. }
  25434. uvs.push(faceUV[s + 2].x, v);
  25435. uvs.push(faceUV[s + 2].z, v);
  25436. if (faceColors) {
  25437. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25438. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25439. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25440. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25441. }
  25442. }
  25443. if (cs !== s) {
  25444. cs = s;
  25445. }
  25446. }
  25447. }
  25448. // indices
  25449. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25450. var s;
  25451. i = 0;
  25452. for (s = 0; s < subdivisions; s++) {
  25453. for (j = 0; j < tessellation; j++) {
  25454. var i0 = i * (e + 1) + j;
  25455. var i1 = (i + 1) * (e + 1) + j;
  25456. var i2 = i * (e + 1) + (j + 1);
  25457. var i3 = (i + 1) * (e + 1) + (j + 1);
  25458. indices.push(i0, i1, i2);
  25459. indices.push(i3, i2, i1);
  25460. }
  25461. if (arc !== 1 && enclose) {
  25462. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25463. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25464. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25465. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25466. }
  25467. i = (hasRings) ? (i + 2) : (i + 1);
  25468. }
  25469. // Caps
  25470. var createCylinderCap = function (isTop) {
  25471. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25472. if (radius === 0) {
  25473. return;
  25474. }
  25475. // Cap positions, normals & uvs
  25476. var angle;
  25477. var circleVector;
  25478. var i;
  25479. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25480. var c;
  25481. if (faceColors) {
  25482. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25483. }
  25484. // cap center
  25485. var vbase = positions.length / 3;
  25486. var offset = isTop ? height / 2 : -height / 2;
  25487. var center = new BABYLON.Vector3(0, offset, 0);
  25488. positions.push(center.x, center.y, center.z);
  25489. normals.push(0, isTop ? 1 : -1, 0);
  25490. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25491. if (faceColors) {
  25492. colors.push(c.r, c.g, c.b, c.a);
  25493. }
  25494. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25495. for (i = 0; i <= tessellation; i++) {
  25496. angle = Math.PI * 2 * i * arc / tessellation;
  25497. var cos = Math.cos(-angle);
  25498. var sin = Math.sin(-angle);
  25499. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25500. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25501. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25502. normals.push(0, isTop ? 1 : -1, 0);
  25503. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25504. if (faceColors) {
  25505. colors.push(c.r, c.g, c.b, c.a);
  25506. }
  25507. }
  25508. // Cap indices
  25509. for (i = 0; i < tessellation; i++) {
  25510. if (!isTop) {
  25511. indices.push(vbase);
  25512. indices.push(vbase + (i + 1));
  25513. indices.push(vbase + (i + 2));
  25514. }
  25515. else {
  25516. indices.push(vbase);
  25517. indices.push(vbase + (i + 2));
  25518. indices.push(vbase + (i + 1));
  25519. }
  25520. }
  25521. };
  25522. // add caps to geometry
  25523. createCylinderCap(false);
  25524. createCylinderCap(true);
  25525. // Sides
  25526. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25527. var vertexData = new VertexData();
  25528. vertexData.indices = indices;
  25529. vertexData.positions = positions;
  25530. vertexData.normals = normals;
  25531. vertexData.uvs = uvs;
  25532. if (faceColors) {
  25533. vertexData.colors = colors;
  25534. }
  25535. return vertexData;
  25536. };
  25537. /**
  25538. * Creates the VertexData of the Torus.
  25539. */
  25540. VertexData.CreateTorus = function (options) {
  25541. var indices = [];
  25542. var positions = [];
  25543. var normals = [];
  25544. var uvs = [];
  25545. var diameter = options.diameter || 1;
  25546. var thickness = options.thickness || 0.5;
  25547. var tessellation = options.tessellation || 16;
  25548. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25549. var stride = tessellation + 1;
  25550. for (var i = 0; i <= tessellation; i++) {
  25551. var u = i / tessellation;
  25552. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25553. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25554. for (var j = 0; j <= tessellation; j++) {
  25555. var v = 1 - j / tessellation;
  25556. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25557. var dx = Math.cos(innerAngle);
  25558. var dy = Math.sin(innerAngle);
  25559. // Create a vertex.
  25560. var normal = new BABYLON.Vector3(dx, dy, 0);
  25561. var position = normal.scale(thickness / 2);
  25562. var textureCoordinate = new BABYLON.Vector2(u, v);
  25563. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25564. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25565. positions.push(position.x, position.y, position.z);
  25566. normals.push(normal.x, normal.y, normal.z);
  25567. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25568. // And create indices for two triangles.
  25569. var nextI = (i + 1) % stride;
  25570. var nextJ = (j + 1) % stride;
  25571. indices.push(i * stride + j);
  25572. indices.push(i * stride + nextJ);
  25573. indices.push(nextI * stride + j);
  25574. indices.push(i * stride + nextJ);
  25575. indices.push(nextI * stride + nextJ);
  25576. indices.push(nextI * stride + j);
  25577. }
  25578. }
  25579. // Sides
  25580. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25581. // Result
  25582. var vertexData = new VertexData();
  25583. vertexData.indices = indices;
  25584. vertexData.positions = positions;
  25585. vertexData.normals = normals;
  25586. vertexData.uvs = uvs;
  25587. return vertexData;
  25588. };
  25589. /**
  25590. * Creates the VertexData of the LineSystem.
  25591. */
  25592. VertexData.CreateLineSystem = function (options) {
  25593. var indices = [];
  25594. var positions = [];
  25595. var lines = options.lines;
  25596. var idx = 0;
  25597. for (var l = 0; l < lines.length; l++) {
  25598. var points = lines[l];
  25599. for (var index = 0; index < points.length; index++) {
  25600. positions.push(points[index].x, points[index].y, points[index].z);
  25601. if (index > 0) {
  25602. indices.push(idx - 1);
  25603. indices.push(idx);
  25604. }
  25605. idx++;
  25606. }
  25607. }
  25608. var vertexData = new VertexData();
  25609. vertexData.indices = indices;
  25610. vertexData.positions = positions;
  25611. return vertexData;
  25612. };
  25613. /**
  25614. * Create the VertexData of the DashedLines.
  25615. */
  25616. VertexData.CreateDashedLines = function (options) {
  25617. var dashSize = options.dashSize || 3;
  25618. var gapSize = options.gapSize || 1;
  25619. var dashNb = options.dashNb || 200;
  25620. var points = options.points;
  25621. var positions = new Array();
  25622. var indices = new Array();
  25623. var curvect = BABYLON.Vector3.Zero();
  25624. var lg = 0;
  25625. var nb = 0;
  25626. var shft = 0;
  25627. var dashshft = 0;
  25628. var curshft = 0;
  25629. var idx = 0;
  25630. var i = 0;
  25631. for (i = 0; i < points.length - 1; i++) {
  25632. points[i + 1].subtractToRef(points[i], curvect);
  25633. lg += curvect.length();
  25634. }
  25635. shft = lg / dashNb;
  25636. dashshft = dashSize * shft / (dashSize + gapSize);
  25637. for (i = 0; i < points.length - 1; i++) {
  25638. points[i + 1].subtractToRef(points[i], curvect);
  25639. nb = Math.floor(curvect.length() / shft);
  25640. curvect.normalize();
  25641. for (var j = 0; j < nb; j++) {
  25642. curshft = shft * j;
  25643. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25644. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25645. indices.push(idx, idx + 1);
  25646. idx += 2;
  25647. }
  25648. }
  25649. // Result
  25650. var vertexData = new VertexData();
  25651. vertexData.positions = positions;
  25652. vertexData.indices = indices;
  25653. return vertexData;
  25654. };
  25655. /**
  25656. * Creates the VertexData of the Ground.
  25657. */
  25658. VertexData.CreateGround = function (options) {
  25659. var indices = [];
  25660. var positions = [];
  25661. var normals = [];
  25662. var uvs = [];
  25663. var row, col;
  25664. var width = options.width || 1;
  25665. var height = options.height || 1;
  25666. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25667. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25668. for (row = 0; row <= subdivisionsY; row++) {
  25669. for (col = 0; col <= subdivisionsX; col++) {
  25670. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  25671. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25672. positions.push(position.x, position.y, position.z);
  25673. normals.push(normal.x, normal.y, normal.z);
  25674. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  25675. }
  25676. }
  25677. for (row = 0; row < subdivisionsY; row++) {
  25678. for (col = 0; col < subdivisionsX; col++) {
  25679. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25680. indices.push(col + 1 + row * (subdivisionsX + 1));
  25681. indices.push(col + row * (subdivisionsX + 1));
  25682. indices.push(col + (row + 1) * (subdivisionsX + 1));
  25683. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25684. indices.push(col + row * (subdivisionsX + 1));
  25685. }
  25686. }
  25687. // Result
  25688. var vertexData = new VertexData();
  25689. vertexData.indices = indices;
  25690. vertexData.positions = positions;
  25691. vertexData.normals = normals;
  25692. vertexData.uvs = uvs;
  25693. return vertexData;
  25694. };
  25695. /**
  25696. * Creates the VertexData of the TiledGround.
  25697. */
  25698. VertexData.CreateTiledGround = function (options) {
  25699. var xmin = options.xmin || -1.0;
  25700. var zmin = options.zmin || -1.0;
  25701. var xmax = options.xmax || 1.0;
  25702. var zmax = options.zmax || 1.0;
  25703. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25704. var precision = options.precision || { w: 1, h: 1 };
  25705. var indices = [];
  25706. var positions = [];
  25707. var normals = [];
  25708. var uvs = [];
  25709. var row, col, tileRow, tileCol;
  25710. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  25711. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25712. precision.w = (precision.w < 1) ? 1 : precision.w;
  25713. precision.h = (precision.h < 1) ? 1 : precision.h;
  25714. var tileSize = {
  25715. 'w': (xmax - xmin) / subdivisions.w,
  25716. 'h': (zmax - zmin) / subdivisions.h
  25717. };
  25718. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25719. // Indices
  25720. var base = positions.length / 3;
  25721. var rowLength = precision.w + 1;
  25722. for (row = 0; row < precision.h; row++) {
  25723. for (col = 0; col < precision.w; col++) {
  25724. var square = [
  25725. base + col + row * rowLength,
  25726. base + (col + 1) + row * rowLength,
  25727. base + (col + 1) + (row + 1) * rowLength,
  25728. base + col + (row + 1) * rowLength
  25729. ];
  25730. indices.push(square[1]);
  25731. indices.push(square[2]);
  25732. indices.push(square[3]);
  25733. indices.push(square[0]);
  25734. indices.push(square[1]);
  25735. indices.push(square[3]);
  25736. }
  25737. }
  25738. // Position, normals and uvs
  25739. var position = BABYLON.Vector3.Zero();
  25740. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25741. for (row = 0; row <= precision.h; row++) {
  25742. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25743. for (col = 0; col <= precision.w; col++) {
  25744. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25745. position.y = 0;
  25746. positions.push(position.x, position.y, position.z);
  25747. normals.push(normal.x, normal.y, normal.z);
  25748. uvs.push(col / precision.w, row / precision.h);
  25749. }
  25750. }
  25751. }
  25752. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25753. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25754. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25755. }
  25756. }
  25757. // Result
  25758. var vertexData = new VertexData();
  25759. vertexData.indices = indices;
  25760. vertexData.positions = positions;
  25761. vertexData.normals = normals;
  25762. vertexData.uvs = uvs;
  25763. return vertexData;
  25764. };
  25765. /**
  25766. * Creates the VertexData of the Ground designed from a heightmap.
  25767. */
  25768. VertexData.CreateGroundFromHeightMap = function (options) {
  25769. var indices = [];
  25770. var positions = [];
  25771. var normals = [];
  25772. var uvs = [];
  25773. var row, col;
  25774. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25775. // Vertices
  25776. for (row = 0; row <= options.subdivisions; row++) {
  25777. for (col = 0; col <= options.subdivisions; col++) {
  25778. 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));
  25779. // Compute height
  25780. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25781. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25782. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25783. var r = options.buffer[pos] / 255.0;
  25784. var g = options.buffer[pos + 1] / 255.0;
  25785. var b = options.buffer[pos + 2] / 255.0;
  25786. var gradient = r * filter.r + g * filter.g + b * filter.b;
  25787. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25788. // Add vertex
  25789. positions.push(position.x, position.y, position.z);
  25790. normals.push(0, 0, 0);
  25791. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25792. }
  25793. }
  25794. // Indices
  25795. for (row = 0; row < options.subdivisions; row++) {
  25796. for (col = 0; col < options.subdivisions; col++) {
  25797. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25798. indices.push(col + 1 + row * (options.subdivisions + 1));
  25799. indices.push(col + row * (options.subdivisions + 1));
  25800. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25801. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25802. indices.push(col + row * (options.subdivisions + 1));
  25803. }
  25804. }
  25805. // Normals
  25806. VertexData.ComputeNormals(positions, indices, normals);
  25807. // Result
  25808. var vertexData = new VertexData();
  25809. vertexData.indices = indices;
  25810. vertexData.positions = positions;
  25811. vertexData.normals = normals;
  25812. vertexData.uvs = uvs;
  25813. return vertexData;
  25814. };
  25815. /**
  25816. * Creates the VertexData of the Plane.
  25817. */
  25818. VertexData.CreatePlane = function (options) {
  25819. var indices = [];
  25820. var positions = [];
  25821. var normals = [];
  25822. var uvs = [];
  25823. var width = options.width || options.size || 1;
  25824. var height = options.height || options.size || 1;
  25825. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25826. // Vertices
  25827. var halfWidth = width / 2.0;
  25828. var halfHeight = height / 2.0;
  25829. positions.push(-halfWidth, -halfHeight, 0);
  25830. normals.push(0, 0, -1.0);
  25831. uvs.push(0.0, 0.0);
  25832. positions.push(halfWidth, -halfHeight, 0);
  25833. normals.push(0, 0, -1.0);
  25834. uvs.push(1.0, 0.0);
  25835. positions.push(halfWidth, halfHeight, 0);
  25836. normals.push(0, 0, -1.0);
  25837. uvs.push(1.0, 1.0);
  25838. positions.push(-halfWidth, halfHeight, 0);
  25839. normals.push(0, 0, -1.0);
  25840. uvs.push(0.0, 1.0);
  25841. // Indices
  25842. indices.push(0);
  25843. indices.push(1);
  25844. indices.push(2);
  25845. indices.push(0);
  25846. indices.push(2);
  25847. indices.push(3);
  25848. // Sides
  25849. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25850. // Result
  25851. var vertexData = new VertexData();
  25852. vertexData.indices = indices;
  25853. vertexData.positions = positions;
  25854. vertexData.normals = normals;
  25855. vertexData.uvs = uvs;
  25856. return vertexData;
  25857. };
  25858. /**
  25859. * Creates the VertexData of the Disc or regular Polygon.
  25860. */
  25861. VertexData.CreateDisc = function (options) {
  25862. var positions = [];
  25863. var indices = [];
  25864. var normals = [];
  25865. var uvs = [];
  25866. var radius = options.radius || 0.5;
  25867. var tessellation = options.tessellation || 64;
  25868. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25869. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25870. // positions and uvs
  25871. positions.push(0, 0, 0); // disc center first
  25872. uvs.push(0.5, 0.5);
  25873. var theta = Math.PI * 2 * arc;
  25874. var step = theta / tessellation;
  25875. for (var a = 0; a < theta; a += step) {
  25876. var x = Math.cos(a);
  25877. var y = Math.sin(a);
  25878. var u = (x + 1) / 2;
  25879. var v = (1 - y) / 2;
  25880. positions.push(radius * x, radius * y, 0);
  25881. uvs.push(u, v);
  25882. }
  25883. if (arc === 1) {
  25884. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25885. uvs.push(uvs[2], uvs[3]);
  25886. }
  25887. //indices
  25888. var vertexNb = positions.length / 3;
  25889. for (var i = 1; i < vertexNb - 1; i++) {
  25890. indices.push(i + 1, 0, i);
  25891. }
  25892. // result
  25893. VertexData.ComputeNormals(positions, indices, normals);
  25894. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25895. var vertexData = new VertexData();
  25896. vertexData.indices = indices;
  25897. vertexData.positions = positions;
  25898. vertexData.normals = normals;
  25899. vertexData.uvs = uvs;
  25900. return vertexData;
  25901. };
  25902. /**
  25903. * Re-creates the VertexData of the Polygon for sideOrientation.
  25904. */
  25905. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  25906. var faceUV = fUV || new Array(3);
  25907. var faceColors = fColors;
  25908. var colors = [];
  25909. // default face colors and UV if undefined
  25910. for (var f = 0; f < 3; f++) {
  25911. if (faceUV[f] === undefined) {
  25912. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25913. }
  25914. if (faceColors && faceColors[f] === undefined) {
  25915. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25916. }
  25917. }
  25918. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25919. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25920. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25921. var indices = polygon.getIndices();
  25922. // set face colours and textures
  25923. var idx = 0;
  25924. var face = 0;
  25925. for (var index = 0; index < normals.length; index += 3) {
  25926. //Edge Face no. 1
  25927. if (Math.abs(normals[index + 1]) == 0) {
  25928. face = 1;
  25929. }
  25930. //Top Face no. 0
  25931. if (normals[index + 1] == 1) {
  25932. face = 0;
  25933. }
  25934. //Bottom Face no. 2
  25935. if (normals[index + 1] == -1) {
  25936. face = 2;
  25937. }
  25938. idx = index / 3;
  25939. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  25940. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  25941. if (faceColors) {
  25942. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  25943. }
  25944. }
  25945. // sides
  25946. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  25947. // Result
  25948. var vertexData = new VertexData();
  25949. vertexData.indices = indices;
  25950. vertexData.positions = positions;
  25951. vertexData.normals = normals;
  25952. vertexData.uvs = uvs;
  25953. if (faceColors) {
  25954. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25955. vertexData.colors = totalColors;
  25956. }
  25957. return vertexData;
  25958. };
  25959. /**
  25960. * Creates the VertexData of the IcoSphere.
  25961. */
  25962. VertexData.CreateIcoSphere = function (options) {
  25963. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25964. var radius = options.radius || 1;
  25965. var flat = (options.flat === undefined) ? true : options.flat;
  25966. var subdivisions = options.subdivisions || 4;
  25967. var radiusX = options.radiusX || radius;
  25968. var radiusY = options.radiusY || radius;
  25969. var radiusZ = options.radiusZ || radius;
  25970. var t = (1 + Math.sqrt(5)) / 2;
  25971. // 12 vertex x,y,z
  25972. var ico_vertices = [
  25973. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25974. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25975. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  25976. ];
  25977. // index of 3 vertex makes a face of icopshere
  25978. var ico_indices = [
  25979. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  25980. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  25981. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  25982. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  25983. ];
  25984. // vertex for uv have aliased position, not for UV
  25985. var vertices_unalias_id = [
  25986. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25987. // vertex alias
  25988. 0,
  25989. 2,
  25990. 3,
  25991. 3,
  25992. 3,
  25993. 4,
  25994. 7,
  25995. 8,
  25996. 9,
  25997. 9,
  25998. 10,
  25999. 11 // 23: B + 12
  26000. ];
  26001. // uv as integer step (not pixels !)
  26002. var ico_vertexuv = [
  26003. 5, 1, 3, 1, 6, 4, 0, 0,
  26004. 5, 3, 4, 2, 2, 2, 4, 0,
  26005. 2, 0, 1, 1, 6, 0, 6, 2,
  26006. // vertex alias (for same vertex on different faces)
  26007. 0, 4,
  26008. 3, 3,
  26009. 4, 4,
  26010. 3, 1,
  26011. 4, 2,
  26012. 4, 4,
  26013. 0, 2,
  26014. 1, 1,
  26015. 2, 2,
  26016. 3, 3,
  26017. 1, 3,
  26018. 2, 4 // 23: B + 12
  26019. ];
  26020. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26021. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26022. // First island of uv mapping
  26023. // v = 4h 3+ 2
  26024. // v = 3h 9+ 4
  26025. // v = 2h 9+ 5 B
  26026. // v = 1h 9 1 0
  26027. // v = 0h 3 8 7 A
  26028. // u = 0 1 2 3 4 5 6 *a
  26029. // Second island of uv mapping
  26030. // v = 4h 0+ B+ 4+
  26031. // v = 3h A+ 2+
  26032. // v = 2h 7+ 6 3+
  26033. // v = 1h 8+ 3+
  26034. // v = 0h
  26035. // u = 0 1 2 3 4 5 6 *a
  26036. // Face layout on texture UV mapping
  26037. // ============
  26038. // \ 4 /\ 16 / ======
  26039. // \ / \ / /\ 11 /
  26040. // \/ 7 \/ / \ /
  26041. // ======= / 10 \/
  26042. // /\ 17 /\ =======
  26043. // / \ / \ \ 15 /\
  26044. // / 8 \/ 12 \ \ / \
  26045. // ============ \/ 6 \
  26046. // \ 18 /\ ============
  26047. // \ / \ \ 5 /\ 0 /
  26048. // \/ 13 \ \ / \ /
  26049. // ======= \/ 1 \/
  26050. // =============
  26051. // /\ 19 /\ 2 /\
  26052. // / \ / \ / \
  26053. // / 14 \/ 9 \/ 3 \
  26054. // ===================
  26055. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26056. var ustep = 138 / 1024;
  26057. var vstep = 239 / 1024;
  26058. var uoffset = 60 / 1024;
  26059. var voffset = 26 / 1024;
  26060. // Second island should have margin, not to touch the first island
  26061. // avoid any borderline artefact in pixel rounding
  26062. var island_u_offset = -40 / 1024;
  26063. var island_v_offset = +20 / 1024;
  26064. // face is either island 0 or 1 :
  26065. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26066. var island = [
  26067. 0, 0, 0, 0, 1,
  26068. 0, 0, 1, 1, 0,
  26069. 0, 0, 1, 1, 0,
  26070. 0, 1, 1, 1, 0 // 15 - 19
  26071. ];
  26072. var indices = [];
  26073. var positions = [];
  26074. var normals = [];
  26075. var uvs = [];
  26076. var current_indice = 0;
  26077. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26078. var face_vertex_pos = new Array(3);
  26079. var face_vertex_uv = new Array(3);
  26080. var v012;
  26081. for (v012 = 0; v012 < 3; v012++) {
  26082. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26083. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26084. }
  26085. // create all with normals
  26086. for (var face = 0; face < 20; face++) {
  26087. // 3 vertex per face
  26088. for (v012 = 0; v012 < 3; v012++) {
  26089. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26090. var v_id = ico_indices[3 * face + v012];
  26091. // vertex have 3D position (x,y,z)
  26092. 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]);
  26093. // Normalize to get normal, then scale to radius
  26094. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26095. // uv Coordinates from vertex ID
  26096. 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);
  26097. }
  26098. // Subdivide the face (interpolate pos, norm, uv)
  26099. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26100. // - norm is linear interpolation of vertex corner normal
  26101. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26102. // - uv is linear interpolation
  26103. //
  26104. // Topology is as below for sub-divide by 2
  26105. // vertex shown as v0,v1,v2
  26106. // interp index is i1 to progress in range [v0,v1[
  26107. // interp index is i2 to progress in range [v0,v2[
  26108. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26109. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26110. //
  26111. //
  26112. // i2 v2
  26113. // ^ ^
  26114. // / / \
  26115. // / / \
  26116. // / / \
  26117. // / / (0,1) \
  26118. // / #---------\
  26119. // / / \ (0,0)'/ \
  26120. // / / \ / \
  26121. // / / \ / \
  26122. // / / (0,0) \ / (1,0) \
  26123. // / #---------#---------\
  26124. // v0 v1
  26125. //
  26126. // --------------------> i1
  26127. //
  26128. // interp of (i1,i2):
  26129. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26130. // along i1 : lerp(x0,x1, i1/(S-i2))
  26131. //
  26132. // centroid of triangle is needed to get help normal computation
  26133. // (c1,c2) are used for centroid location
  26134. var interp_vertex = function (i1, i2, c1, c2) {
  26135. // vertex is interpolated from
  26136. // - face_vertex_pos[0..2]
  26137. // - face_vertex_uv[0..2]
  26138. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26139. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26140. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26141. pos_interp.normalize();
  26142. var vertex_normal;
  26143. if (flat) {
  26144. // in flat mode, recalculate normal as face centroid normal
  26145. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26146. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26147. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26148. }
  26149. else {
  26150. // in smooth mode, recalculate normal from each single vertex position
  26151. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26152. }
  26153. // Vertex normal need correction due to X,Y,Z radius scaling
  26154. vertex_normal.x /= radiusX;
  26155. vertex_normal.y /= radiusY;
  26156. vertex_normal.z /= radiusZ;
  26157. vertex_normal.normalize();
  26158. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26159. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26160. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26161. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26162. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26163. uvs.push(uv_interp.x, uv_interp.y);
  26164. // push each vertex has member of a face
  26165. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26166. indices.push(current_indice);
  26167. current_indice++;
  26168. };
  26169. for (var i2 = 0; i2 < subdivisions; i2++) {
  26170. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26171. // face : (i1,i2) for /\ :
  26172. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26173. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26174. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26175. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26176. if (i1 + i2 + 1 < subdivisions) {
  26177. // face : (i1,i2)' for \/ :
  26178. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26179. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26180. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26181. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26182. }
  26183. }
  26184. }
  26185. }
  26186. // Sides
  26187. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26188. // Result
  26189. var vertexData = new VertexData();
  26190. vertexData.indices = indices;
  26191. vertexData.positions = positions;
  26192. vertexData.normals = normals;
  26193. vertexData.uvs = uvs;
  26194. return vertexData;
  26195. };
  26196. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26197. /**
  26198. * Creates the VertexData of the Polyhedron.
  26199. */
  26200. VertexData.CreatePolyhedron = function (options) {
  26201. // provided polyhedron types :
  26202. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26203. // 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)
  26204. var polyhedra = [];
  26205. 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]] };
  26206. 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]] };
  26207. polyhedra[2] = {
  26208. 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]],
  26209. 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]]
  26210. };
  26211. polyhedra[3] = {
  26212. 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]],
  26213. 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]]
  26214. };
  26215. polyhedra[4] = {
  26216. 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]],
  26217. 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]]
  26218. };
  26219. 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]] };
  26220. 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]] };
  26221. 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]] };
  26222. 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]] };
  26223. 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]] };
  26224. 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]] };
  26225. 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]] };
  26226. 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]] };
  26227. 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]] };
  26228. polyhedra[14] = {
  26229. 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]],
  26230. 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]]
  26231. };
  26232. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26233. var size = options.size;
  26234. var sizeX = options.sizeX || size || 1;
  26235. var sizeY = options.sizeY || size || 1;
  26236. var sizeZ = options.sizeZ || size || 1;
  26237. var data = options.custom || polyhedra[type];
  26238. var nbfaces = data.face.length;
  26239. var faceUV = options.faceUV || new Array(nbfaces);
  26240. var faceColors = options.faceColors;
  26241. var flat = (options.flat === undefined) ? true : options.flat;
  26242. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26243. var positions = [];
  26244. var indices = [];
  26245. var normals = [];
  26246. var uvs = [];
  26247. var colors = [];
  26248. var index = 0;
  26249. var faceIdx = 0; // face cursor in the array "indexes"
  26250. var indexes = [];
  26251. var i = 0;
  26252. var f = 0;
  26253. var u, v, ang, x, y, tmp;
  26254. // default face colors and UV if undefined
  26255. if (flat) {
  26256. for (f = 0; f < nbfaces; f++) {
  26257. if (faceColors && faceColors[f] === undefined) {
  26258. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26259. }
  26260. if (faceUV && faceUV[f] === undefined) {
  26261. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26262. }
  26263. }
  26264. }
  26265. if (!flat) {
  26266. for (i = 0; i < data.vertex.length; i++) {
  26267. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26268. uvs.push(0, 0);
  26269. }
  26270. for (f = 0; f < nbfaces; f++) {
  26271. for (i = 0; i < data.face[f].length - 2; i++) {
  26272. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26273. }
  26274. }
  26275. }
  26276. else {
  26277. for (f = 0; f < nbfaces; f++) {
  26278. var fl = data.face[f].length; // number of vertices of the current face
  26279. ang = 2 * Math.PI / fl;
  26280. x = 0.5 * Math.tan(ang / 2);
  26281. y = 0.5;
  26282. // positions, uvs, colors
  26283. for (i = 0; i < fl; i++) {
  26284. // positions
  26285. 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);
  26286. indexes.push(index);
  26287. index++;
  26288. // uvs
  26289. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26290. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26291. uvs.push(u, v);
  26292. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26293. y = x * Math.sin(ang) + y * Math.cos(ang);
  26294. x = tmp;
  26295. // colors
  26296. if (faceColors) {
  26297. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26298. }
  26299. }
  26300. // indices from indexes
  26301. for (i = 0; i < fl - 2; i++) {
  26302. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26303. }
  26304. faceIdx += fl;
  26305. }
  26306. }
  26307. VertexData.ComputeNormals(positions, indices, normals);
  26308. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26309. var vertexData = new VertexData();
  26310. vertexData.positions = positions;
  26311. vertexData.indices = indices;
  26312. vertexData.normals = normals;
  26313. vertexData.uvs = uvs;
  26314. if (faceColors && flat) {
  26315. vertexData.colors = colors;
  26316. }
  26317. return vertexData;
  26318. };
  26319. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26320. /**
  26321. * Creates the VertexData of the Torus Knot.
  26322. */
  26323. VertexData.CreateTorusKnot = function (options) {
  26324. var indices = [];
  26325. var positions = [];
  26326. var normals = [];
  26327. var uvs = [];
  26328. var radius = options.radius || 2;
  26329. var tube = options.tube || 0.5;
  26330. var radialSegments = options.radialSegments || 32;
  26331. var tubularSegments = options.tubularSegments || 32;
  26332. var p = options.p || 2;
  26333. var q = options.q || 3;
  26334. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26335. // Helper
  26336. var getPos = function (angle) {
  26337. var cu = Math.cos(angle);
  26338. var su = Math.sin(angle);
  26339. var quOverP = q / p * angle;
  26340. var cs = Math.cos(quOverP);
  26341. var tx = radius * (2 + cs) * 0.5 * cu;
  26342. var ty = radius * (2 + cs) * su * 0.5;
  26343. var tz = radius * Math.sin(quOverP) * 0.5;
  26344. return new BABYLON.Vector3(tx, ty, tz);
  26345. };
  26346. // Vertices
  26347. var i;
  26348. var j;
  26349. for (i = 0; i <= radialSegments; i++) {
  26350. var modI = i % radialSegments;
  26351. var u = modI / radialSegments * 2 * p * Math.PI;
  26352. var p1 = getPos(u);
  26353. var p2 = getPos(u + 0.01);
  26354. var tang = p2.subtract(p1);
  26355. var n = p2.add(p1);
  26356. var bitan = BABYLON.Vector3.Cross(tang, n);
  26357. n = BABYLON.Vector3.Cross(bitan, tang);
  26358. bitan.normalize();
  26359. n.normalize();
  26360. for (j = 0; j < tubularSegments; j++) {
  26361. var modJ = j % tubularSegments;
  26362. var v = modJ / tubularSegments * 2 * Math.PI;
  26363. var cx = -tube * Math.cos(v);
  26364. var cy = tube * Math.sin(v);
  26365. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26366. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26367. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26368. uvs.push(i / radialSegments);
  26369. uvs.push(j / tubularSegments);
  26370. }
  26371. }
  26372. for (i = 0; i < radialSegments; i++) {
  26373. for (j = 0; j < tubularSegments; j++) {
  26374. var jNext = (j + 1) % tubularSegments;
  26375. var a = i * tubularSegments + j;
  26376. var b = (i + 1) * tubularSegments + j;
  26377. var c = (i + 1) * tubularSegments + jNext;
  26378. var d = i * tubularSegments + jNext;
  26379. indices.push(d);
  26380. indices.push(b);
  26381. indices.push(a);
  26382. indices.push(d);
  26383. indices.push(c);
  26384. indices.push(b);
  26385. }
  26386. }
  26387. // Normals
  26388. VertexData.ComputeNormals(positions, indices, normals);
  26389. // Sides
  26390. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26391. // Result
  26392. var vertexData = new VertexData();
  26393. vertexData.indices = indices;
  26394. vertexData.positions = positions;
  26395. vertexData.normals = normals;
  26396. vertexData.uvs = uvs;
  26397. return vertexData;
  26398. };
  26399. // Tools
  26400. /**
  26401. * @param {any} - positions (number[] or Float32Array)
  26402. * @param {any} - indices (number[] or Uint16Array)
  26403. * @param {any} - normals (number[] or Float32Array)
  26404. * options (optional) :
  26405. * facetPositions : optional array of facet positions (vector3)
  26406. * facetNormals : optional array of facet normals (vector3)
  26407. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26408. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26409. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26410. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26411. * bInfo : optional bounding info, required for facetPartitioning computation
  26412. */
  26413. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26414. // temporary scalar variables
  26415. var index = 0; // facet index
  26416. var p1p2x = 0.0; // p1p2 vector x coordinate
  26417. var p1p2y = 0.0; // p1p2 vector y coordinate
  26418. var p1p2z = 0.0; // p1p2 vector z coordinate
  26419. var p3p2x = 0.0; // p3p2 vector x coordinate
  26420. var p3p2y = 0.0; // p3p2 vector y coordinate
  26421. var p3p2z = 0.0; // p3p2 vector z coordinate
  26422. var faceNormalx = 0.0; // facet normal x coordinate
  26423. var faceNormaly = 0.0; // facet normal y coordinate
  26424. var faceNormalz = 0.0; // facet normal z coordinate
  26425. var length = 0.0; // facet normal length before normalization
  26426. var v1x = 0; // vector1 x index in the positions array
  26427. var v1y = 0; // vector1 y index in the positions array
  26428. var v1z = 0; // vector1 z index in the positions array
  26429. var v2x = 0; // vector2 x index in the positions array
  26430. var v2y = 0; // vector2 y index in the positions array
  26431. var v2z = 0; // vector2 z index in the positions array
  26432. var v3x = 0; // vector3 x index in the positions array
  26433. var v3y = 0; // vector3 y index in the positions array
  26434. var v3z = 0; // vector3 z index in the positions array
  26435. var computeFacetNormals = false;
  26436. var computeFacetPositions = false;
  26437. var computeFacetPartitioning = false;
  26438. var faceNormalSign = 1;
  26439. if (options) {
  26440. computeFacetNormals = (options.facetNormals) ? true : false;
  26441. computeFacetPositions = (options.facetPositions) ? true : false;
  26442. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26443. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26444. }
  26445. // facetPartitioning reinit if needed
  26446. if (computeFacetPartitioning) {
  26447. var ox = 0; // X partitioning index for facet position
  26448. var oy = 0; // Y partinioning index for facet position
  26449. var oz = 0; // Z partinioning index for facet position
  26450. var b1x = 0; // X partitioning index for facet v1 vertex
  26451. var b1y = 0; // Y partitioning index for facet v1 vertex
  26452. var b1z = 0; // z partitioning index for facet v1 vertex
  26453. var b2x = 0; // X partitioning index for facet v2 vertex
  26454. var b2y = 0; // Y partitioning index for facet v2 vertex
  26455. var b2z = 0; // Z partitioning index for facet v2 vertex
  26456. var b3x = 0; // X partitioning index for facet v3 vertex
  26457. var b3y = 0; // Y partitioning index for facet v3 vertex
  26458. var b3z = 0; // Z partitioning index for facet v3 vertex
  26459. var block_idx_o = 0; // facet barycenter block index
  26460. var block_idx_v1 = 0; // v1 vertex block index
  26461. var block_idx_v2 = 0; // v2 vertex block index
  26462. var block_idx_v3 = 0; // v3 vertex block index
  26463. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26464. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26465. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26466. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26467. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26468. var subSq = options.subDiv.max * options.subDiv.max;
  26469. options.facetPartitioning.length = 0;
  26470. }
  26471. // reset the normals
  26472. for (index = 0; index < positions.length; index++) {
  26473. normals[index] = 0.0;
  26474. }
  26475. // Loop : 1 indice triplet = 1 facet
  26476. var nbFaces = indices.length / 3;
  26477. for (index = 0; index < nbFaces; index++) {
  26478. // get the indexes of the coordinates of each vertex of the facet
  26479. v1x = indices[index * 3] * 3;
  26480. v1y = v1x + 1;
  26481. v1z = v1x + 2;
  26482. v2x = indices[index * 3 + 1] * 3;
  26483. v2y = v2x + 1;
  26484. v2z = v2x + 2;
  26485. v3x = indices[index * 3 + 2] * 3;
  26486. v3y = v3x + 1;
  26487. v3z = v3x + 2;
  26488. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26489. p1p2y = positions[v1y] - positions[v2y];
  26490. p1p2z = positions[v1z] - positions[v2z];
  26491. p3p2x = positions[v3x] - positions[v2x];
  26492. p3p2y = positions[v3y] - positions[v2y];
  26493. p3p2z = positions[v3z] - positions[v2z];
  26494. // compute the face normal with the cross product
  26495. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26496. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26497. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26498. // normalize this normal and store it in the array facetData
  26499. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26500. length = (length === 0) ? 1.0 : length;
  26501. faceNormalx /= length;
  26502. faceNormaly /= length;
  26503. faceNormalz /= length;
  26504. if (computeFacetNormals) {
  26505. options.facetNormals[index].x = faceNormalx;
  26506. options.facetNormals[index].y = faceNormaly;
  26507. options.facetNormals[index].z = faceNormalz;
  26508. }
  26509. if (computeFacetPositions) {
  26510. // compute and the facet barycenter coordinates in the array facetPositions
  26511. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26512. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26513. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26514. }
  26515. if (computeFacetPartitioning) {
  26516. // store the facet indexes in arrays in the main facetPartitioning array :
  26517. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26518. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26519. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26520. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26521. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26522. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26523. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26524. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26525. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26526. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26527. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26528. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26529. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26530. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26531. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26532. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26533. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26534. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26535. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26536. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26537. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26538. // push each facet index in each block containing the vertex
  26539. options.facetPartitioning[block_idx_v1].push(index);
  26540. if (block_idx_v2 != block_idx_v1) {
  26541. options.facetPartitioning[block_idx_v2].push(index);
  26542. }
  26543. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26544. options.facetPartitioning[block_idx_v3].push(index);
  26545. }
  26546. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26547. options.facetPartitioning[block_idx_o].push(index);
  26548. }
  26549. }
  26550. // compute the normals anyway
  26551. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26552. normals[v1y] += faceNormaly;
  26553. normals[v1z] += faceNormalz;
  26554. normals[v2x] += faceNormalx;
  26555. normals[v2y] += faceNormaly;
  26556. normals[v2z] += faceNormalz;
  26557. normals[v3x] += faceNormalx;
  26558. normals[v3y] += faceNormaly;
  26559. normals[v3z] += faceNormalz;
  26560. }
  26561. // last normalization of each normal
  26562. for (index = 0; index < normals.length / 3; index++) {
  26563. faceNormalx = normals[index * 3];
  26564. faceNormaly = normals[index * 3 + 1];
  26565. faceNormalz = normals[index * 3 + 2];
  26566. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26567. length = (length === 0) ? 1.0 : length;
  26568. faceNormalx /= length;
  26569. faceNormaly /= length;
  26570. faceNormalz /= length;
  26571. normals[index * 3] = faceNormalx;
  26572. normals[index * 3 + 1] = faceNormaly;
  26573. normals[index * 3 + 2] = faceNormalz;
  26574. }
  26575. };
  26576. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26577. var li = indices.length;
  26578. var ln = normals.length;
  26579. var i;
  26580. var n;
  26581. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26582. switch (sideOrientation) {
  26583. case BABYLON.Mesh.FRONTSIDE:
  26584. // nothing changed
  26585. break;
  26586. case BABYLON.Mesh.BACKSIDE:
  26587. var tmp;
  26588. // indices
  26589. for (i = 0; i < li; i += 3) {
  26590. tmp = indices[i];
  26591. indices[i] = indices[i + 2];
  26592. indices[i + 2] = tmp;
  26593. }
  26594. // normals
  26595. for (n = 0; n < ln; n++) {
  26596. normals[n] = -normals[n];
  26597. }
  26598. break;
  26599. case BABYLON.Mesh.DOUBLESIDE:
  26600. // positions
  26601. var lp = positions.length;
  26602. var l = lp / 3;
  26603. for (var p = 0; p < lp; p++) {
  26604. positions[lp + p] = positions[p];
  26605. }
  26606. // indices
  26607. for (i = 0; i < li; i += 3) {
  26608. indices[i + li] = indices[i + 2] + l;
  26609. indices[i + 1 + li] = indices[i + 1] + l;
  26610. indices[i + 2 + li] = indices[i] + l;
  26611. }
  26612. // normals
  26613. for (n = 0; n < ln; n++) {
  26614. normals[ln + n] = -normals[n];
  26615. }
  26616. // uvs
  26617. var lu = uvs.length;
  26618. var u = 0;
  26619. for (u = 0; u < lu; u++) {
  26620. uvs[u + lu] = uvs[u];
  26621. }
  26622. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26623. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26624. u = 0;
  26625. for (i = 0; i < lu / 2; i++) {
  26626. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  26627. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  26628. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  26629. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  26630. u += 2;
  26631. }
  26632. break;
  26633. }
  26634. };
  26635. /**
  26636. * Creates a new VertexData from the imported parameters.
  26637. */
  26638. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26639. var vertexData = new VertexData();
  26640. // positions
  26641. var positions = parsedVertexData.positions;
  26642. if (positions) {
  26643. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26644. }
  26645. // normals
  26646. var normals = parsedVertexData.normals;
  26647. if (normals) {
  26648. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26649. }
  26650. // tangents
  26651. var tangents = parsedVertexData.tangents;
  26652. if (tangents) {
  26653. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  26654. }
  26655. // uvs
  26656. var uvs = parsedVertexData.uvs;
  26657. if (uvs) {
  26658. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26659. }
  26660. // uv2s
  26661. var uv2s = parsedVertexData.uv2s;
  26662. if (uv2s) {
  26663. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26664. }
  26665. // uv3s
  26666. var uv3s = parsedVertexData.uv3s;
  26667. if (uv3s) {
  26668. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26669. }
  26670. // uv4s
  26671. var uv4s = parsedVertexData.uv4s;
  26672. if (uv4s) {
  26673. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26674. }
  26675. // uv5s
  26676. var uv5s = parsedVertexData.uv5s;
  26677. if (uv5s) {
  26678. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26679. }
  26680. // uv6s
  26681. var uv6s = parsedVertexData.uv6s;
  26682. if (uv6s) {
  26683. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26684. }
  26685. // colors
  26686. var colors = parsedVertexData.colors;
  26687. if (colors) {
  26688. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26689. }
  26690. // matricesIndices
  26691. var matricesIndices = parsedVertexData.matricesIndices;
  26692. if (matricesIndices) {
  26693. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26694. }
  26695. // matricesWeights
  26696. var matricesWeights = parsedVertexData.matricesWeights;
  26697. if (matricesWeights) {
  26698. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26699. }
  26700. // indices
  26701. var indices = parsedVertexData.indices;
  26702. if (indices) {
  26703. vertexData.indices = indices;
  26704. }
  26705. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26706. };
  26707. return VertexData;
  26708. }());
  26709. BABYLON.VertexData = VertexData;
  26710. })(BABYLON || (BABYLON = {}));
  26711. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  26712. var BABYLON;
  26713. (function (BABYLON) {
  26714. var Geometry = (function () {
  26715. function Geometry(id, scene, vertexData, updatable, mesh) {
  26716. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26717. this._totalVertices = 0;
  26718. this._isDisposed = false;
  26719. this.id = id;
  26720. this._engine = scene.getEngine();
  26721. this._meshes = [];
  26722. this._scene = scene;
  26723. //Init vertex buffer cache
  26724. this._vertexBuffers = {};
  26725. this._indices = [];
  26726. // vertexData
  26727. if (vertexData) {
  26728. this.setAllVerticesData(vertexData, updatable);
  26729. }
  26730. else {
  26731. this._totalVertices = 0;
  26732. this._indices = [];
  26733. }
  26734. if (this._engine.getCaps().vertexArrayObject) {
  26735. this._vertexArrayObjects = {};
  26736. }
  26737. // applyToMesh
  26738. if (mesh) {
  26739. if (mesh.getClassName() === "LinesMesh") {
  26740. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  26741. this.updateExtend();
  26742. }
  26743. this.applyToMesh(mesh);
  26744. mesh.computeWorldMatrix(true);
  26745. }
  26746. }
  26747. Object.defineProperty(Geometry.prototype, "boundingBias", {
  26748. /**
  26749. * 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
  26750. * @returns The Bias Vector
  26751. */
  26752. get: function () {
  26753. return this._boundingBias;
  26754. },
  26755. set: function (value) {
  26756. if (this._boundingBias && this._boundingBias.equals(value)) {
  26757. return;
  26758. }
  26759. this._boundingBias = value.clone();
  26760. this.updateBoundingInfo(true, null);
  26761. },
  26762. enumerable: true,
  26763. configurable: true
  26764. });
  26765. Object.defineProperty(Geometry.prototype, "extend", {
  26766. get: function () {
  26767. return this._extend;
  26768. },
  26769. enumerable: true,
  26770. configurable: true
  26771. });
  26772. Geometry.prototype.getScene = function () {
  26773. return this._scene;
  26774. };
  26775. Geometry.prototype.getEngine = function () {
  26776. return this._engine;
  26777. };
  26778. Geometry.prototype.isReady = function () {
  26779. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26780. };
  26781. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  26782. get: function () {
  26783. for (var index = 0; index < this._meshes.length; index++) {
  26784. if (!this._meshes[index].doNotSerialize) {
  26785. return false;
  26786. }
  26787. }
  26788. return true;
  26789. },
  26790. enumerable: true,
  26791. configurable: true
  26792. });
  26793. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26794. vertexData.applyToGeometry(this, updatable);
  26795. this.notifyUpdate();
  26796. };
  26797. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26798. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26799. this.setVerticesBuffer(buffer);
  26800. };
  26801. Geometry.prototype.removeVerticesData = function (kind) {
  26802. if (this._vertexBuffers[kind]) {
  26803. this._vertexBuffers[kind].dispose();
  26804. delete this._vertexBuffers[kind];
  26805. }
  26806. };
  26807. Geometry.prototype.setVerticesBuffer = function (buffer) {
  26808. var kind = buffer.getKind();
  26809. if (this._vertexBuffers[kind]) {
  26810. this._vertexBuffers[kind].dispose();
  26811. }
  26812. this._vertexBuffers[kind] = buffer;
  26813. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26814. var data = buffer.getData();
  26815. var stride = buffer.getStrideSize();
  26816. this._totalVertices = data.length / stride;
  26817. this.updateExtend(data, stride);
  26818. this._resetPointsArrayCache();
  26819. var meshes = this._meshes;
  26820. var numOfMeshes = meshes.length;
  26821. for (var index = 0; index < numOfMeshes; index++) {
  26822. var mesh = meshes[index];
  26823. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26824. mesh._createGlobalSubMesh();
  26825. mesh.computeWorldMatrix(true);
  26826. }
  26827. }
  26828. this.notifyUpdate(kind);
  26829. if (this._vertexArrayObjects) {
  26830. this._disposeVertexArrayObjects();
  26831. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  26832. }
  26833. };
  26834. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26835. var vertexBuffer = this.getVertexBuffer(kind);
  26836. if (!vertexBuffer) {
  26837. return;
  26838. }
  26839. vertexBuffer.updateDirectly(data, offset);
  26840. this.notifyUpdate(kind);
  26841. };
  26842. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26843. var vertexBuffer = this.getVertexBuffer(kind);
  26844. if (!vertexBuffer) {
  26845. return;
  26846. }
  26847. vertexBuffer.update(data);
  26848. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26849. var stride = vertexBuffer.getStrideSize();
  26850. this._totalVertices = data.length / stride;
  26851. this.updateBoundingInfo(updateExtends, data);
  26852. }
  26853. this.notifyUpdate(kind);
  26854. };
  26855. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  26856. if (updateExtends) {
  26857. this.updateExtend(data);
  26858. }
  26859. var meshes = this._meshes;
  26860. var numOfMeshes = meshes.length;
  26861. this._resetPointsArrayCache();
  26862. for (var index = 0; index < numOfMeshes; index++) {
  26863. var mesh = meshes[index];
  26864. if (updateExtends) {
  26865. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26866. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26867. var subMesh = mesh.subMeshes[subIndex];
  26868. subMesh.refreshBoundingInfo();
  26869. }
  26870. }
  26871. }
  26872. };
  26873. Geometry.prototype._bind = function (effect, indexToBind) {
  26874. if (indexToBind === void 0) { indexToBind = undefined; }
  26875. if (indexToBind === undefined) {
  26876. indexToBind = this._indexBuffer;
  26877. }
  26878. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  26879. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  26880. return;
  26881. }
  26882. // Using VAO
  26883. if (!this._vertexArrayObjects[effect.key]) {
  26884. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  26885. }
  26886. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  26887. };
  26888. Geometry.prototype.getTotalVertices = function () {
  26889. if (!this.isReady()) {
  26890. return 0;
  26891. }
  26892. return this._totalVertices;
  26893. };
  26894. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26895. var vertexBuffer = this.getVertexBuffer(kind);
  26896. if (!vertexBuffer) {
  26897. return null;
  26898. }
  26899. var orig = vertexBuffer.getData();
  26900. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  26901. return orig;
  26902. }
  26903. else {
  26904. var len = orig.length;
  26905. var copy = [];
  26906. for (var i = 0; i < len; i++) {
  26907. copy.push(orig[i]);
  26908. }
  26909. return copy;
  26910. }
  26911. };
  26912. Geometry.prototype.getVertexBuffer = function (kind) {
  26913. if (!this.isReady()) {
  26914. return null;
  26915. }
  26916. return this._vertexBuffers[kind];
  26917. };
  26918. Geometry.prototype.getVertexBuffers = function () {
  26919. if (!this.isReady()) {
  26920. return null;
  26921. }
  26922. return this._vertexBuffers;
  26923. };
  26924. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26925. if (!this._vertexBuffers) {
  26926. if (this._delayInfo) {
  26927. return this._delayInfo.indexOf(kind) !== -1;
  26928. }
  26929. return false;
  26930. }
  26931. return this._vertexBuffers[kind] !== undefined;
  26932. };
  26933. Geometry.prototype.getVerticesDataKinds = function () {
  26934. var result = [];
  26935. var kind;
  26936. if (!this._vertexBuffers && this._delayInfo) {
  26937. for (kind in this._delayInfo) {
  26938. result.push(kind);
  26939. }
  26940. }
  26941. else {
  26942. for (kind in this._vertexBuffers) {
  26943. result.push(kind);
  26944. }
  26945. }
  26946. return result;
  26947. };
  26948. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26949. if (this._indexBuffer) {
  26950. this._engine._releaseBuffer(this._indexBuffer);
  26951. }
  26952. this._disposeVertexArrayObjects();
  26953. this._indices = indices;
  26954. if (this._meshes.length !== 0 && this._indices) {
  26955. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26956. }
  26957. if (totalVertices !== undefined) {
  26958. this._totalVertices = totalVertices;
  26959. }
  26960. var meshes = this._meshes;
  26961. var numOfMeshes = meshes.length;
  26962. for (var index = 0; index < numOfMeshes; index++) {
  26963. meshes[index]._createGlobalSubMesh();
  26964. }
  26965. this.notifyUpdate();
  26966. };
  26967. Geometry.prototype.getTotalIndices = function () {
  26968. if (!this.isReady()) {
  26969. return 0;
  26970. }
  26971. return this._indices.length;
  26972. };
  26973. Geometry.prototype.getIndices = function (copyWhenShared) {
  26974. if (!this.isReady()) {
  26975. return null;
  26976. }
  26977. var orig = this._indices;
  26978. if (!copyWhenShared || this._meshes.length === 1) {
  26979. return orig;
  26980. }
  26981. else {
  26982. var len = orig.length;
  26983. var copy = [];
  26984. for (var i = 0; i < len; i++) {
  26985. copy.push(orig[i]);
  26986. }
  26987. return copy;
  26988. }
  26989. };
  26990. Geometry.prototype.getIndexBuffer = function () {
  26991. if (!this.isReady()) {
  26992. return null;
  26993. }
  26994. return this._indexBuffer;
  26995. };
  26996. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  26997. if (!effect || !this._vertexArrayObjects) {
  26998. return;
  26999. }
  27000. if (this._vertexArrayObjects[effect.key]) {
  27001. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27002. delete this._vertexArrayObjects[effect.key];
  27003. }
  27004. };
  27005. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27006. var meshes = this._meshes;
  27007. var index = meshes.indexOf(mesh);
  27008. if (index === -1) {
  27009. return;
  27010. }
  27011. meshes.splice(index, 1);
  27012. mesh._geometry = null;
  27013. if (meshes.length === 0 && shouldDispose) {
  27014. this.dispose();
  27015. }
  27016. };
  27017. Geometry.prototype.applyToMesh = function (mesh) {
  27018. if (mesh._geometry === this) {
  27019. return;
  27020. }
  27021. var previousGeometry = mesh._geometry;
  27022. if (previousGeometry) {
  27023. previousGeometry.releaseForMesh(mesh);
  27024. }
  27025. var meshes = this._meshes;
  27026. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27027. mesh._geometry = this;
  27028. this._scene.pushGeometry(this);
  27029. meshes.push(mesh);
  27030. if (this.isReady()) {
  27031. this._applyToMesh(mesh);
  27032. }
  27033. else {
  27034. mesh._boundingInfo = this._boundingInfo;
  27035. }
  27036. };
  27037. Geometry.prototype.updateExtend = function (data, stride) {
  27038. if (data === void 0) { data = null; }
  27039. if (!data) {
  27040. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27041. }
  27042. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27043. };
  27044. Geometry.prototype._applyToMesh = function (mesh) {
  27045. var numOfMeshes = this._meshes.length;
  27046. // vertexBuffers
  27047. for (var kind in this._vertexBuffers) {
  27048. if (numOfMeshes === 1) {
  27049. this._vertexBuffers[kind].create();
  27050. }
  27051. var buffer = this._vertexBuffers[kind].getBuffer();
  27052. if (buffer)
  27053. buffer.references = numOfMeshes;
  27054. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27055. if (!this._extend) {
  27056. this.updateExtend(this._vertexBuffers[kind].getData());
  27057. }
  27058. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27059. mesh._createGlobalSubMesh();
  27060. //bounding info was just created again, world matrix should be applied again.
  27061. mesh._updateBoundingInfo();
  27062. }
  27063. }
  27064. // indexBuffer
  27065. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27066. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27067. }
  27068. if (this._indexBuffer) {
  27069. this._indexBuffer.references = numOfMeshes;
  27070. }
  27071. };
  27072. Geometry.prototype.notifyUpdate = function (kind) {
  27073. if (this.onGeometryUpdated) {
  27074. this.onGeometryUpdated(this, kind);
  27075. }
  27076. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27077. var mesh = _a[_i];
  27078. mesh._markSubMeshesAsAttributesDirty();
  27079. }
  27080. };
  27081. Geometry.prototype.load = function (scene, onLoaded) {
  27082. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27083. return;
  27084. }
  27085. if (this.isReady()) {
  27086. if (onLoaded) {
  27087. onLoaded();
  27088. }
  27089. return;
  27090. }
  27091. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27092. this._queueLoad(scene, onLoaded);
  27093. };
  27094. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27095. var _this = this;
  27096. scene._addPendingData(this);
  27097. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27098. _this._delayLoadingFunction(JSON.parse(data), _this);
  27099. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27100. _this._delayInfo = [];
  27101. scene._removePendingData(_this);
  27102. var meshes = _this._meshes;
  27103. var numOfMeshes = meshes.length;
  27104. for (var index = 0; index < numOfMeshes; index++) {
  27105. _this._applyToMesh(meshes[index]);
  27106. }
  27107. if (onLoaded) {
  27108. onLoaded();
  27109. }
  27110. }, function () { }, scene.database);
  27111. };
  27112. /**
  27113. * Invert the geometry to move from a right handed system to a left handed one.
  27114. */
  27115. Geometry.prototype.toLeftHanded = function () {
  27116. // Flip faces
  27117. var tIndices = this.getIndices(false);
  27118. if (tIndices != null && tIndices.length > 0) {
  27119. for (var i = 0; i < tIndices.length; i += 3) {
  27120. var tTemp = tIndices[i + 0];
  27121. tIndices[i + 0] = tIndices[i + 2];
  27122. tIndices[i + 2] = tTemp;
  27123. }
  27124. this.setIndices(tIndices);
  27125. }
  27126. // Negate position.z
  27127. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27128. if (tPositions != null && tPositions.length > 0) {
  27129. for (var i = 0; i < tPositions.length; i += 3) {
  27130. tPositions[i + 2] = -tPositions[i + 2];
  27131. }
  27132. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27133. }
  27134. // Negate normal.z
  27135. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27136. if (tNormals != null && tNormals.length > 0) {
  27137. for (var i = 0; i < tNormals.length; i += 3) {
  27138. tNormals[i + 2] = -tNormals[i + 2];
  27139. }
  27140. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27141. }
  27142. };
  27143. // Cache
  27144. Geometry.prototype._resetPointsArrayCache = function () {
  27145. this._positions = null;
  27146. };
  27147. Geometry.prototype._generatePointsArray = function () {
  27148. if (this._positions)
  27149. return true;
  27150. this._positions = [];
  27151. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27152. if (!data) {
  27153. return false;
  27154. }
  27155. for (var index = 0; index < data.length; index += 3) {
  27156. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27157. }
  27158. return true;
  27159. };
  27160. Geometry.prototype.isDisposed = function () {
  27161. return this._isDisposed;
  27162. };
  27163. Geometry.prototype._disposeVertexArrayObjects = function () {
  27164. if (this._vertexArrayObjects) {
  27165. for (var kind in this._vertexArrayObjects) {
  27166. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27167. }
  27168. this._vertexArrayObjects = {};
  27169. }
  27170. };
  27171. Geometry.prototype.dispose = function () {
  27172. var meshes = this._meshes;
  27173. var numOfMeshes = meshes.length;
  27174. var index;
  27175. for (index = 0; index < numOfMeshes; index++) {
  27176. this.releaseForMesh(meshes[index]);
  27177. }
  27178. this._meshes = [];
  27179. this._disposeVertexArrayObjects();
  27180. for (var kind in this._vertexBuffers) {
  27181. this._vertexBuffers[kind].dispose();
  27182. }
  27183. this._vertexBuffers = {};
  27184. this._totalVertices = 0;
  27185. if (this._indexBuffer) {
  27186. this._engine._releaseBuffer(this._indexBuffer);
  27187. }
  27188. this._indexBuffer = null;
  27189. this._indices = [];
  27190. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27191. this.delayLoadingFile = null;
  27192. this._delayLoadingFunction = null;
  27193. this._delayInfo = [];
  27194. this._boundingInfo = null;
  27195. this._scene.removeGeometry(this);
  27196. this._isDisposed = true;
  27197. };
  27198. Geometry.prototype.copy = function (id) {
  27199. var vertexData = new BABYLON.VertexData();
  27200. vertexData.indices = [];
  27201. var indices = this.getIndices();
  27202. for (var index = 0; index < indices.length; index++) {
  27203. vertexData.indices.push(indices[index]);
  27204. }
  27205. var updatable = false;
  27206. var stopChecking = false;
  27207. var kind;
  27208. for (kind in this._vertexBuffers) {
  27209. // using slice() to make a copy of the array and not just reference it
  27210. var data = this.getVerticesData(kind);
  27211. if (data instanceof Float32Array) {
  27212. vertexData.set(new Float32Array(data), kind);
  27213. }
  27214. else {
  27215. vertexData.set(data.slice(0), kind);
  27216. }
  27217. if (!stopChecking) {
  27218. updatable = this.getVertexBuffer(kind).isUpdatable();
  27219. stopChecking = !updatable;
  27220. }
  27221. }
  27222. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27223. geometry.delayLoadState = this.delayLoadState;
  27224. geometry.delayLoadingFile = this.delayLoadingFile;
  27225. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27226. for (kind in this._delayInfo) {
  27227. geometry._delayInfo = geometry._delayInfo || [];
  27228. geometry._delayInfo.push(kind);
  27229. }
  27230. // Bounding info
  27231. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27232. return geometry;
  27233. };
  27234. Geometry.prototype.serialize = function () {
  27235. var serializationObject = {};
  27236. serializationObject.id = this.id;
  27237. if (BABYLON.Tags.HasTags(this)) {
  27238. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27239. }
  27240. return serializationObject;
  27241. };
  27242. Geometry.prototype.toNumberArray = function (origin) {
  27243. if (Array.isArray(origin)) {
  27244. return origin;
  27245. }
  27246. else {
  27247. return Array.prototype.slice.call(origin);
  27248. }
  27249. };
  27250. Geometry.prototype.serializeVerticeData = function () {
  27251. var serializationObject = this.serialize();
  27252. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27253. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27254. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27255. serializationObject.positions._updatable = true;
  27256. }
  27257. }
  27258. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27259. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27260. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27261. serializationObject.normals._updatable = true;
  27262. }
  27263. }
  27264. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27265. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27266. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27267. serializationObject.uvs._updatable = true;
  27268. }
  27269. }
  27270. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27271. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27272. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27273. serializationObject.uv2s._updatable = true;
  27274. }
  27275. }
  27276. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27277. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27278. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27279. serializationObject.uv3s._updatable = true;
  27280. }
  27281. }
  27282. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27283. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27284. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27285. serializationObject.uv4s._updatable = true;
  27286. }
  27287. }
  27288. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27289. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27290. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27291. serializationObject.uv5s._updatable = true;
  27292. }
  27293. }
  27294. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27295. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27296. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27297. serializationObject.uv6s._updatable = true;
  27298. }
  27299. }
  27300. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27301. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27302. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27303. serializationObject.colors._updatable = true;
  27304. }
  27305. }
  27306. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27307. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27308. serializationObject.matricesIndices._isExpanded = true;
  27309. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27310. serializationObject.matricesIndices._updatable = true;
  27311. }
  27312. }
  27313. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27314. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27315. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27316. serializationObject.matricesWeights._updatable = true;
  27317. }
  27318. }
  27319. serializationObject.indices = this.toNumberArray(this.getIndices());
  27320. return serializationObject;
  27321. };
  27322. // Statics
  27323. Geometry.ExtractFromMesh = function (mesh, id) {
  27324. var geometry = mesh._geometry;
  27325. if (!geometry) {
  27326. return null;
  27327. }
  27328. return geometry.copy(id);
  27329. };
  27330. /**
  27331. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27332. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27333. * Be aware Math.random() could cause collisions, but:
  27334. * "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"
  27335. */
  27336. Geometry.RandomId = function () {
  27337. return BABYLON.Tools.RandomId();
  27338. };
  27339. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27340. var scene = mesh.getScene();
  27341. // Geometry
  27342. var geometryId = parsedGeometry.geometryId;
  27343. if (geometryId) {
  27344. var geometry = scene.getGeometryByID(geometryId);
  27345. if (geometry) {
  27346. geometry.applyToMesh(mesh);
  27347. }
  27348. }
  27349. else if (parsedGeometry instanceof ArrayBuffer) {
  27350. var binaryInfo = mesh._binaryInfo;
  27351. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27352. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27353. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27354. }
  27355. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27356. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27357. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27358. }
  27359. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27360. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27361. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27362. }
  27363. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27364. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27365. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27366. }
  27367. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27368. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27369. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27370. }
  27371. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27372. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27373. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27374. }
  27375. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27376. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27377. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27378. }
  27379. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27380. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27381. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27382. }
  27383. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27384. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27385. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27386. }
  27387. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27388. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27389. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27390. }
  27391. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27392. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27393. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27394. }
  27395. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27396. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27397. mesh.setIndices(indicesData);
  27398. }
  27399. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27400. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27401. mesh.subMeshes = [];
  27402. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27403. var materialIndex = subMeshesData[(i * 5) + 0];
  27404. var verticesStart = subMeshesData[(i * 5) + 1];
  27405. var verticesCount = subMeshesData[(i * 5) + 2];
  27406. var indexStart = subMeshesData[(i * 5) + 3];
  27407. var indexCount = subMeshesData[(i * 5) + 4];
  27408. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27409. }
  27410. }
  27411. }
  27412. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27413. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27414. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27415. if (parsedGeometry.uvs) {
  27416. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27417. }
  27418. if (parsedGeometry.uvs2) {
  27419. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27420. }
  27421. if (parsedGeometry.uvs3) {
  27422. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27423. }
  27424. if (parsedGeometry.uvs4) {
  27425. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27426. }
  27427. if (parsedGeometry.uvs5) {
  27428. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27429. }
  27430. if (parsedGeometry.uvs6) {
  27431. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27432. }
  27433. if (parsedGeometry.colors) {
  27434. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27435. }
  27436. if (parsedGeometry.matricesIndices) {
  27437. if (!parsedGeometry.matricesIndices._isExpanded) {
  27438. var floatIndices = [];
  27439. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27440. var matricesIndex = parsedGeometry.matricesIndices[i];
  27441. floatIndices.push(matricesIndex & 0x000000FF);
  27442. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27443. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27444. floatIndices.push(matricesIndex >> 24);
  27445. }
  27446. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27447. }
  27448. else {
  27449. delete parsedGeometry.matricesIndices._isExpanded;
  27450. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27451. }
  27452. }
  27453. if (parsedGeometry.matricesIndicesExtra) {
  27454. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27455. var floatIndices = [];
  27456. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27457. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27458. floatIndices.push(matricesIndex & 0x000000FF);
  27459. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27460. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27461. floatIndices.push(matricesIndex >> 24);
  27462. }
  27463. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27464. }
  27465. else {
  27466. delete parsedGeometry.matricesIndices._isExpanded;
  27467. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27468. }
  27469. }
  27470. if (parsedGeometry.matricesWeights) {
  27471. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27472. }
  27473. if (parsedGeometry.matricesWeightsExtra) {
  27474. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27475. }
  27476. mesh.setIndices(parsedGeometry.indices);
  27477. }
  27478. // SubMeshes
  27479. if (parsedGeometry.subMeshes) {
  27480. mesh.subMeshes = [];
  27481. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27482. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27483. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27484. }
  27485. }
  27486. // Flat shading
  27487. if (mesh._shouldGenerateFlatShading) {
  27488. mesh.convertToFlatShadedMesh();
  27489. delete mesh._shouldGenerateFlatShading;
  27490. }
  27491. // Update
  27492. mesh.computeWorldMatrix(true);
  27493. // Octree
  27494. if (scene['_selectionOctree']) {
  27495. scene['_selectionOctree'].addMesh(mesh);
  27496. }
  27497. };
  27498. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27499. if (scene.getGeometryByID(parsedVertexData.id)) {
  27500. return null; // null since geometry could be something else than a box...
  27501. }
  27502. var geometry = new Geometry(parsedVertexData.id, scene);
  27503. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27504. if (parsedVertexData.delayLoadingFile) {
  27505. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27506. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27507. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27508. geometry._delayInfo = [];
  27509. if (parsedVertexData.hasUVs) {
  27510. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27511. }
  27512. if (parsedVertexData.hasUVs2) {
  27513. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27514. }
  27515. if (parsedVertexData.hasUVs3) {
  27516. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27517. }
  27518. if (parsedVertexData.hasUVs4) {
  27519. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27520. }
  27521. if (parsedVertexData.hasUVs5) {
  27522. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27523. }
  27524. if (parsedVertexData.hasUVs6) {
  27525. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27526. }
  27527. if (parsedVertexData.hasColors) {
  27528. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27529. }
  27530. if (parsedVertexData.hasMatricesIndices) {
  27531. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27532. }
  27533. if (parsedVertexData.hasMatricesWeights) {
  27534. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27535. }
  27536. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27537. }
  27538. else {
  27539. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27540. }
  27541. scene.pushGeometry(geometry, true);
  27542. return geometry;
  27543. };
  27544. return Geometry;
  27545. }());
  27546. BABYLON.Geometry = Geometry;
  27547. /////// Primitives //////////////////////////////////////////////
  27548. (function (Geometry) {
  27549. var Primitives;
  27550. (function (Primitives) {
  27551. /// Abstract class
  27552. var _Primitive = (function (_super) {
  27553. __extends(_Primitive, _super);
  27554. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27555. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27556. _this._canBeRegenerated = _canBeRegenerated;
  27557. _this._beingRegenerated = true;
  27558. _this.regenerate();
  27559. _this._beingRegenerated = false;
  27560. return _this;
  27561. }
  27562. _Primitive.prototype.canBeRegenerated = function () {
  27563. return this._canBeRegenerated;
  27564. };
  27565. _Primitive.prototype.regenerate = function () {
  27566. if (!this._canBeRegenerated) {
  27567. return;
  27568. }
  27569. this._beingRegenerated = true;
  27570. this.setAllVerticesData(this._regenerateVertexData(), false);
  27571. this._beingRegenerated = false;
  27572. };
  27573. _Primitive.prototype.asNewGeometry = function (id) {
  27574. return _super.prototype.copy.call(this, id);
  27575. };
  27576. // overrides
  27577. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27578. if (!this._beingRegenerated) {
  27579. return;
  27580. }
  27581. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27582. };
  27583. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27584. if (!this._beingRegenerated) {
  27585. return;
  27586. }
  27587. _super.prototype.setVerticesData.call(this, kind, data, false);
  27588. };
  27589. // to override
  27590. // protected
  27591. _Primitive.prototype._regenerateVertexData = function () {
  27592. throw new Error("Abstract method");
  27593. };
  27594. _Primitive.prototype.copy = function (id) {
  27595. throw new Error("Must be overriden in sub-classes.");
  27596. };
  27597. _Primitive.prototype.serialize = function () {
  27598. var serializationObject = _super.prototype.serialize.call(this);
  27599. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27600. return serializationObject;
  27601. };
  27602. return _Primitive;
  27603. }(Geometry));
  27604. Primitives._Primitive = _Primitive;
  27605. var Ribbon = (function (_super) {
  27606. __extends(Ribbon, _super);
  27607. // Members
  27608. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27609. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27610. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27611. _this.pathArray = pathArray;
  27612. _this.closeArray = closeArray;
  27613. _this.closePath = closePath;
  27614. _this.offset = offset;
  27615. _this.side = side;
  27616. return _this;
  27617. }
  27618. Ribbon.prototype._regenerateVertexData = function () {
  27619. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27620. };
  27621. Ribbon.prototype.copy = function (id) {
  27622. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27623. };
  27624. return Ribbon;
  27625. }(_Primitive));
  27626. Primitives.Ribbon = Ribbon;
  27627. var Box = (function (_super) {
  27628. __extends(Box, _super);
  27629. // Members
  27630. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27631. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27632. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27633. _this.size = size;
  27634. _this.side = side;
  27635. return _this;
  27636. }
  27637. Box.prototype._regenerateVertexData = function () {
  27638. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27639. };
  27640. Box.prototype.copy = function (id) {
  27641. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27642. };
  27643. Box.prototype.serialize = function () {
  27644. var serializationObject = _super.prototype.serialize.call(this);
  27645. serializationObject.size = this.size;
  27646. return serializationObject;
  27647. };
  27648. Box.Parse = function (parsedBox, scene) {
  27649. if (scene.getGeometryByID(parsedBox.id)) {
  27650. return null; // null since geometry could be something else than a box...
  27651. }
  27652. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27653. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27654. scene.pushGeometry(box, true);
  27655. return box;
  27656. };
  27657. return Box;
  27658. }(_Primitive));
  27659. Primitives.Box = Box;
  27660. var Sphere = (function (_super) {
  27661. __extends(Sphere, _super);
  27662. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27663. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27664. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27665. _this.segments = segments;
  27666. _this.diameter = diameter;
  27667. _this.side = side;
  27668. return _this;
  27669. }
  27670. Sphere.prototype._regenerateVertexData = function () {
  27671. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27672. };
  27673. Sphere.prototype.copy = function (id) {
  27674. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27675. };
  27676. Sphere.prototype.serialize = function () {
  27677. var serializationObject = _super.prototype.serialize.call(this);
  27678. serializationObject.segments = this.segments;
  27679. serializationObject.diameter = this.diameter;
  27680. return serializationObject;
  27681. };
  27682. Sphere.Parse = function (parsedSphere, scene) {
  27683. if (scene.getGeometryByID(parsedSphere.id)) {
  27684. return null; // null since geometry could be something else than a sphere...
  27685. }
  27686. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27687. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27688. scene.pushGeometry(sphere, true);
  27689. return sphere;
  27690. };
  27691. return Sphere;
  27692. }(_Primitive));
  27693. Primitives.Sphere = Sphere;
  27694. var Disc = (function (_super) {
  27695. __extends(Disc, _super);
  27696. // Members
  27697. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27698. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27699. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27700. _this.radius = radius;
  27701. _this.tessellation = tessellation;
  27702. _this.side = side;
  27703. return _this;
  27704. }
  27705. Disc.prototype._regenerateVertexData = function () {
  27706. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27707. };
  27708. Disc.prototype.copy = function (id) {
  27709. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27710. };
  27711. return Disc;
  27712. }(_Primitive));
  27713. Primitives.Disc = Disc;
  27714. var Cylinder = (function (_super) {
  27715. __extends(Cylinder, _super);
  27716. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27717. if (subdivisions === void 0) { subdivisions = 1; }
  27718. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27719. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27720. _this.height = height;
  27721. _this.diameterTop = diameterTop;
  27722. _this.diameterBottom = diameterBottom;
  27723. _this.tessellation = tessellation;
  27724. _this.subdivisions = subdivisions;
  27725. _this.side = side;
  27726. return _this;
  27727. }
  27728. Cylinder.prototype._regenerateVertexData = function () {
  27729. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27730. };
  27731. Cylinder.prototype.copy = function (id) {
  27732. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27733. };
  27734. Cylinder.prototype.serialize = function () {
  27735. var serializationObject = _super.prototype.serialize.call(this);
  27736. serializationObject.height = this.height;
  27737. serializationObject.diameterTop = this.diameterTop;
  27738. serializationObject.diameterBottom = this.diameterBottom;
  27739. serializationObject.tessellation = this.tessellation;
  27740. return serializationObject;
  27741. };
  27742. Cylinder.Parse = function (parsedCylinder, scene) {
  27743. if (scene.getGeometryByID(parsedCylinder.id)) {
  27744. return null; // null since geometry could be something else than a cylinder...
  27745. }
  27746. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27747. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27748. scene.pushGeometry(cylinder, true);
  27749. return cylinder;
  27750. };
  27751. return Cylinder;
  27752. }(_Primitive));
  27753. Primitives.Cylinder = Cylinder;
  27754. var Torus = (function (_super) {
  27755. __extends(Torus, _super);
  27756. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27757. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27758. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27759. _this.diameter = diameter;
  27760. _this.thickness = thickness;
  27761. _this.tessellation = tessellation;
  27762. _this.side = side;
  27763. return _this;
  27764. }
  27765. Torus.prototype._regenerateVertexData = function () {
  27766. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27767. };
  27768. Torus.prototype.copy = function (id) {
  27769. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27770. };
  27771. Torus.prototype.serialize = function () {
  27772. var serializationObject = _super.prototype.serialize.call(this);
  27773. serializationObject.diameter = this.diameter;
  27774. serializationObject.thickness = this.thickness;
  27775. serializationObject.tessellation = this.tessellation;
  27776. return serializationObject;
  27777. };
  27778. Torus.Parse = function (parsedTorus, scene) {
  27779. if (scene.getGeometryByID(parsedTorus.id)) {
  27780. return null; // null since geometry could be something else than a torus...
  27781. }
  27782. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27783. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27784. scene.pushGeometry(torus, true);
  27785. return torus;
  27786. };
  27787. return Torus;
  27788. }(_Primitive));
  27789. Primitives.Torus = Torus;
  27790. var Ground = (function (_super) {
  27791. __extends(Ground, _super);
  27792. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27793. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27794. _this.width = width;
  27795. _this.height = height;
  27796. _this.subdivisions = subdivisions;
  27797. return _this;
  27798. }
  27799. Ground.prototype._regenerateVertexData = function () {
  27800. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27801. };
  27802. Ground.prototype.copy = function (id) {
  27803. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27804. };
  27805. Ground.prototype.serialize = function () {
  27806. var serializationObject = _super.prototype.serialize.call(this);
  27807. serializationObject.width = this.width;
  27808. serializationObject.height = this.height;
  27809. serializationObject.subdivisions = this.subdivisions;
  27810. return serializationObject;
  27811. };
  27812. Ground.Parse = function (parsedGround, scene) {
  27813. if (scene.getGeometryByID(parsedGround.id)) {
  27814. return null; // null since geometry could be something else than a ground...
  27815. }
  27816. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27817. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27818. scene.pushGeometry(ground, true);
  27819. return ground;
  27820. };
  27821. return Ground;
  27822. }(_Primitive));
  27823. Primitives.Ground = Ground;
  27824. var TiledGround = (function (_super) {
  27825. __extends(TiledGround, _super);
  27826. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27827. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27828. _this.xmin = xmin;
  27829. _this.zmin = zmin;
  27830. _this.xmax = xmax;
  27831. _this.zmax = zmax;
  27832. _this.subdivisions = subdivisions;
  27833. _this.precision = precision;
  27834. return _this;
  27835. }
  27836. TiledGround.prototype._regenerateVertexData = function () {
  27837. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27838. };
  27839. TiledGround.prototype.copy = function (id) {
  27840. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27841. };
  27842. return TiledGround;
  27843. }(_Primitive));
  27844. Primitives.TiledGround = TiledGround;
  27845. var Plane = (function (_super) {
  27846. __extends(Plane, _super);
  27847. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27848. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27849. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27850. _this.size = size;
  27851. _this.side = side;
  27852. return _this;
  27853. }
  27854. Plane.prototype._regenerateVertexData = function () {
  27855. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27856. };
  27857. Plane.prototype.copy = function (id) {
  27858. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27859. };
  27860. Plane.prototype.serialize = function () {
  27861. var serializationObject = _super.prototype.serialize.call(this);
  27862. serializationObject.size = this.size;
  27863. return serializationObject;
  27864. };
  27865. Plane.Parse = function (parsedPlane, scene) {
  27866. if (scene.getGeometryByID(parsedPlane.id)) {
  27867. return null; // null since geometry could be something else than a ground...
  27868. }
  27869. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  27870. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27871. scene.pushGeometry(plane, true);
  27872. return plane;
  27873. };
  27874. return Plane;
  27875. }(_Primitive));
  27876. Primitives.Plane = Plane;
  27877. var TorusKnot = (function (_super) {
  27878. __extends(TorusKnot, _super);
  27879. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27880. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27881. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27882. _this.radius = radius;
  27883. _this.tube = tube;
  27884. _this.radialSegments = radialSegments;
  27885. _this.tubularSegments = tubularSegments;
  27886. _this.p = p;
  27887. _this.q = q;
  27888. _this.side = side;
  27889. return _this;
  27890. }
  27891. TorusKnot.prototype._regenerateVertexData = function () {
  27892. 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 });
  27893. };
  27894. TorusKnot.prototype.copy = function (id) {
  27895. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27896. };
  27897. TorusKnot.prototype.serialize = function () {
  27898. var serializationObject = _super.prototype.serialize.call(this);
  27899. serializationObject.radius = this.radius;
  27900. serializationObject.tube = this.tube;
  27901. serializationObject.radialSegments = this.radialSegments;
  27902. serializationObject.tubularSegments = this.tubularSegments;
  27903. serializationObject.p = this.p;
  27904. serializationObject.q = this.q;
  27905. return serializationObject;
  27906. };
  27907. ;
  27908. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  27909. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  27910. return null; // null since geometry could be something else than a ground...
  27911. }
  27912. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  27913. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  27914. scene.pushGeometry(torusKnot, true);
  27915. return torusKnot;
  27916. };
  27917. return TorusKnot;
  27918. }(_Primitive));
  27919. Primitives.TorusKnot = TorusKnot;
  27920. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27921. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27922. })(BABYLON || (BABYLON = {}));
  27923. //# sourceMappingURL=babylon.geometry.js.map
  27924. var BABYLON;
  27925. (function (BABYLON) {
  27926. var PostProcessManager = (function () {
  27927. function PostProcessManager(scene) {
  27928. this._vertexBuffers = {};
  27929. this._scene = scene;
  27930. }
  27931. PostProcessManager.prototype._prepareBuffers = function () {
  27932. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  27933. return;
  27934. }
  27935. // VBO
  27936. var vertices = [];
  27937. vertices.push(1, 1);
  27938. vertices.push(-1, 1);
  27939. vertices.push(-1, -1);
  27940. vertices.push(1, -1);
  27941. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27942. // Indices
  27943. var indices = [];
  27944. indices.push(0);
  27945. indices.push(1);
  27946. indices.push(2);
  27947. indices.push(0);
  27948. indices.push(2);
  27949. indices.push(3);
  27950. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  27951. };
  27952. // Methods
  27953. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  27954. var postProcesses = this._scene.activeCamera._postProcesses;
  27955. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27956. return false;
  27957. }
  27958. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  27959. return true;
  27960. };
  27961. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  27962. var engine = this._scene.getEngine();
  27963. for (var index = 0; index < postProcesses.length; index++) {
  27964. if (index < postProcesses.length - 1) {
  27965. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27966. }
  27967. else {
  27968. if (targetTexture) {
  27969. engine.bindFramebuffer(targetTexture);
  27970. }
  27971. else {
  27972. engine.restoreDefaultFramebuffer();
  27973. }
  27974. }
  27975. var pp = postProcesses[index];
  27976. var effect = pp.apply();
  27977. if (effect) {
  27978. pp.onBeforeRenderObservable.notifyObservers(effect);
  27979. // VBOs
  27980. this._prepareBuffers();
  27981. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27982. // Draw order
  27983. engine.draw(true, 0, 6);
  27984. pp.onAfterRenderObservable.notifyObservers(effect);
  27985. }
  27986. }
  27987. // Restore depth buffer
  27988. engine.setDepthBuffer(true);
  27989. engine.setDepthWrite(true);
  27990. };
  27991. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  27992. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  27993. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27994. return;
  27995. }
  27996. var engine = this._scene.getEngine();
  27997. for (var index = 0, len = postProcesses.length; index < len; index++) {
  27998. if (index < len - 1) {
  27999. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28000. }
  28001. else {
  28002. if (targetTexture) {
  28003. engine.bindFramebuffer(targetTexture, faceIndex);
  28004. }
  28005. else {
  28006. engine.restoreDefaultFramebuffer();
  28007. }
  28008. }
  28009. if (doNotPresent) {
  28010. break;
  28011. }
  28012. var pp = postProcesses[index];
  28013. var effect = pp.apply();
  28014. if (effect) {
  28015. pp.onBeforeRenderObservable.notifyObservers(effect);
  28016. // VBOs
  28017. this._prepareBuffers();
  28018. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28019. // Draw order
  28020. engine.draw(true, 0, 6);
  28021. pp.onAfterRenderObservable.notifyObservers(effect);
  28022. }
  28023. }
  28024. // Restore states
  28025. engine.setDepthBuffer(true);
  28026. engine.setDepthWrite(true);
  28027. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28028. };
  28029. PostProcessManager.prototype.dispose = function () {
  28030. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28031. if (buffer) {
  28032. buffer.dispose();
  28033. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28034. }
  28035. if (this._indexBuffer) {
  28036. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28037. this._indexBuffer = null;
  28038. }
  28039. };
  28040. return PostProcessManager;
  28041. }());
  28042. BABYLON.PostProcessManager = PostProcessManager;
  28043. })(BABYLON || (BABYLON = {}));
  28044. //# sourceMappingURL=babylon.postProcessManager.js.map
  28045. var BABYLON;
  28046. (function (BABYLON) {
  28047. var StandardMaterialDefines = (function (_super) {
  28048. __extends(StandardMaterialDefines, _super);
  28049. function StandardMaterialDefines() {
  28050. var _this = _super.call(this) || this;
  28051. _this.DIFFUSE = false;
  28052. _this.AMBIENT = false;
  28053. _this.OPACITY = false;
  28054. _this.OPACITYRGB = false;
  28055. _this.REFLECTION = false;
  28056. _this.EMISSIVE = false;
  28057. _this.SPECULAR = false;
  28058. _this.BUMP = false;
  28059. _this.PARALLAX = false;
  28060. _this.PARALLAXOCCLUSION = false;
  28061. _this.SPECULAROVERALPHA = false;
  28062. _this.CLIPPLANE = false;
  28063. _this.ALPHATEST = false;
  28064. _this.ALPHAFROMDIFFUSE = false;
  28065. _this.POINTSIZE = false;
  28066. _this.FOG = false;
  28067. _this.SPECULARTERM = false;
  28068. _this.DIFFUSEFRESNEL = false;
  28069. _this.OPACITYFRESNEL = false;
  28070. _this.REFLECTIONFRESNEL = false;
  28071. _this.REFRACTIONFRESNEL = false;
  28072. _this.EMISSIVEFRESNEL = false;
  28073. _this.FRESNEL = false;
  28074. _this.NORMAL = false;
  28075. _this.UV1 = false;
  28076. _this.UV2 = false;
  28077. _this.VERTEXCOLOR = false;
  28078. _this.VERTEXALPHA = false;
  28079. _this.NUM_BONE_INFLUENCERS = 0;
  28080. _this.BonesPerMesh = 0;
  28081. _this.INSTANCES = false;
  28082. _this.GLOSSINESS = false;
  28083. _this.ROUGHNESS = false;
  28084. _this.EMISSIVEASILLUMINATION = false;
  28085. _this.LINKEMISSIVEWITHDIFFUSE = false;
  28086. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  28087. _this.LIGHTMAP = false;
  28088. _this.USELIGHTMAPASSHADOWMAP = false;
  28089. _this.REFLECTIONMAP_3D = false;
  28090. _this.REFLECTIONMAP_SPHERICAL = false;
  28091. _this.REFLECTIONMAP_PLANAR = false;
  28092. _this.REFLECTIONMAP_CUBIC = false;
  28093. _this.REFLECTIONMAP_PROJECTION = false;
  28094. _this.REFLECTIONMAP_SKYBOX = false;
  28095. _this.REFLECTIONMAP_EXPLICIT = false;
  28096. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  28097. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  28098. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  28099. _this.INVERTCUBICMAP = false;
  28100. _this.LOGARITHMICDEPTH = false;
  28101. _this.REFRACTION = false;
  28102. _this.REFRACTIONMAP_3D = false;
  28103. _this.REFLECTIONOVERALPHA = false;
  28104. _this.INVERTNORMALMAPX = false;
  28105. _this.INVERTNORMALMAPY = false;
  28106. _this.TWOSIDEDLIGHTING = false;
  28107. _this.SHADOWFULLFLOAT = false;
  28108. _this.CAMERACOLORGRADING = false;
  28109. _this.CAMERACOLORCURVES = false;
  28110. _this.MORPHTARGETS = false;
  28111. _this.MORPHTARGETS_NORMAL = false;
  28112. _this.MORPHTARGETS_TANGENT = false;
  28113. _this.NUM_MORPH_INFLUENCERS = 0;
  28114. _this.USERIGHTHANDEDSYSTEM = false;
  28115. _this.rebuild();
  28116. return _this;
  28117. }
  28118. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  28119. var modes = [
  28120. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  28121. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  28122. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  28123. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  28124. ];
  28125. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  28126. var mode = modes_1[_i];
  28127. this[mode] = (mode === modeToEnable);
  28128. }
  28129. };
  28130. return StandardMaterialDefines;
  28131. }(BABYLON.MaterialDefines));
  28132. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  28133. var StandardMaterial = (function (_super) {
  28134. __extends(StandardMaterial, _super);
  28135. function StandardMaterial(name, scene) {
  28136. var _this = _super.call(this, name, scene) || this;
  28137. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  28138. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  28139. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  28140. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  28141. _this.specularPower = 64;
  28142. _this._useAlphaFromDiffuseTexture = false;
  28143. _this._useEmissiveAsIllumination = false;
  28144. _this._linkEmissiveWithDiffuse = false;
  28145. _this._useSpecularOverAlpha = false;
  28146. _this._useReflectionOverAlpha = false;
  28147. _this._disableLighting = false;
  28148. _this._useParallax = false;
  28149. _this._useParallaxOcclusion = false;
  28150. _this.parallaxScaleBias = 0.05;
  28151. _this._roughness = 0;
  28152. _this.indexOfRefraction = 0.98;
  28153. _this.invertRefractionY = true;
  28154. _this._useLightmapAsShadowmap = false;
  28155. _this._useReflectionFresnelFromSpecular = false;
  28156. _this._useGlossinessFromSpecularMapAlpha = false;
  28157. _this._maxSimultaneousLights = 4;
  28158. /**
  28159. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  28160. */
  28161. _this._invertNormalMapX = false;
  28162. /**
  28163. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  28164. */
  28165. _this._invertNormalMapY = false;
  28166. /**
  28167. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  28168. */
  28169. _this._twoSidedLighting = false;
  28170. /**
  28171. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  28172. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  28173. * 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;
  28174. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  28175. */
  28176. _this._cameraColorCurves = null;
  28177. _this._renderTargets = new BABYLON.SmartArray(16);
  28178. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  28179. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  28180. _this.getRenderTargetTextures = function () {
  28181. _this._renderTargets.reset();
  28182. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  28183. _this._renderTargets.push(_this._reflectionTexture);
  28184. }
  28185. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  28186. _this._renderTargets.push(_this._refractionTexture);
  28187. }
  28188. return _this._renderTargets;
  28189. };
  28190. return _this;
  28191. }
  28192. StandardMaterial.prototype.getClassName = function () {
  28193. return "StandardMaterial";
  28194. };
  28195. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  28196. get: function () {
  28197. return this._useLogarithmicDepth;
  28198. },
  28199. set: function (value) {
  28200. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  28201. this._markAllSubMeshesAsMiscDirty();
  28202. },
  28203. enumerable: true,
  28204. configurable: true
  28205. });
  28206. StandardMaterial.prototype.needAlphaBlending = function () {
  28207. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  28208. };
  28209. StandardMaterial.prototype.needAlphaTesting = function () {
  28210. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  28211. };
  28212. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  28213. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  28214. };
  28215. StandardMaterial.prototype.getAlphaTestTexture = function () {
  28216. return this._diffuseTexture;
  28217. };
  28218. /**
  28219. * Child classes can use it to update shaders
  28220. */
  28221. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28222. if (this.isFrozen) {
  28223. if (this._wasPreviouslyReady && subMesh.effect) {
  28224. return true;
  28225. }
  28226. }
  28227. if (!subMesh._materialDefines) {
  28228. subMesh._materialDefines = new StandardMaterialDefines();
  28229. }
  28230. var scene = this.getScene();
  28231. var defines = subMesh._materialDefines;
  28232. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  28233. if (defines._renderId === scene.getRenderId()) {
  28234. return true;
  28235. }
  28236. }
  28237. var engine = scene.getEngine();
  28238. // Lights
  28239. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  28240. // Textures
  28241. if (defines._areTexturesDirty) {
  28242. defines._needUVs = false;
  28243. if (scene.texturesEnabled) {
  28244. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28245. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  28246. return false;
  28247. }
  28248. else {
  28249. defines._needUVs = true;
  28250. defines.DIFFUSE = true;
  28251. }
  28252. }
  28253. else {
  28254. defines.DIFFUSE = false;
  28255. }
  28256. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28257. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  28258. return false;
  28259. }
  28260. else {
  28261. defines._needUVs = true;
  28262. defines.AMBIENT = true;
  28263. }
  28264. }
  28265. else {
  28266. defines.AMBIENT = false;
  28267. }
  28268. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28269. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  28270. return false;
  28271. }
  28272. else {
  28273. defines._needUVs = true;
  28274. defines.OPACITY = true;
  28275. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  28276. }
  28277. }
  28278. else {
  28279. defines.OPACITY = false;
  28280. }
  28281. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28282. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  28283. return false;
  28284. }
  28285. else {
  28286. defines._needNormals = true;
  28287. defines.REFLECTION = true;
  28288. defines.ROUGHNESS = (this._roughness > 0);
  28289. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  28290. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  28291. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  28292. switch (this._reflectionTexture.coordinatesMode) {
  28293. case BABYLON.Texture.CUBIC_MODE:
  28294. case BABYLON.Texture.INVCUBIC_MODE:
  28295. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  28296. break;
  28297. case BABYLON.Texture.EXPLICIT_MODE:
  28298. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  28299. break;
  28300. case BABYLON.Texture.PLANAR_MODE:
  28301. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  28302. break;
  28303. case BABYLON.Texture.PROJECTION_MODE:
  28304. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  28305. break;
  28306. case BABYLON.Texture.SKYBOX_MODE:
  28307. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  28308. break;
  28309. case BABYLON.Texture.SPHERICAL_MODE:
  28310. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  28311. break;
  28312. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28313. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  28314. break;
  28315. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28316. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  28317. break;
  28318. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28319. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  28320. break;
  28321. }
  28322. }
  28323. }
  28324. else {
  28325. defines.REFLECTION = false;
  28326. }
  28327. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28328. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  28329. return false;
  28330. }
  28331. else {
  28332. defines._needUVs = true;
  28333. defines.EMISSIVE = true;
  28334. }
  28335. }
  28336. else {
  28337. defines.EMISSIVE = false;
  28338. }
  28339. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28340. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  28341. return false;
  28342. }
  28343. else {
  28344. defines._needUVs = true;
  28345. defines.LIGHTMAP = true;
  28346. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  28347. }
  28348. }
  28349. else {
  28350. defines.LIGHTMAP = false;
  28351. }
  28352. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28353. if (!this._specularTexture.isReadyOrNotBlocking()) {
  28354. return false;
  28355. }
  28356. else {
  28357. defines._needUVs = true;
  28358. defines.SPECULAR = true;
  28359. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  28360. }
  28361. }
  28362. else {
  28363. defines.SPECULAR = false;
  28364. }
  28365. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  28366. // Bump texure can not be none blocking.
  28367. if (!this._bumpTexture.isReady()) {
  28368. return false;
  28369. }
  28370. else {
  28371. defines._needUVs = true;
  28372. defines.BUMP = true;
  28373. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  28374. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  28375. defines.PARALLAX = this._useParallax;
  28376. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  28377. }
  28378. }
  28379. else {
  28380. defines.BUMP = false;
  28381. }
  28382. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28383. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  28384. return false;
  28385. }
  28386. else {
  28387. defines._needUVs = true;
  28388. defines.REFRACTION = true;
  28389. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  28390. }
  28391. }
  28392. else {
  28393. defines.REFRACTION = false;
  28394. }
  28395. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  28396. // Camera Color Grading can not be none blocking.
  28397. if (!this._cameraColorGradingTexture.isReady()) {
  28398. return false;
  28399. }
  28400. else {
  28401. defines.CAMERACOLORGRADING = true;
  28402. }
  28403. }
  28404. else {
  28405. defines.CAMERACOLORGRADING = false;
  28406. }
  28407. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  28408. }
  28409. else {
  28410. defines.DIFFUSE = false;
  28411. defines.AMBIENT = false;
  28412. defines.OPACITY = false;
  28413. defines.REFLECTION = false;
  28414. defines.EMISSIVE = false;
  28415. defines.LIGHTMAP = false;
  28416. defines.BUMP = false;
  28417. defines.REFRACTION = false;
  28418. defines.CAMERACOLORGRADING = false;
  28419. }
  28420. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  28421. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  28422. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  28423. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  28424. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  28425. }
  28426. if (defines._areFresnelDirty) {
  28427. if (StandardMaterial.FresnelEnabled) {
  28428. // Fresnel
  28429. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  28430. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  28431. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  28432. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  28433. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  28434. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  28435. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  28436. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  28437. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  28438. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  28439. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  28440. defines._needNormals = true;
  28441. defines.FRESNEL = true;
  28442. }
  28443. }
  28444. else {
  28445. defines.FRESNEL = false;
  28446. }
  28447. }
  28448. // Misc.
  28449. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  28450. // Attribs
  28451. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  28452. // Values that need to be evaluated on every frame
  28453. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  28454. if (scene._mirroredCameraPosition && defines.BUMP) {
  28455. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  28456. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  28457. defines.markAsUnprocessed();
  28458. }
  28459. // Get correct effect
  28460. if (defines.isDirty) {
  28461. defines.markAsProcessed();
  28462. scene.resetCachedMaterial();
  28463. // Fallbacks
  28464. var fallbacks = new BABYLON.EffectFallbacks();
  28465. if (defines.REFLECTION) {
  28466. fallbacks.addFallback(0, "REFLECTION");
  28467. }
  28468. if (defines.SPECULAR) {
  28469. fallbacks.addFallback(0, "SPECULAR");
  28470. }
  28471. if (defines.BUMP) {
  28472. fallbacks.addFallback(0, "BUMP");
  28473. }
  28474. if (defines.PARALLAX) {
  28475. fallbacks.addFallback(1, "PARALLAX");
  28476. }
  28477. if (defines.PARALLAXOCCLUSION) {
  28478. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  28479. }
  28480. if (defines.SPECULAROVERALPHA) {
  28481. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  28482. }
  28483. if (defines.FOG) {
  28484. fallbacks.addFallback(1, "FOG");
  28485. }
  28486. if (defines.POINTSIZE) {
  28487. fallbacks.addFallback(0, "POINTSIZE");
  28488. }
  28489. if (defines.LOGARITHMICDEPTH) {
  28490. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  28491. }
  28492. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  28493. if (defines.SPECULARTERM) {
  28494. fallbacks.addFallback(0, "SPECULARTERM");
  28495. }
  28496. if (defines.DIFFUSEFRESNEL) {
  28497. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  28498. }
  28499. if (defines.OPACITYFRESNEL) {
  28500. fallbacks.addFallback(2, "OPACITYFRESNEL");
  28501. }
  28502. if (defines.REFLECTIONFRESNEL) {
  28503. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  28504. }
  28505. if (defines.EMISSIVEFRESNEL) {
  28506. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  28507. }
  28508. if (defines.FRESNEL) {
  28509. fallbacks.addFallback(4, "FRESNEL");
  28510. }
  28511. //Attributes
  28512. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28513. if (defines.NORMAL) {
  28514. attribs.push(BABYLON.VertexBuffer.NormalKind);
  28515. }
  28516. if (defines.UV1) {
  28517. attribs.push(BABYLON.VertexBuffer.UVKind);
  28518. }
  28519. if (defines.UV2) {
  28520. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28521. }
  28522. if (defines.VERTEXCOLOR) {
  28523. attribs.push(BABYLON.VertexBuffer.ColorKind);
  28524. }
  28525. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  28526. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  28527. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  28528. var shaderName = "default";
  28529. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  28530. "vFogInfos", "vFogColor", "pointSize",
  28531. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  28532. "mBones",
  28533. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  28534. "depthValues",
  28535. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  28536. "logarithmicDepthConstant"
  28537. ];
  28538. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  28539. var uniformBuffers = ["Material", "Scene"];
  28540. if (defines.CAMERACOLORCURVES) {
  28541. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  28542. }
  28543. if (defines.CAMERACOLORGRADING) {
  28544. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  28545. }
  28546. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  28547. uniformsNames: uniforms,
  28548. uniformBuffersNames: uniformBuffers,
  28549. samplers: samplers,
  28550. defines: defines,
  28551. maxSimultaneousLights: this._maxSimultaneousLights
  28552. });
  28553. if (this.customShaderNameResolve) {
  28554. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  28555. }
  28556. var join = defines.toString();
  28557. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  28558. attributes: attribs,
  28559. uniformsNames: uniforms,
  28560. uniformBuffersNames: uniformBuffers,
  28561. samplers: samplers,
  28562. defines: join,
  28563. fallbacks: fallbacks,
  28564. onCompiled: this.onCompiled,
  28565. onError: this.onError,
  28566. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  28567. }, engine), defines);
  28568. this.buildUniformLayout();
  28569. }
  28570. if (!subMesh.effect.isReady()) {
  28571. return false;
  28572. }
  28573. defines._renderId = scene.getRenderId();
  28574. this._wasPreviouslyReady = true;
  28575. return true;
  28576. };
  28577. StandardMaterial.prototype.buildUniformLayout = function () {
  28578. // Order is important !
  28579. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  28580. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  28581. this._uniformBuffer.addUniform("opacityParts", 4);
  28582. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  28583. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  28584. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  28585. this._uniformBuffer.addUniform("refractionRightColor", 4);
  28586. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  28587. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  28588. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  28589. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  28590. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  28591. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  28592. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  28593. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  28594. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  28595. this._uniformBuffer.addUniform("vBumpInfos", 3);
  28596. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  28597. this._uniformBuffer.addUniform("ambientMatrix", 16);
  28598. this._uniformBuffer.addUniform("opacityMatrix", 16);
  28599. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  28600. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  28601. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  28602. this._uniformBuffer.addUniform("specularMatrix", 16);
  28603. this._uniformBuffer.addUniform("bumpMatrix", 16);
  28604. this._uniformBuffer.addUniform("refractionMatrix", 16);
  28605. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  28606. this._uniformBuffer.addUniform("vSpecularColor", 4);
  28607. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  28608. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  28609. this._uniformBuffer.addUniform("pointSize", 1);
  28610. this._uniformBuffer.create();
  28611. };
  28612. StandardMaterial.prototype.unbind = function () {
  28613. if (this._activeEffect) {
  28614. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  28615. this._activeEffect.setTexture("reflection2DSampler", null);
  28616. }
  28617. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  28618. this._activeEffect.setTexture("refraction2DSampler", null);
  28619. }
  28620. }
  28621. _super.prototype.unbind.call(this);
  28622. };
  28623. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28624. var scene = this.getScene();
  28625. var defines = subMesh._materialDefines;
  28626. if (!defines) {
  28627. return;
  28628. }
  28629. var effect = subMesh.effect;
  28630. this._activeEffect = effect;
  28631. // Matrices
  28632. this.bindOnlyWorldMatrix(world);
  28633. // Bones
  28634. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  28635. if (this._mustRebind(scene, effect, mesh.visibility)) {
  28636. this._uniformBuffer.bindToEffect(effect, "Material");
  28637. this.bindViewProjection(effect);
  28638. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  28639. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  28640. // Fresnel
  28641. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  28642. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  28643. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  28644. }
  28645. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  28646. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  28647. }
  28648. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  28649. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  28650. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  28651. }
  28652. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  28653. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  28654. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  28655. }
  28656. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28657. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  28658. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  28659. }
  28660. }
  28661. // Textures
  28662. if (scene.texturesEnabled) {
  28663. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28664. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  28665. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  28666. }
  28667. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28668. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  28669. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  28670. }
  28671. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28672. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  28673. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  28674. }
  28675. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28676. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  28677. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  28678. }
  28679. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28680. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  28681. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  28682. }
  28683. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28684. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  28685. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  28686. }
  28687. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28688. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  28689. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  28690. }
  28691. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  28692. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  28693. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  28694. }
  28695. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28696. var depth = 1.0;
  28697. if (!this._refractionTexture.isCube) {
  28698. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  28699. if (this._refractionTexture.depth) {
  28700. depth = this._refractionTexture.depth;
  28701. }
  28702. }
  28703. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  28704. }
  28705. }
  28706. // Point size
  28707. if (this.pointsCloud) {
  28708. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  28709. }
  28710. if (defines.SPECULARTERM) {
  28711. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  28712. }
  28713. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  28714. // Diffuse
  28715. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  28716. }
  28717. // Textures
  28718. if (scene.texturesEnabled) {
  28719. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28720. effect.setTexture("diffuseSampler", this._diffuseTexture);
  28721. }
  28722. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28723. effect.setTexture("ambientSampler", this._ambientTexture);
  28724. }
  28725. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28726. effect.setTexture("opacitySampler", this._opacityTexture);
  28727. }
  28728. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28729. if (this._reflectionTexture.isCube) {
  28730. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  28731. }
  28732. else {
  28733. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  28734. }
  28735. }
  28736. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28737. effect.setTexture("emissiveSampler", this._emissiveTexture);
  28738. }
  28739. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28740. effect.setTexture("lightmapSampler", this._lightmapTexture);
  28741. }
  28742. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28743. effect.setTexture("specularSampler", this._specularTexture);
  28744. }
  28745. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  28746. effect.setTexture("bumpSampler", this._bumpTexture);
  28747. }
  28748. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28749. var depth = 1.0;
  28750. if (this._refractionTexture.isCube) {
  28751. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  28752. }
  28753. else {
  28754. effect.setTexture("refraction2DSampler", this._refractionTexture);
  28755. }
  28756. }
  28757. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  28758. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  28759. }
  28760. }
  28761. // Clip plane
  28762. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  28763. // Colors
  28764. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  28765. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  28766. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  28767. }
  28768. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  28769. // Lights
  28770. if (scene.lightsEnabled && !this._disableLighting) {
  28771. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  28772. }
  28773. // View
  28774. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  28775. this.bindView(effect);
  28776. }
  28777. // Fog
  28778. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  28779. // Morph targets
  28780. if (defines.NUM_MORPH_INFLUENCERS) {
  28781. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  28782. }
  28783. // Log. depth
  28784. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  28785. // Color Curves
  28786. if (this._cameraColorCurves) {
  28787. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  28788. }
  28789. }
  28790. this._uniformBuffer.update();
  28791. this._afterBind(mesh, this._activeEffect);
  28792. };
  28793. StandardMaterial.prototype.getAnimatables = function () {
  28794. var results = [];
  28795. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  28796. results.push(this._diffuseTexture);
  28797. }
  28798. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  28799. results.push(this._ambientTexture);
  28800. }
  28801. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  28802. results.push(this._opacityTexture);
  28803. }
  28804. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  28805. results.push(this._reflectionTexture);
  28806. }
  28807. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  28808. results.push(this._emissiveTexture);
  28809. }
  28810. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  28811. results.push(this._specularTexture);
  28812. }
  28813. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  28814. results.push(this._bumpTexture);
  28815. }
  28816. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  28817. results.push(this._lightmapTexture);
  28818. }
  28819. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  28820. results.push(this._refractionTexture);
  28821. }
  28822. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  28823. results.push(this._cameraColorGradingTexture);
  28824. }
  28825. return results;
  28826. };
  28827. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28828. if (forceDisposeTextures) {
  28829. if (this._diffuseTexture) {
  28830. this._diffuseTexture.dispose();
  28831. }
  28832. if (this._ambientTexture) {
  28833. this._ambientTexture.dispose();
  28834. }
  28835. if (this._opacityTexture) {
  28836. this._opacityTexture.dispose();
  28837. }
  28838. if (this._reflectionTexture) {
  28839. this._reflectionTexture.dispose();
  28840. }
  28841. if (this._emissiveTexture) {
  28842. this._emissiveTexture.dispose();
  28843. }
  28844. if (this._specularTexture) {
  28845. this._specularTexture.dispose();
  28846. }
  28847. if (this._bumpTexture) {
  28848. this._bumpTexture.dispose();
  28849. }
  28850. if (this._lightmapTexture) {
  28851. this._lightmapTexture.dispose();
  28852. }
  28853. if (this._refractionTexture) {
  28854. this._refractionTexture.dispose();
  28855. }
  28856. if (this._cameraColorGradingTexture) {
  28857. this._cameraColorGradingTexture.dispose();
  28858. }
  28859. }
  28860. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  28861. };
  28862. StandardMaterial.prototype.clone = function (name) {
  28863. var _this = this;
  28864. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  28865. result.name = name;
  28866. result.id = name;
  28867. return result;
  28868. };
  28869. StandardMaterial.prototype.serialize = function () {
  28870. return BABYLON.SerializationHelper.Serialize(this);
  28871. };
  28872. // Statics
  28873. StandardMaterial.Parse = function (source, scene, rootUrl) {
  28874. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  28875. };
  28876. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  28877. get: function () {
  28878. return StandardMaterial._DiffuseTextureEnabled;
  28879. },
  28880. set: function (value) {
  28881. if (StandardMaterial._DiffuseTextureEnabled === value) {
  28882. return;
  28883. }
  28884. StandardMaterial._DiffuseTextureEnabled = value;
  28885. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28886. },
  28887. enumerable: true,
  28888. configurable: true
  28889. });
  28890. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  28891. get: function () {
  28892. return StandardMaterial._AmbientTextureEnabled;
  28893. },
  28894. set: function (value) {
  28895. if (StandardMaterial._AmbientTextureEnabled === value) {
  28896. return;
  28897. }
  28898. StandardMaterial._AmbientTextureEnabled = value;
  28899. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28900. },
  28901. enumerable: true,
  28902. configurable: true
  28903. });
  28904. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  28905. get: function () {
  28906. return StandardMaterial._OpacityTextureEnabled;
  28907. },
  28908. set: function (value) {
  28909. if (StandardMaterial._OpacityTextureEnabled === value) {
  28910. return;
  28911. }
  28912. StandardMaterial._OpacityTextureEnabled = value;
  28913. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28914. },
  28915. enumerable: true,
  28916. configurable: true
  28917. });
  28918. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  28919. get: function () {
  28920. return StandardMaterial._ReflectionTextureEnabled;
  28921. },
  28922. set: function (value) {
  28923. if (StandardMaterial._ReflectionTextureEnabled === value) {
  28924. return;
  28925. }
  28926. StandardMaterial._ReflectionTextureEnabled = value;
  28927. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28928. },
  28929. enumerable: true,
  28930. configurable: true
  28931. });
  28932. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  28933. get: function () {
  28934. return StandardMaterial._EmissiveTextureEnabled;
  28935. },
  28936. set: function (value) {
  28937. if (StandardMaterial._EmissiveTextureEnabled === value) {
  28938. return;
  28939. }
  28940. StandardMaterial._EmissiveTextureEnabled = value;
  28941. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28942. },
  28943. enumerable: true,
  28944. configurable: true
  28945. });
  28946. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  28947. get: function () {
  28948. return StandardMaterial._SpecularTextureEnabled;
  28949. },
  28950. set: function (value) {
  28951. if (StandardMaterial._SpecularTextureEnabled === value) {
  28952. return;
  28953. }
  28954. StandardMaterial._SpecularTextureEnabled = value;
  28955. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28956. },
  28957. enumerable: true,
  28958. configurable: true
  28959. });
  28960. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  28961. get: function () {
  28962. return StandardMaterial._BumpTextureEnabled;
  28963. },
  28964. set: function (value) {
  28965. if (StandardMaterial._BumpTextureEnabled === value) {
  28966. return;
  28967. }
  28968. StandardMaterial._BumpTextureEnabled = value;
  28969. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28970. },
  28971. enumerable: true,
  28972. configurable: true
  28973. });
  28974. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  28975. get: function () {
  28976. return StandardMaterial._LightmapTextureEnabled;
  28977. },
  28978. set: function (value) {
  28979. if (StandardMaterial._LightmapTextureEnabled === value) {
  28980. return;
  28981. }
  28982. StandardMaterial._LightmapTextureEnabled = value;
  28983. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28984. },
  28985. enumerable: true,
  28986. configurable: true
  28987. });
  28988. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  28989. get: function () {
  28990. return StandardMaterial._RefractionTextureEnabled;
  28991. },
  28992. set: function (value) {
  28993. if (StandardMaterial._RefractionTextureEnabled === value) {
  28994. return;
  28995. }
  28996. StandardMaterial._RefractionTextureEnabled = value;
  28997. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28998. },
  28999. enumerable: true,
  29000. configurable: true
  29001. });
  29002. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  29003. get: function () {
  29004. return StandardMaterial._ColorGradingTextureEnabled;
  29005. },
  29006. set: function (value) {
  29007. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  29008. return;
  29009. }
  29010. StandardMaterial._ColorGradingTextureEnabled = value;
  29011. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29012. },
  29013. enumerable: true,
  29014. configurable: true
  29015. });
  29016. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  29017. get: function () {
  29018. return StandardMaterial._FresnelEnabled;
  29019. },
  29020. set: function (value) {
  29021. if (StandardMaterial._FresnelEnabled === value) {
  29022. return;
  29023. }
  29024. StandardMaterial._FresnelEnabled = value;
  29025. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  29026. },
  29027. enumerable: true,
  29028. configurable: true
  29029. });
  29030. return StandardMaterial;
  29031. }(BABYLON.PushMaterial));
  29032. // Flags used to enable or disable a type of texture for all Standard Materials
  29033. StandardMaterial._DiffuseTextureEnabled = true;
  29034. StandardMaterial._AmbientTextureEnabled = true;
  29035. StandardMaterial._OpacityTextureEnabled = true;
  29036. StandardMaterial._ReflectionTextureEnabled = true;
  29037. StandardMaterial._EmissiveTextureEnabled = true;
  29038. StandardMaterial._SpecularTextureEnabled = true;
  29039. StandardMaterial._BumpTextureEnabled = true;
  29040. StandardMaterial._LightmapTextureEnabled = true;
  29041. StandardMaterial._RefractionTextureEnabled = true;
  29042. StandardMaterial._ColorGradingTextureEnabled = true;
  29043. StandardMaterial._FresnelEnabled = true;
  29044. __decorate([
  29045. BABYLON.serializeAsTexture("diffuseTexture")
  29046. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  29047. __decorate([
  29048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29049. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  29050. __decorate([
  29051. BABYLON.serializeAsTexture("ambientTexture")
  29052. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  29053. __decorate([
  29054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29055. ], StandardMaterial.prototype, "ambientTexture", void 0);
  29056. __decorate([
  29057. BABYLON.serializeAsTexture("opacityTexture")
  29058. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  29059. __decorate([
  29060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29061. ], StandardMaterial.prototype, "opacityTexture", void 0);
  29062. __decorate([
  29063. BABYLON.serializeAsTexture("reflectionTexture")
  29064. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  29065. __decorate([
  29066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29067. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  29068. __decorate([
  29069. BABYLON.serializeAsTexture("emissiveTexture")
  29070. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  29071. __decorate([
  29072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29073. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  29074. __decorate([
  29075. BABYLON.serializeAsTexture("specularTexture")
  29076. ], StandardMaterial.prototype, "_specularTexture", void 0);
  29077. __decorate([
  29078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29079. ], StandardMaterial.prototype, "specularTexture", void 0);
  29080. __decorate([
  29081. BABYLON.serializeAsTexture("bumpTexture")
  29082. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  29083. __decorate([
  29084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29085. ], StandardMaterial.prototype, "bumpTexture", void 0);
  29086. __decorate([
  29087. BABYLON.serializeAsTexture("lightmapTexture")
  29088. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  29089. __decorate([
  29090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29091. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  29092. __decorate([
  29093. BABYLON.serializeAsTexture("refractionTexture")
  29094. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  29095. __decorate([
  29096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29097. ], StandardMaterial.prototype, "refractionTexture", void 0);
  29098. __decorate([
  29099. BABYLON.serializeAsColor3("ambient")
  29100. ], StandardMaterial.prototype, "ambientColor", void 0);
  29101. __decorate([
  29102. BABYLON.serializeAsColor3("diffuse")
  29103. ], StandardMaterial.prototype, "diffuseColor", void 0);
  29104. __decorate([
  29105. BABYLON.serializeAsColor3("specular")
  29106. ], StandardMaterial.prototype, "specularColor", void 0);
  29107. __decorate([
  29108. BABYLON.serializeAsColor3("emissive")
  29109. ], StandardMaterial.prototype, "emissiveColor", void 0);
  29110. __decorate([
  29111. BABYLON.serialize()
  29112. ], StandardMaterial.prototype, "specularPower", void 0);
  29113. __decorate([
  29114. BABYLON.serialize("useAlphaFromDiffuseTexture")
  29115. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  29116. __decorate([
  29117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29118. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  29119. __decorate([
  29120. BABYLON.serialize("useEmissiveAsIllumination")
  29121. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  29122. __decorate([
  29123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29124. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29125. __decorate([
  29126. BABYLON.serialize("linkEmissiveWithDiffuse")
  29127. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  29128. __decorate([
  29129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29130. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  29131. __decorate([
  29132. BABYLON.serialize("useSpecularOverAlpha")
  29133. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  29134. __decorate([
  29135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29136. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  29137. __decorate([
  29138. BABYLON.serialize("useReflectionOverAlpha")
  29139. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  29140. __decorate([
  29141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29142. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  29143. __decorate([
  29144. BABYLON.serialize("disableLighting")
  29145. ], StandardMaterial.prototype, "_disableLighting", void 0);
  29146. __decorate([
  29147. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29148. ], StandardMaterial.prototype, "disableLighting", void 0);
  29149. __decorate([
  29150. BABYLON.serialize("useParallax")
  29151. ], StandardMaterial.prototype, "_useParallax", void 0);
  29152. __decorate([
  29153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29154. ], StandardMaterial.prototype, "useParallax", void 0);
  29155. __decorate([
  29156. BABYLON.serialize("useParallaxOcclusion")
  29157. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  29158. __decorate([
  29159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29160. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  29161. __decorate([
  29162. BABYLON.serialize()
  29163. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  29164. __decorate([
  29165. BABYLON.serialize("roughness")
  29166. ], StandardMaterial.prototype, "_roughness", void 0);
  29167. __decorate([
  29168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29169. ], StandardMaterial.prototype, "roughness", void 0);
  29170. __decorate([
  29171. BABYLON.serialize()
  29172. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  29173. __decorate([
  29174. BABYLON.serialize()
  29175. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  29176. __decorate([
  29177. BABYLON.serialize("useLightmapAsShadowmap")
  29178. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  29179. __decorate([
  29180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29181. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  29182. __decorate([
  29183. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  29184. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  29185. __decorate([
  29186. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29187. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  29188. __decorate([
  29189. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  29190. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  29191. __decorate([
  29192. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29193. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  29194. __decorate([
  29195. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  29196. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  29197. __decorate([
  29198. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29199. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  29200. __decorate([
  29201. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  29202. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  29203. __decorate([
  29204. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29205. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  29206. __decorate([
  29207. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  29208. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  29209. __decorate([
  29210. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29211. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  29212. __decorate([
  29213. BABYLON.serialize("useReflectionFresnelFromSpecular")
  29214. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  29215. __decorate([
  29216. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29217. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  29218. __decorate([
  29219. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  29220. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  29221. __decorate([
  29222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29223. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  29224. __decorate([
  29225. BABYLON.serialize("maxSimultaneousLights")
  29226. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  29227. __decorate([
  29228. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29229. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  29230. __decorate([
  29231. BABYLON.serialize("invertNormalMapX")
  29232. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  29233. __decorate([
  29234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29235. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  29236. __decorate([
  29237. BABYLON.serialize("invertNormalMapY")
  29238. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  29239. __decorate([
  29240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29241. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  29242. __decorate([
  29243. BABYLON.serialize("twoSidedLighting")
  29244. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  29245. __decorate([
  29246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29247. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  29248. __decorate([
  29249. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  29250. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  29251. __decorate([
  29252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29253. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  29254. __decorate([
  29255. BABYLON.serializeAsColorCurves("cameraColorCurves")
  29256. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  29257. __decorate([
  29258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29259. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  29260. __decorate([
  29261. BABYLON.serialize()
  29262. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  29263. BABYLON.StandardMaterial = StandardMaterial;
  29264. })(BABYLON || (BABYLON = {}));
  29265. //# sourceMappingURL=babylon.standardMaterial.js.map
  29266. var BABYLON;
  29267. (function (BABYLON) {
  29268. var PBRMaterialDefines = (function (_super) {
  29269. __extends(PBRMaterialDefines, _super);
  29270. function PBRMaterialDefines() {
  29271. var _this = _super.call(this) || this;
  29272. _this.PBR = true;
  29273. _this.ALBEDO = false;
  29274. _this.AMBIENT = false;
  29275. _this.AMBIENTINGRAYSCALE = false;
  29276. _this.OPACITY = false;
  29277. _this.OPACITYRGB = false;
  29278. _this.REFLECTION = false;
  29279. _this.EMISSIVE = false;
  29280. _this.REFLECTIVITY = false;
  29281. _this.BUMP = false;
  29282. _this.PARALLAX = false;
  29283. _this.PARALLAXOCCLUSION = false;
  29284. _this.SPECULAROVERALPHA = false;
  29285. _this.CLIPPLANE = false;
  29286. _this.ALPHATEST = false;
  29287. _this.ALPHAFROMALBEDO = false;
  29288. _this.POINTSIZE = false;
  29289. _this.FOG = false;
  29290. _this.SPECULARTERM = false;
  29291. _this.OPACITYFRESNEL = false;
  29292. _this.EMISSIVEFRESNEL = false;
  29293. _this.FRESNEL = false;
  29294. _this.NORMAL = false;
  29295. _this.TANGENT = false;
  29296. _this.UV1 = false;
  29297. _this.UV2 = false;
  29298. _this.VERTEXCOLOR = false;
  29299. _this.VERTEXALPHA = false;
  29300. _this.NUM_BONE_INFLUENCERS = 0;
  29301. _this.BonesPerMesh = 0;
  29302. _this.INSTANCES = false;
  29303. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  29304. _this.MICROSURFACEAUTOMATIC = false;
  29305. _this.EMISSIVEASILLUMINATION = false;
  29306. _this.LIGHTMAP = false;
  29307. _this.USELIGHTMAPASSHADOWMAP = false;
  29308. _this.REFLECTIONMAP_3D = false;
  29309. _this.REFLECTIONMAP_SPHERICAL = false;
  29310. _this.REFLECTIONMAP_PLANAR = false;
  29311. _this.REFLECTIONMAP_CUBIC = false;
  29312. _this.REFLECTIONMAP_PROJECTION = false;
  29313. _this.REFLECTIONMAP_SKYBOX = false;
  29314. _this.REFLECTIONMAP_EXPLICIT = false;
  29315. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29316. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29317. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  29318. _this.INVERTCUBICMAP = false;
  29319. _this.LOGARITHMICDEPTH = false;
  29320. _this.CAMERATONEMAP = false;
  29321. _this.CAMERACONTRAST = false;
  29322. _this.CAMERACOLORGRADING = false;
  29323. _this.CAMERACOLORCURVES = false;
  29324. _this.USESPHERICALFROMREFLECTIONMAP = false;
  29325. _this.REFRACTION = false;
  29326. _this.REFRACTIONMAP_3D = false;
  29327. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  29328. _this.REFRACTIONMAPINLINEARSPACE = false;
  29329. _this.LODBASEDMICROSFURACE = false;
  29330. _this.USEPHYSICALLIGHTFALLOFF = false;
  29331. _this.RADIANCEOVERALPHA = false;
  29332. _this.USEPMREMREFLECTION = false;
  29333. _this.USEPMREMREFRACTION = false;
  29334. _this.INVERTNORMALMAPX = false;
  29335. _this.INVERTNORMALMAPY = false;
  29336. _this.TWOSIDEDLIGHTING = false;
  29337. _this.SHADOWFULLFLOAT = false;
  29338. _this.NORMALXYSCALE = true;
  29339. _this.USERIGHTHANDEDSYSTEM = false;
  29340. _this.METALLICWORKFLOW = false;
  29341. _this.METALLICMAP = false;
  29342. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  29343. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  29344. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  29345. _this.AOSTOREINMETALMAPRED = false;
  29346. _this.MICROSURFACEMAP = false;
  29347. _this.MORPHTARGETS = false;
  29348. _this.MORPHTARGETS_NORMAL = false;
  29349. _this.MORPHTARGETS_TANGENT = false;
  29350. _this.NUM_MORPH_INFLUENCERS = 0;
  29351. _this.ALPHATESTVALUE = 0.4;
  29352. _this.LDROUTPUT = true;
  29353. _this.rebuild();
  29354. return _this;
  29355. }
  29356. PBRMaterialDefines.prototype.reset = function () {
  29357. _super.prototype.reset.call(this);
  29358. this.ALPHATESTVALUE = 0.4;
  29359. this.PBR = true;
  29360. };
  29361. return PBRMaterialDefines;
  29362. }(BABYLON.MaterialDefines));
  29363. /**
  29364. * The Physically based material base class of BJS.
  29365. *
  29366. * This offers the main features of a standard PBR material.
  29367. * For more information, please refer to the documentation :
  29368. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  29369. */
  29370. var PBRBaseMaterial = (function (_super) {
  29371. __extends(PBRBaseMaterial, _super);
  29372. /**
  29373. * Instantiates a new PBRMaterial instance.
  29374. *
  29375. * @param name The material name
  29376. * @param scene The scene the material will be use in.
  29377. */
  29378. function PBRBaseMaterial(name, scene) {
  29379. var _this = _super.call(this, name, scene) || this;
  29380. /**
  29381. * Intensity of the direct lights e.g. the four lights available in your scene.
  29382. * This impacts both the direct diffuse and specular highlights.
  29383. */
  29384. _this._directIntensity = 1.0;
  29385. /**
  29386. * Intensity of the emissive part of the material.
  29387. * This helps controlling the emissive effect without modifying the emissive color.
  29388. */
  29389. _this._emissiveIntensity = 1.0;
  29390. /**
  29391. * Intensity of the environment e.g. how much the environment will light the object
  29392. * either through harmonics for rough material or through the refelction for shiny ones.
  29393. */
  29394. _this._environmentIntensity = 1.0;
  29395. /**
  29396. * This is a special control allowing the reduction of the specular highlights coming from the
  29397. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  29398. */
  29399. _this._specularIntensity = 1.0;
  29400. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  29401. /**
  29402. * Debug Control allowing disabling the bump map on this material.
  29403. */
  29404. _this._disableBumpMap = false;
  29405. /**
  29406. * The camera exposure used on this material.
  29407. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  29408. * This corresponds to a photographic exposure.
  29409. */
  29410. _this._cameraExposure = 1.0;
  29411. /**
  29412. * The camera contrast used on this material.
  29413. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  29414. */
  29415. _this._cameraContrast = 1.0;
  29416. /**
  29417. * Color Grading 2D Lookup Texture.
  29418. * This allows special effects like sepia, black and white to sixties rendering style.
  29419. */
  29420. _this._cameraColorGradingTexture = null;
  29421. /**
  29422. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  29423. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  29424. * 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;
  29425. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  29426. */
  29427. _this._cameraColorCurves = null;
  29428. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  29429. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  29430. /**
  29431. * AKA Occlusion Texture Intensity in other nomenclature.
  29432. */
  29433. _this._ambientTextureStrength = 1.0;
  29434. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  29435. /**
  29436. * AKA Diffuse Color in other nomenclature.
  29437. */
  29438. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  29439. /**
  29440. * AKA Specular Color in other nomenclature.
  29441. */
  29442. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  29443. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  29444. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  29445. /**
  29446. * AKA Glossiness in other nomenclature.
  29447. */
  29448. _this._microSurface = 0.9;
  29449. /**
  29450. * source material index of refraction (IOR)' / 'destination material IOR.
  29451. */
  29452. _this._indexOfRefraction = 0.66;
  29453. /**
  29454. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  29455. */
  29456. _this._invertRefractionY = false;
  29457. /**
  29458. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  29459. * Materials half opaque for instance using refraction could benefit from this control.
  29460. */
  29461. _this._linkRefractionWithTransparency = false;
  29462. _this._useLightmapAsShadowmap = false;
  29463. /**
  29464. * In this mode, the emissive informtaion will always be added to the lighting once.
  29465. * A light for instance can be thought as emissive.
  29466. */
  29467. _this._useEmissiveAsIllumination = false;
  29468. /**
  29469. * Secifies that the alpha is coming form the albedo channel alpha channel.
  29470. */
  29471. _this._useAlphaFromAlbedoTexture = false;
  29472. /**
  29473. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  29474. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  29475. */
  29476. _this._useSpecularOverAlpha = true;
  29477. /**
  29478. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  29479. */
  29480. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  29481. /**
  29482. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  29483. */
  29484. _this._useRoughnessFromMetallicTextureAlpha = true;
  29485. /**
  29486. * Specifies if the metallic texture contains the roughness information in its green channel.
  29487. */
  29488. _this._useRoughnessFromMetallicTextureGreen = false;
  29489. /**
  29490. * Specifies if the metallic texture contains the metallness information in its blue channel.
  29491. */
  29492. _this._useMetallnessFromMetallicTextureBlue = false;
  29493. /**
  29494. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  29495. */
  29496. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  29497. /**
  29498. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  29499. */
  29500. _this._useAmbientInGrayScale = false;
  29501. /**
  29502. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  29503. * The material will try to infer what glossiness each pixel should be.
  29504. */
  29505. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  29506. /**
  29507. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  29508. * the creation of the material.
  29509. */
  29510. _this._useScalarInLinearSpace = false;
  29511. /**
  29512. * BJS is using an harcoded light falloff based on a manually sets up range.
  29513. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  29514. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  29515. */
  29516. _this._usePhysicalLightFalloff = true;
  29517. /**
  29518. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  29519. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  29520. */
  29521. _this._useRadianceOverAlpha = true;
  29522. /**
  29523. * Allows using the bump map in parallax mode.
  29524. */
  29525. _this._useParallax = false;
  29526. /**
  29527. * Allows using the bump map in parallax occlusion mode.
  29528. */
  29529. _this._useParallaxOcclusion = false;
  29530. /**
  29531. * Controls the scale bias of the parallax mode.
  29532. */
  29533. _this._parallaxScaleBias = 0.05;
  29534. /**
  29535. * If sets to true, disables all the lights affecting the material.
  29536. */
  29537. _this._disableLighting = false;
  29538. /**
  29539. * Number of Simultaneous lights allowed on the material.
  29540. */
  29541. _this._maxSimultaneousLights = 4;
  29542. /**
  29543. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29544. */
  29545. _this._invertNormalMapX = false;
  29546. /**
  29547. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  29548. */
  29549. _this._invertNormalMapY = false;
  29550. /**
  29551. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  29552. */
  29553. _this._twoSidedLighting = false;
  29554. /**
  29555. * Defines the alpha limits in alpha test mode.
  29556. */
  29557. _this._alphaCutOff = 0.4;
  29558. /**
  29559. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  29560. */
  29561. _this._forceAlphaTest = false;
  29562. /**
  29563. * If false, it allows the output of the shader to be in hdr space (e.g. more than one) which is usefull
  29564. * in combination of post process in float or half float mode.
  29565. */
  29566. _this._ldrOutput = true;
  29567. _this._renderTargets = new BABYLON.SmartArray(16);
  29568. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  29569. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  29570. _this._tempColor = new BABYLON.Color3();
  29571. _this._defines = new PBRMaterialDefines();
  29572. _this._cachedDefines = new PBRMaterialDefines();
  29573. _this._myScene = null;
  29574. _this._myShadowGenerator = null;
  29575. _this._cachedDefines.BonesPerMesh = -1;
  29576. _this.getRenderTargetTextures = function () {
  29577. _this._renderTargets.reset();
  29578. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  29579. _this._renderTargets.push(_this._reflectionTexture);
  29580. }
  29581. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  29582. _this._renderTargets.push(_this._refractionTexture);
  29583. }
  29584. return _this._renderTargets;
  29585. };
  29586. return _this;
  29587. }
  29588. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  29589. get: function () {
  29590. return this._useLogarithmicDepth;
  29591. },
  29592. set: function (value) {
  29593. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  29594. },
  29595. enumerable: true,
  29596. configurable: true
  29597. });
  29598. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  29599. if (this._linkRefractionWithTransparency) {
  29600. return false;
  29601. }
  29602. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  29603. };
  29604. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  29605. if (this._linkRefractionWithTransparency) {
  29606. return false;
  29607. }
  29608. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  29609. };
  29610. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  29611. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  29612. };
  29613. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  29614. return this._albedoTexture;
  29615. };
  29616. PBRBaseMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  29617. if (!mesh) {
  29618. return true;
  29619. }
  29620. if (this._defines.INSTANCES !== useInstances) {
  29621. return false;
  29622. }
  29623. return false;
  29624. };
  29625. PBRBaseMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  29626. BABYLON.PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this._useScalarInLinearSpace);
  29627. };
  29628. PBRBaseMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  29629. if (!useScalarInLinear) {
  29630. color.toLinearSpaceToRef(ref);
  29631. }
  29632. else {
  29633. ref.r = color.r;
  29634. ref.g = color.g;
  29635. ref.b = color.b;
  29636. }
  29637. };
  29638. PBRBaseMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  29639. var lightIndex = 0;
  29640. var depthValuesAlreadySet = false;
  29641. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  29642. var light = _a[_i];
  29643. var useUbo = light._uniformBuffer.useUbo;
  29644. var scaledIntensity = light.getScaledIntensity();
  29645. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  29646. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  29647. // GAMMA CORRECTION.
  29648. this.convertColorToLinearSpaceToRef(light.diffuse, BABYLON.PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  29649. BABYLON.PBRMaterial._scaledAlbedo.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledAlbedo);
  29650. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, BABYLON.PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  29651. if (defines["SPECULARTERM"]) {
  29652. this.convertColorToLinearSpaceToRef(light.specular, BABYLON.PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  29653. BABYLON.PBRMaterial._scaledReflectivity.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledReflectivity);
  29654. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, BABYLON.PBRMaterial._scaledReflectivity);
  29655. }
  29656. // Shadows
  29657. if (scene.shadowsEnabled) {
  29658. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  29659. }
  29660. light._uniformBuffer.update();
  29661. lightIndex++;
  29662. if (lightIndex === maxSimultaneousLights)
  29663. break;
  29664. }
  29665. };
  29666. PBRBaseMaterial.prototype.isReady = function (mesh, useInstances) {
  29667. if (this.isFrozen) {
  29668. if (this._wasPreviouslyReady) {
  29669. return true;
  29670. }
  29671. }
  29672. var scene = this.getScene();
  29673. var engine = scene.getEngine();
  29674. var needUVs = false;
  29675. this._defines.reset();
  29676. if (scene.lightsEnabled && !this._disableLighting) {
  29677. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this._maxSimultaneousLights);
  29678. }
  29679. if (!this.checkReadyOnEveryCall) {
  29680. if (this._renderId === scene.getRenderId()) {
  29681. if (this._checkCache(scene, mesh, useInstances)) {
  29682. return true;
  29683. }
  29684. }
  29685. }
  29686. if (scene.texturesEnabled) {
  29687. if (scene.getEngine().getCaps().textureLOD) {
  29688. this._defines.LODBASEDMICROSFURACE = true;
  29689. }
  29690. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29691. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  29692. return false;
  29693. }
  29694. needUVs = true;
  29695. this._defines.ALBEDO = true;
  29696. }
  29697. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29698. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  29699. return false;
  29700. }
  29701. needUVs = true;
  29702. this._defines.AMBIENT = true;
  29703. this._defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  29704. }
  29705. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29706. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  29707. return false;
  29708. }
  29709. needUVs = true;
  29710. this._defines.OPACITY = true;
  29711. if (this._opacityTexture.getAlphaFromRGB) {
  29712. this._defines.OPACITYRGB = true;
  29713. }
  29714. }
  29715. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  29716. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29717. if (!reflectionTexture.isReadyOrNotBlocking()) {
  29718. return false;
  29719. }
  29720. this._defines.REFLECTION = true;
  29721. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  29722. this._defines.INVERTCUBICMAP = true;
  29723. }
  29724. this._defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  29725. switch (reflectionTexture.coordinatesMode) {
  29726. case BABYLON.Texture.CUBIC_MODE:
  29727. case BABYLON.Texture.INVCUBIC_MODE:
  29728. this._defines.REFLECTIONMAP_CUBIC = true;
  29729. break;
  29730. case BABYLON.Texture.EXPLICIT_MODE:
  29731. this._defines.REFLECTIONMAP_EXPLICIT = true;
  29732. break;
  29733. case BABYLON.Texture.PLANAR_MODE:
  29734. this._defines.REFLECTIONMAP_PLANAR = true;
  29735. break;
  29736. case BABYLON.Texture.PROJECTION_MODE:
  29737. this._defines.REFLECTIONMAP_PROJECTION = true;
  29738. break;
  29739. case BABYLON.Texture.SKYBOX_MODE:
  29740. this._defines.REFLECTIONMAP_SKYBOX = true;
  29741. break;
  29742. case BABYLON.Texture.SPHERICAL_MODE:
  29743. this._defines.REFLECTIONMAP_SPHERICAL = true;
  29744. break;
  29745. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  29746. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  29747. break;
  29748. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  29749. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  29750. break;
  29751. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  29752. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  29753. break;
  29754. }
  29755. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  29756. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  29757. if (reflectionTexture.isPMREM) {
  29758. this._defines.USEPMREMREFLECTION = true;
  29759. }
  29760. }
  29761. }
  29762. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29763. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  29764. return false;
  29765. }
  29766. needUVs = true;
  29767. this._defines.LIGHTMAP = true;
  29768. this._defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  29769. }
  29770. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29771. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  29772. return false;
  29773. }
  29774. needUVs = true;
  29775. this._defines.EMISSIVE = true;
  29776. }
  29777. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29778. if (this._metallicTexture) {
  29779. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  29780. return false;
  29781. }
  29782. needUVs = true;
  29783. this._defines.METALLICWORKFLOW = true;
  29784. this._defines.METALLICMAP = true;
  29785. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  29786. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  29787. this._defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  29788. this._defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  29789. }
  29790. else if (this._reflectivityTexture) {
  29791. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  29792. return false;
  29793. }
  29794. needUVs = true;
  29795. this._defines.REFLECTIVITY = true;
  29796. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  29797. this._defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  29798. }
  29799. if (this._microSurfaceTexture) {
  29800. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  29801. return false;
  29802. }
  29803. needUVs = true;
  29804. this._defines.MICROSURFACEMAP = true;
  29805. }
  29806. }
  29807. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  29808. // Bump texure can not be none blocking.
  29809. if (!this._bumpTexture.isReady()) {
  29810. return false;
  29811. }
  29812. needUVs = true;
  29813. this._defines.BUMP = true;
  29814. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29815. this._defines.PARALLAX = true;
  29816. if (this._useParallaxOcclusion) {
  29817. this._defines.PARALLAXOCCLUSION = true;
  29818. }
  29819. }
  29820. if (this._invertNormalMapX) {
  29821. this._defines.INVERTNORMALMAPX = true;
  29822. }
  29823. if (this._invertNormalMapY) {
  29824. this._defines.INVERTNORMALMAPY = true;
  29825. }
  29826. if (scene._mirroredCameraPosition) {
  29827. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  29828. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  29829. }
  29830. this._defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  29831. }
  29832. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29833. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  29834. return false;
  29835. }
  29836. needUVs = true;
  29837. this._defines.REFRACTION = true;
  29838. this._defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  29839. if (this._linkRefractionWithTransparency) {
  29840. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  29841. }
  29842. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  29843. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  29844. if (this._refractionTexture.isPMREM) {
  29845. this._defines.USEPMREMREFRACTION = true;
  29846. }
  29847. }
  29848. }
  29849. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  29850. // Color Grading texure can not be none blocking.
  29851. if (!this._cameraColorGradingTexture.isReady()) {
  29852. return false;
  29853. }
  29854. this._defines.CAMERACOLORGRADING = true;
  29855. }
  29856. if (!this.backFaceCulling && this._twoSidedLighting) {
  29857. this._defines.TWOSIDEDLIGHTING = true;
  29858. }
  29859. }
  29860. this._defines.LDROUTPUT = this._ldrOutput;
  29861. // Effect
  29862. if (scene.clipPlane) {
  29863. this._defines.CLIPPLANE = true;
  29864. }
  29865. this._defines.ALPHATESTVALUE = this._alphaCutOff;
  29866. if (engine.getAlphaTesting() || this._forceAlphaTest) {
  29867. this._defines.ALPHATEST = true;
  29868. }
  29869. if (this._shouldUseAlphaFromAlbedoTexture()) {
  29870. this._defines.ALPHAFROMALBEDO = true;
  29871. }
  29872. if (this._useEmissiveAsIllumination) {
  29873. this._defines.EMISSIVEASILLUMINATION = true;
  29874. }
  29875. if (this.useLogarithmicDepth) {
  29876. this._defines.LOGARITHMICDEPTH = true;
  29877. }
  29878. if (this._cameraContrast != 1) {
  29879. this._defines.CAMERACONTRAST = true;
  29880. }
  29881. if (this._cameraExposure != 1) {
  29882. this._defines.CAMERATONEMAP = true;
  29883. }
  29884. if (this._cameraColorCurves) {
  29885. this._defines.CAMERACOLORCURVES = true;
  29886. }
  29887. // Point size
  29888. if (this.pointsCloud || scene.forcePointsCloud) {
  29889. this._defines.POINTSIZE = true;
  29890. }
  29891. // Fog
  29892. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  29893. this._defines.FOG = true;
  29894. }
  29895. if (BABYLON.StandardMaterial.FresnelEnabled) {
  29896. // Fresnel
  29897. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  29898. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  29899. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  29900. this._defines.OPACITYFRESNEL = true;
  29901. }
  29902. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  29903. this._defines.EMISSIVEFRESNEL = true;
  29904. }
  29905. this._defines.FRESNEL = true;
  29906. }
  29907. }
  29908. if (this._defines.SPECULARTERM && this._useSpecularOverAlpha) {
  29909. this._defines.SPECULAROVERALPHA = true;
  29910. }
  29911. if (this._usePhysicalLightFalloff) {
  29912. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  29913. }
  29914. if (this._useRadianceOverAlpha) {
  29915. this._defines.RADIANCEOVERALPHA = true;
  29916. }
  29917. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  29918. this._defines.METALLICWORKFLOW = true;
  29919. }
  29920. // Attribs
  29921. if (mesh) {
  29922. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29923. mesh.createNormals(true);
  29924. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  29925. }
  29926. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29927. this._defines.NORMAL = true;
  29928. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29929. this._defines.TANGENT = true;
  29930. }
  29931. }
  29932. if (needUVs) {
  29933. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29934. this._defines.UV1 = true;
  29935. }
  29936. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29937. this._defines.UV2 = true;
  29938. }
  29939. }
  29940. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29941. this._defines.VERTEXCOLOR = true;
  29942. if (mesh.hasVertexAlpha) {
  29943. this._defines.VERTEXALPHA = true;
  29944. }
  29945. }
  29946. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29947. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  29948. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  29949. }
  29950. // Instances
  29951. if (useInstances) {
  29952. this._defines.INSTANCES = true;
  29953. }
  29954. if (mesh.morphTargetManager) {
  29955. var manager = mesh.morphTargetManager;
  29956. this._defines.MORPHTARGETS_TANGENT = manager.supportsTangents && this._defines.TANGENT;
  29957. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  29958. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  29959. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  29960. }
  29961. }
  29962. // Get correct effect
  29963. if (!this._defines.isEqual(this._cachedDefines)) {
  29964. this._defines.cloneTo(this._cachedDefines);
  29965. scene.resetCachedMaterial();
  29966. // Fallbacks
  29967. var fallbacks = new BABYLON.EffectFallbacks();
  29968. if (this._defines.REFLECTION) {
  29969. fallbacks.addFallback(0, "REFLECTION");
  29970. }
  29971. if (this._defines.REFRACTION) {
  29972. fallbacks.addFallback(0, "REFRACTION");
  29973. }
  29974. if (this._defines.REFLECTIVITY) {
  29975. fallbacks.addFallback(0, "REFLECTIVITY");
  29976. }
  29977. if (this._defines.BUMP) {
  29978. fallbacks.addFallback(0, "BUMP");
  29979. }
  29980. if (this._defines.PARALLAX) {
  29981. fallbacks.addFallback(1, "PARALLAX");
  29982. }
  29983. if (this._defines.PARALLAXOCCLUSION) {
  29984. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29985. }
  29986. if (this._defines.SPECULAROVERALPHA) {
  29987. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29988. }
  29989. if (this._defines.FOG) {
  29990. fallbacks.addFallback(1, "FOG");
  29991. }
  29992. if (this._defines.POINTSIZE) {
  29993. fallbacks.addFallback(0, "POINTSIZE");
  29994. }
  29995. if (this._defines.LOGARITHMICDEPTH) {
  29996. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29997. }
  29998. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this._maxSimultaneousLights);
  29999. if (this._defines.SPECULARTERM) {
  30000. fallbacks.addFallback(0, "SPECULARTERM");
  30001. }
  30002. if (this._defines.OPACITYFRESNEL) {
  30003. fallbacks.addFallback(1, "OPACITYFRESNEL");
  30004. }
  30005. if (this._defines.EMISSIVEFRESNEL) {
  30006. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  30007. }
  30008. if (this._defines.FRESNEL) {
  30009. fallbacks.addFallback(3, "FRESNEL");
  30010. }
  30011. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  30012. fallbacks.addCPUSkinningFallback(0, mesh);
  30013. }
  30014. //Attributes
  30015. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30016. if (this._defines.NORMAL) {
  30017. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30018. }
  30019. if (this._defines.TANGENT) {
  30020. attribs.push(BABYLON.VertexBuffer.TangentKind);
  30021. }
  30022. if (this._defines.UV1) {
  30023. attribs.push(BABYLON.VertexBuffer.UVKind);
  30024. }
  30025. if (this._defines.UV2) {
  30026. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30027. }
  30028. if (this._defines.VERTEXCOLOR) {
  30029. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30030. }
  30031. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  30032. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  30033. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  30034. // Legacy browser patch
  30035. var join = this._defines.toString();
  30036. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  30037. "vFogInfos", "vFogColor", "pointSize",
  30038. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30039. "mBones",
  30040. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30041. "depthValues",
  30042. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  30043. "vLightingIntensity",
  30044. "logarithmicDepthConstant",
  30045. "vSphericalX", "vSphericalY", "vSphericalZ",
  30046. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  30047. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  30048. "vMicrosurfaceTextureLods",
  30049. "vCameraInfos"
  30050. ];
  30051. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30052. var uniformBuffers = ["Material", "Scene"];
  30053. if (this._defines.CAMERACOLORCURVES) {
  30054. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  30055. }
  30056. if (this._defines.CAMERACOLORGRADING) {
  30057. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  30058. }
  30059. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30060. uniformsNames: uniforms,
  30061. uniformBuffersNames: uniformBuffers,
  30062. samplers: samplers,
  30063. defines: this._defines,
  30064. maxSimultaneousLights: this._maxSimultaneousLights
  30065. });
  30066. var onCompiled = function (effect) {
  30067. if (this.onCompiled) {
  30068. this.onCompiled(effect);
  30069. }
  30070. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  30071. }.bind(this);
  30072. this._effect = scene.getEngine().createEffect("pbr", {
  30073. attributes: attribs,
  30074. uniformsNames: uniforms,
  30075. uniformBuffersNames: uniformBuffers,
  30076. samplers: samplers,
  30077. defines: join,
  30078. fallbacks: fallbacks,
  30079. onCompiled: onCompiled,
  30080. onError: this.onError,
  30081. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS }
  30082. }, engine);
  30083. this.buildUniformLayout();
  30084. }
  30085. if (!this._effect.isReady()) {
  30086. return false;
  30087. }
  30088. this._renderId = scene.getRenderId();
  30089. this._wasPreviouslyReady = true;
  30090. return true;
  30091. };
  30092. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  30093. // Order is important !
  30094. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  30095. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  30096. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  30097. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  30098. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  30099. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  30100. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  30101. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  30102. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  30103. this._uniformBuffer.addUniform("vBumpInfos", 3);
  30104. this._uniformBuffer.addUniform("albedoMatrix", 16);
  30105. this._uniformBuffer.addUniform("ambientMatrix", 16);
  30106. this._uniformBuffer.addUniform("opacityMatrix", 16);
  30107. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  30108. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  30109. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  30110. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  30111. this._uniformBuffer.addUniform("bumpMatrix", 16);
  30112. this._uniformBuffer.addUniform("refractionMatrix", 16);
  30113. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  30114. this._uniformBuffer.addUniform("vReflectionColor", 3);
  30115. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  30116. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  30117. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  30118. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  30119. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  30120. this._uniformBuffer.addUniform("opacityParts", 4);
  30121. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  30122. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  30123. this._uniformBuffer.addUniform("pointSize", 1);
  30124. this._uniformBuffer.create();
  30125. };
  30126. PBRBaseMaterial.prototype.unbind = function () {
  30127. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  30128. this._uniformBuffer.setTexture("reflection2DSampler", null);
  30129. }
  30130. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  30131. this._uniformBuffer.setTexture("refraction2DSampler", null);
  30132. }
  30133. _super.prototype.unbind.call(this);
  30134. };
  30135. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30136. this._effect.setMatrix("world", world);
  30137. };
  30138. PBRBaseMaterial.prototype.bind = function (world, mesh) {
  30139. this._myScene = this.getScene();
  30140. var effect = this._effect;
  30141. // Matrices
  30142. this.bindOnlyWorldMatrix(world);
  30143. // Bones
  30144. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  30145. if (this._myScene.getCachedMaterial() !== this) {
  30146. this._uniformBuffer.bindToEffect(effect, "Material");
  30147. this.bindViewProjection(effect);
  30148. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  30149. // Fresnel
  30150. if (BABYLON.StandardMaterial.FresnelEnabled) {
  30151. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  30152. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this._opacityFresnelParameters.leftColor.toLuminance(), this._opacityFresnelParameters.rightColor.toLuminance(), this._opacityFresnelParameters.bias), this._opacityFresnelParameters.power);
  30153. }
  30154. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  30155. this._uniformBuffer.updateColor4("emissiveLeftColor", this._emissiveFresnelParameters.leftColor, this._emissiveFresnelParameters.power);
  30156. this._uniformBuffer.updateColor4("emissiveRightColor", this._emissiveFresnelParameters.rightColor, this._emissiveFresnelParameters.bias);
  30157. }
  30158. }
  30159. // Texture uniforms
  30160. if (this._myScene.texturesEnabled) {
  30161. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30162. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  30163. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  30164. }
  30165. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30166. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  30167. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  30168. }
  30169. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30170. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  30171. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  30172. }
  30173. var reflectionTexture = this._reflectionTexture || this._myScene.environmentTexture;
  30174. ;
  30175. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30176. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  30177. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  30178. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  30179. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  30180. this._effect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  30181. this._effect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  30182. this._effect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  30183. this._effect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  30184. this._effect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  30185. this._effect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  30186. this._effect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  30187. this._effect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  30188. this._effect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  30189. }
  30190. }
  30191. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30192. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  30193. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  30194. }
  30195. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30196. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  30197. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  30198. }
  30199. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30200. if (this._metallicTexture) {
  30201. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  30202. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  30203. }
  30204. else if (this._reflectivityTexture) {
  30205. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  30206. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  30207. }
  30208. if (this._microSurfaceTexture) {
  30209. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  30210. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  30211. }
  30212. }
  30213. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30214. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  30215. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  30216. }
  30217. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30218. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  30219. var depth = 1.0;
  30220. if (!this._refractionTexture.isCube) {
  30221. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  30222. if (this._refractionTexture.depth) {
  30223. depth = this._refractionTexture.depth;
  30224. }
  30225. }
  30226. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  30227. }
  30228. if ((reflectionTexture || this._refractionTexture)) {
  30229. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  30230. }
  30231. }
  30232. // Point size
  30233. if (this.pointsCloud) {
  30234. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  30235. }
  30236. // Colors
  30237. if (this._defines.METALLICWORKFLOW) {
  30238. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  30239. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  30240. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  30241. }
  30242. else {
  30243. // GAMMA CORRECTION.
  30244. this.convertColorToLinearSpaceToRef(this._reflectivityColor, BABYLON.PBRMaterial._scaledReflectivity);
  30245. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, this._microSurface);
  30246. }
  30247. // GAMMA CORRECTION.
  30248. this.convertColorToLinearSpaceToRef(this._emissiveColor, BABYLON.PBRMaterial._scaledEmissive);
  30249. this._uniformBuffer.updateColor3("vEmissiveColor", BABYLON.PBRMaterial._scaledEmissive);
  30250. // GAMMA CORRECTION.
  30251. this.convertColorToLinearSpaceToRef(this._reflectionColor, BABYLON.PBRMaterial._scaledReflection);
  30252. this._uniformBuffer.updateColor3("vReflectionColor", BABYLON.PBRMaterial._scaledReflection);
  30253. // GAMMA CORRECTION.
  30254. this.convertColorToLinearSpaceToRef(this._albedoColor, BABYLON.PBRMaterial._scaledAlbedo);
  30255. this._uniformBuffer.updateColor4("vAlbedoColor", BABYLON.PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  30256. // Misc
  30257. this._lightingInfos.x = this._directIntensity;
  30258. this._lightingInfos.y = this._emissiveIntensity;
  30259. this._lightingInfos.z = this._environmentIntensity;
  30260. this._lightingInfos.w = this._specularIntensity;
  30261. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  30262. }
  30263. // Textures
  30264. if (this._myScene.texturesEnabled) {
  30265. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30266. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  30267. }
  30268. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30269. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  30270. }
  30271. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30272. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  30273. }
  30274. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30275. if (reflectionTexture.isCube) {
  30276. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  30277. }
  30278. else {
  30279. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  30280. }
  30281. }
  30282. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30283. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  30284. }
  30285. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30286. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  30287. }
  30288. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30289. if (this._metallicTexture) {
  30290. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  30291. }
  30292. else if (this._reflectivityTexture) {
  30293. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  30294. }
  30295. if (this._microSurfaceTexture) {
  30296. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  30297. }
  30298. }
  30299. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30300. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  30301. }
  30302. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30303. if (this._refractionTexture.isCube) {
  30304. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  30305. }
  30306. else {
  30307. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  30308. }
  30309. }
  30310. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  30311. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, this._effect);
  30312. }
  30313. }
  30314. // Clip plane
  30315. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  30316. // Colors
  30317. this._myScene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  30318. effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  30319. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30320. }
  30321. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  30322. // Lights
  30323. if (this._myScene.lightsEnabled && !this._disableLighting) {
  30324. BABYLON.PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this._useScalarInLinearSpace, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  30325. }
  30326. // View
  30327. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  30328. this.bindView(effect);
  30329. }
  30330. // Fog
  30331. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  30332. // Morph targets
  30333. if (this._defines.NUM_MORPH_INFLUENCERS) {
  30334. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  30335. }
  30336. this._cameraInfos.x = this._cameraExposure;
  30337. this._cameraInfos.y = this._cameraContrast;
  30338. effect.setVector4("vCameraInfos", this._cameraInfos);
  30339. if (this._cameraColorCurves) {
  30340. BABYLON.ColorCurves.Bind(this._cameraColorCurves, this._effect);
  30341. }
  30342. // Log. depth
  30343. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  30344. }
  30345. this._uniformBuffer.update();
  30346. this._afterBind(mesh);
  30347. this._myScene = null;
  30348. };
  30349. PBRBaseMaterial.prototype.getAnimatables = function () {
  30350. var results = [];
  30351. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  30352. results.push(this._albedoTexture);
  30353. }
  30354. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  30355. results.push(this._ambientTexture);
  30356. }
  30357. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  30358. results.push(this._opacityTexture);
  30359. }
  30360. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  30361. results.push(this._reflectionTexture);
  30362. }
  30363. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  30364. results.push(this._emissiveTexture);
  30365. }
  30366. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  30367. results.push(this._metallicTexture);
  30368. }
  30369. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  30370. results.push(this._reflectivityTexture);
  30371. }
  30372. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  30373. results.push(this._bumpTexture);
  30374. }
  30375. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  30376. results.push(this._lightmapTexture);
  30377. }
  30378. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  30379. results.push(this._refractionTexture);
  30380. }
  30381. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  30382. results.push(this._cameraColorGradingTexture);
  30383. }
  30384. return results;
  30385. };
  30386. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30387. if (forceDisposeTextures) {
  30388. if (this._albedoTexture) {
  30389. this._albedoTexture.dispose();
  30390. }
  30391. if (this._ambientTexture) {
  30392. this._ambientTexture.dispose();
  30393. }
  30394. if (this._opacityTexture) {
  30395. this._opacityTexture.dispose();
  30396. }
  30397. if (this._reflectionTexture) {
  30398. this._reflectionTexture.dispose();
  30399. }
  30400. if (this._emissiveTexture) {
  30401. this._emissiveTexture.dispose();
  30402. }
  30403. if (this._metallicTexture) {
  30404. this._metallicTexture.dispose();
  30405. }
  30406. if (this._reflectivityTexture) {
  30407. this._reflectivityTexture.dispose();
  30408. }
  30409. if (this._bumpTexture) {
  30410. this._bumpTexture.dispose();
  30411. }
  30412. if (this._lightmapTexture) {
  30413. this._lightmapTexture.dispose();
  30414. }
  30415. if (this._refractionTexture) {
  30416. this._refractionTexture.dispose();
  30417. }
  30418. if (this._cameraColorGradingTexture) {
  30419. this._cameraColorGradingTexture.dispose();
  30420. }
  30421. }
  30422. this._renderTargets.dispose();
  30423. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30424. };
  30425. return PBRBaseMaterial;
  30426. }(BABYLON.Material));
  30427. PBRBaseMaterial._scaledAlbedo = new BABYLON.Color3();
  30428. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  30429. PBRBaseMaterial._scaledEmissive = new BABYLON.Color3();
  30430. PBRBaseMaterial._scaledReflection = new BABYLON.Color3();
  30431. __decorate([
  30432. BABYLON.serialize()
  30433. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  30434. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  30435. })(BABYLON || (BABYLON = {}));
  30436. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  30437. var BABYLON;
  30438. (function (BABYLON) {
  30439. var Internals;
  30440. (function (Internals) {
  30441. /**
  30442. * The Physically based simple base material of BJS.
  30443. *
  30444. * This enables better naming and convention enforcements on top of the pbrMaterial.
  30445. * It is used as the base class for both the specGloss and metalRough conventions.
  30446. */
  30447. var PBRBaseSimpleMaterial = (function (_super) {
  30448. __extends(PBRBaseSimpleMaterial, _super);
  30449. /**
  30450. * Instantiates a new PBRMaterial instance.
  30451. *
  30452. * @param name The material name
  30453. * @param scene The scene the material will be use in.
  30454. */
  30455. function PBRBaseSimpleMaterial(name, scene) {
  30456. var _this = _super.call(this, name, scene) || this;
  30457. /**
  30458. * Number of Simultaneous lights allowed on the material.
  30459. */
  30460. _this.maxSimultaneousLights = 4;
  30461. /**
  30462. * If sets to true, disables all the lights affecting the material.
  30463. */
  30464. _this.disableLighting = false;
  30465. /**
  30466. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30467. */
  30468. _this.invertNormalMapX = false;
  30469. /**
  30470. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30471. */
  30472. _this.invertNormalMapY = false;
  30473. /**
  30474. * Emissivie color used to self-illuminate the model.
  30475. */
  30476. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30477. /**
  30478. * Occlusion Channel Strenght.
  30479. */
  30480. _this.occlusionStrength = 1.0;
  30481. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30482. _this._useEmissiveAsIllumination = true;
  30483. _this._useAmbientInGrayScale = true;
  30484. _this._useScalarInLinearSpace = true;
  30485. return _this;
  30486. }
  30487. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  30488. /**
  30489. * Gets the current transparency mode.
  30490. */
  30491. get: function () {
  30492. return this._transparencyMode;
  30493. },
  30494. /**
  30495. * Sets the transparency mode of the material.
  30496. */
  30497. set: function (value) {
  30498. this._transparencyMode = value;
  30499. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  30500. this._forceAlphaTest = true;
  30501. }
  30502. else {
  30503. this._forceAlphaTest = false;
  30504. }
  30505. },
  30506. enumerable: true,
  30507. configurable: true
  30508. });
  30509. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  30510. /**
  30511. * Gets the current double sided mode.
  30512. */
  30513. get: function () {
  30514. return this._twoSidedLighting;
  30515. },
  30516. /**
  30517. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30518. */
  30519. set: function (value) {
  30520. this._twoSidedLighting = value;
  30521. this.backFaceCulling = !value;
  30522. },
  30523. enumerable: true,
  30524. configurable: true
  30525. });
  30526. /**
  30527. * Specifies wether or not the alpha value of the albedo texture should be used.
  30528. */
  30529. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  30530. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30531. };
  30532. /**
  30533. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  30534. */
  30535. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  30536. if (this._linkRefractionWithTransparency) {
  30537. return false;
  30538. }
  30539. return (this.alpha < 1.0) ||
  30540. (this._shouldUseAlphaFromAlbedoTexture() &&
  30541. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  30542. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  30543. };
  30544. /**
  30545. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  30546. */
  30547. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  30548. if (this._linkRefractionWithTransparency) {
  30549. return false;
  30550. }
  30551. return this._shouldUseAlphaFromAlbedoTexture() &&
  30552. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  30553. };
  30554. return PBRBaseSimpleMaterial;
  30555. }(BABYLON.PBRBaseMaterial));
  30556. __decorate([
  30557. BABYLON.serialize(),
  30558. BABYLON.expandToProperty(null)
  30559. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  30560. __decorate([
  30561. BABYLON.serialize(),
  30562. BABYLON.expandToProperty(null)
  30563. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  30564. __decorate([
  30565. BABYLON.serializeAsTexture(),
  30566. BABYLON.expandToProperty(null, "_reflectionTexture")
  30567. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  30568. __decorate([
  30569. BABYLON.serialize(),
  30570. BABYLON.expandToProperty(null)
  30571. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  30572. __decorate([
  30573. BABYLON.serialize(),
  30574. BABYLON.expandToProperty(null)
  30575. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  30576. __decorate([
  30577. BABYLON.serializeAsTexture(),
  30578. BABYLON.expandToProperty(null, "_bumpTexture")
  30579. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  30580. __decorate([
  30581. BABYLON.serializeAsColor3("emissive"),
  30582. BABYLON.expandToProperty(null)
  30583. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  30584. __decorate([
  30585. BABYLON.serializeAsTexture(),
  30586. BABYLON.expandToProperty(null)
  30587. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  30588. __decorate([
  30589. BABYLON.serialize(),
  30590. BABYLON.expandToProperty(null, "_ambientTextureStrength")
  30591. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  30592. __decorate([
  30593. BABYLON.serializeAsTexture(),
  30594. BABYLON.expandToProperty(null, "_ambientTexture")
  30595. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  30596. __decorate([
  30597. BABYLON.serialize(),
  30598. BABYLON.expandToProperty(null, "_alphaCutOff")
  30599. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  30600. __decorate([
  30601. BABYLON.serialize()
  30602. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  30603. __decorate([
  30604. BABYLON.serialize()
  30605. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  30606. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  30607. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30608. })(BABYLON || (BABYLON = {}));
  30609. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  30610. var BABYLON;
  30611. (function (BABYLON) {
  30612. /**
  30613. * The Physically based material of BJS.
  30614. *
  30615. * This offers the main features of a standard PBR material.
  30616. * For more information, please refer to the documentation :
  30617. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  30618. */
  30619. var PBRMaterial = (function (_super) {
  30620. __extends(PBRMaterial, _super);
  30621. /**
  30622. * Instantiates a new PBRMaterial instance.
  30623. *
  30624. * @param name The material name
  30625. * @param scene The scene the material will be use in.
  30626. */
  30627. function PBRMaterial(name, scene) {
  30628. var _this = _super.call(this, name, scene) || this;
  30629. /**
  30630. * Intensity of the direct lights e.g. the four lights available in your scene.
  30631. * This impacts both the direct diffuse and specular highlights.
  30632. */
  30633. _this.directIntensity = 1.0;
  30634. /**
  30635. * Intensity of the emissive part of the material.
  30636. * This helps controlling the emissive effect without modifying the emissive color.
  30637. */
  30638. _this.emissiveIntensity = 1.0;
  30639. /**
  30640. * Intensity of the environment e.g. how much the environment will light the object
  30641. * either through harmonics for rough material or through the refelction for shiny ones.
  30642. */
  30643. _this.environmentIntensity = 1.0;
  30644. /**
  30645. * This is a special control allowing the reduction of the specular highlights coming from the
  30646. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  30647. */
  30648. _this.specularIntensity = 1.0;
  30649. /**
  30650. * Debug Control allowing disabling the bump map on this material.
  30651. */
  30652. _this.disableBumpMap = false;
  30653. /**
  30654. * The camera exposure used on this material.
  30655. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30656. * This corresponds to a photographic exposure.
  30657. */
  30658. _this.cameraExposure = 1.0;
  30659. /**
  30660. * The camera contrast used on this material.
  30661. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  30662. */
  30663. _this.cameraContrast = 1.0;
  30664. /**
  30665. * Color Grading 2D Lookup Texture.
  30666. * This allows special effects like sepia, black and white to sixties rendering style.
  30667. */
  30668. _this.cameraColorGradingTexture = null;
  30669. /**
  30670. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30671. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30672. * 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;
  30673. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30674. */
  30675. _this.cameraColorCurves = null;
  30676. /**
  30677. * AKA Occlusion Texture Intensity in other nomenclature.
  30678. */
  30679. _this.ambientTextureStrength = 1.0;
  30680. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30681. /**
  30682. * AKA Diffuse Color in other nomenclature.
  30683. */
  30684. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  30685. /**
  30686. * AKA Specular Color in other nomenclature.
  30687. */
  30688. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  30689. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  30690. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30691. /**
  30692. * AKA Glossiness in other nomenclature.
  30693. */
  30694. _this.microSurface = 0.9;
  30695. /**
  30696. * source material index of refraction (IOR)' / 'destination material IOR.
  30697. */
  30698. _this.indexOfRefraction = 0.66;
  30699. /**
  30700. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  30701. */
  30702. _this.invertRefractionY = false;
  30703. /**
  30704. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  30705. * Materials half opaque for instance using refraction could benefit from this control.
  30706. */
  30707. _this.linkRefractionWithTransparency = false;
  30708. _this.useLightmapAsShadowmap = false;
  30709. /**
  30710. * In this mode, the emissive informtaion will always be added to the lighting once.
  30711. * A light for instance can be thought as emissive.
  30712. */
  30713. _this.useEmissiveAsIllumination = false;
  30714. /**
  30715. * Secifies that the alpha is coming form the albedo channel alpha channel.
  30716. */
  30717. _this.useAlphaFromAlbedoTexture = false;
  30718. /**
  30719. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  30720. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  30721. */
  30722. _this.useSpecularOverAlpha = true;
  30723. /**
  30724. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  30725. */
  30726. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  30727. /**
  30728. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  30729. */
  30730. _this.useRoughnessFromMetallicTextureAlpha = true;
  30731. /**
  30732. * Specifies if the metallic texture contains the roughness information in its green channel.
  30733. */
  30734. _this.useRoughnessFromMetallicTextureGreen = false;
  30735. /**
  30736. * Specifies if the metallic texture contains the metallness information in its blue channel.
  30737. */
  30738. _this.useMetallnessFromMetallicTextureBlue = false;
  30739. /**
  30740. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  30741. */
  30742. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  30743. /**
  30744. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  30745. */
  30746. _this.useAmbientInGrayScale = false;
  30747. /**
  30748. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  30749. * The material will try to infer what glossiness each pixel should be.
  30750. */
  30751. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  30752. /**
  30753. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  30754. * the creation of the material.
  30755. */
  30756. _this.useScalarInLinearSpace = false;
  30757. /**
  30758. * BJS is using an harcoded light falloff based on a manually sets up range.
  30759. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  30760. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  30761. */
  30762. _this.usePhysicalLightFalloff = true;
  30763. /**
  30764. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  30765. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  30766. */
  30767. _this.useRadianceOverAlpha = true;
  30768. /**
  30769. * Allows using the bump map in parallax mode.
  30770. */
  30771. _this.useParallax = false;
  30772. /**
  30773. * Allows using the bump map in parallax occlusion mode.
  30774. */
  30775. _this.useParallaxOcclusion = false;
  30776. /**
  30777. * Controls the scale bias of the parallax mode.
  30778. */
  30779. _this.parallaxScaleBias = 0.05;
  30780. /**
  30781. * If sets to true, disables all the lights affecting the material.
  30782. */
  30783. _this.disableLighting = false;
  30784. /**
  30785. * Number of Simultaneous lights allowed on the material.
  30786. */
  30787. _this.maxSimultaneousLights = 4;
  30788. /**
  30789. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30790. */
  30791. _this.invertNormalMapX = false;
  30792. /**
  30793. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30794. */
  30795. _this.invertNormalMapY = false;
  30796. /**
  30797. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30798. */
  30799. _this.twoSidedLighting = false;
  30800. return _this;
  30801. }
  30802. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  30803. /**
  30804. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  30805. */
  30806. get: function () {
  30807. return this._PBRMATERIAL_OPAQUE;
  30808. },
  30809. enumerable: true,
  30810. configurable: true
  30811. });
  30812. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  30813. /**
  30814. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  30815. */
  30816. get: function () {
  30817. return this._PBRMATERIAL_ALPHATEST;
  30818. },
  30819. enumerable: true,
  30820. configurable: true
  30821. });
  30822. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  30823. /**
  30824. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  30825. */
  30826. get: function () {
  30827. return this._PBRMATERIAL_ALPHABLEND;
  30828. },
  30829. enumerable: true,
  30830. configurable: true
  30831. });
  30832. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  30833. /**
  30834. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  30835. * They are also discarded below the alpha cutoff threshold to improve performances.
  30836. */
  30837. get: function () {
  30838. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  30839. },
  30840. enumerable: true,
  30841. configurable: true
  30842. });
  30843. PBRMaterial.prototype.getClassName = function () {
  30844. return "PBRMaterial";
  30845. };
  30846. PBRMaterial.prototype.clone = function (name) {
  30847. var _this = this;
  30848. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  30849. };
  30850. PBRMaterial.prototype.serialize = function () {
  30851. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30852. serializationObject.customType = "BABYLON.PBRMaterial";
  30853. return serializationObject;
  30854. };
  30855. // Statics
  30856. PBRMaterial.Parse = function (source, scene, rootUrl) {
  30857. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  30858. };
  30859. return PBRMaterial;
  30860. }(BABYLON.PBRBaseMaterial));
  30861. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  30862. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  30863. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  30864. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  30865. __decorate([
  30866. BABYLON.serialize(),
  30867. BABYLON.expandToProperty(null)
  30868. ], PBRMaterial.prototype, "directIntensity", void 0);
  30869. __decorate([
  30870. BABYLON.serialize(),
  30871. BABYLON.expandToProperty(null)
  30872. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  30873. __decorate([
  30874. BABYLON.serialize(),
  30875. BABYLON.expandToProperty(null)
  30876. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  30877. __decorate([
  30878. BABYLON.serialize(),
  30879. BABYLON.expandToProperty(null)
  30880. ], PBRMaterial.prototype, "specularIntensity", void 0);
  30881. __decorate([
  30882. BABYLON.serialize(),
  30883. BABYLON.expandToProperty(null)
  30884. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  30885. __decorate([
  30886. BABYLON.serialize(),
  30887. BABYLON.expandToProperty(null)
  30888. ], PBRMaterial.prototype, "cameraExposure", void 0);
  30889. __decorate([
  30890. BABYLON.serialize(),
  30891. BABYLON.expandToProperty(null)
  30892. ], PBRMaterial.prototype, "cameraContrast", void 0);
  30893. __decorate([
  30894. BABYLON.serializeAsTexture(),
  30895. BABYLON.expandToProperty(null)
  30896. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  30897. __decorate([
  30898. BABYLON.serializeAsColorCurves(),
  30899. BABYLON.expandToProperty(null)
  30900. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  30901. __decorate([
  30902. BABYLON.serializeAsTexture(),
  30903. BABYLON.expandToProperty(null)
  30904. ], PBRMaterial.prototype, "albedoTexture", void 0);
  30905. __decorate([
  30906. BABYLON.serializeAsTexture(),
  30907. BABYLON.expandToProperty(null)
  30908. ], PBRMaterial.prototype, "ambientTexture", void 0);
  30909. __decorate([
  30910. BABYLON.serialize(),
  30911. BABYLON.expandToProperty(null)
  30912. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  30913. __decorate([
  30914. BABYLON.serializeAsTexture(),
  30915. BABYLON.expandToProperty(null)
  30916. ], PBRMaterial.prototype, "opacityTexture", void 0);
  30917. __decorate([
  30918. BABYLON.serializeAsTexture(),
  30919. BABYLON.expandToProperty(null)
  30920. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  30921. __decorate([
  30922. BABYLON.serializeAsTexture(),
  30923. BABYLON.expandToProperty(null)
  30924. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  30925. __decorate([
  30926. BABYLON.serializeAsTexture(),
  30927. BABYLON.expandToProperty(null)
  30928. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  30929. __decorate([
  30930. BABYLON.serializeAsTexture(),
  30931. BABYLON.expandToProperty(null)
  30932. ], PBRMaterial.prototype, "metallicTexture", void 0);
  30933. __decorate([
  30934. BABYLON.serialize(),
  30935. BABYLON.expandToProperty(null)
  30936. ], PBRMaterial.prototype, "metallic", void 0);
  30937. __decorate([
  30938. BABYLON.serialize(),
  30939. BABYLON.expandToProperty(null)
  30940. ], PBRMaterial.prototype, "roughness", void 0);
  30941. __decorate([
  30942. BABYLON.serializeAsTexture(),
  30943. BABYLON.expandToProperty(null)
  30944. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  30945. __decorate([
  30946. BABYLON.serializeAsTexture(),
  30947. BABYLON.expandToProperty(null)
  30948. ], PBRMaterial.prototype, "bumpTexture", void 0);
  30949. __decorate([
  30950. BABYLON.serializeAsTexture(),
  30951. BABYLON.expandToProperty(null)
  30952. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  30953. __decorate([
  30954. BABYLON.serializeAsTexture(),
  30955. BABYLON.expandToProperty(null)
  30956. ], PBRMaterial.prototype, "refractionTexture", void 0);
  30957. __decorate([
  30958. BABYLON.serializeAsColor3("ambient"),
  30959. BABYLON.expandToProperty(null)
  30960. ], PBRMaterial.prototype, "ambientColor", void 0);
  30961. __decorate([
  30962. BABYLON.serializeAsColor3("albedo"),
  30963. BABYLON.expandToProperty(null)
  30964. ], PBRMaterial.prototype, "albedoColor", void 0);
  30965. __decorate([
  30966. BABYLON.serializeAsColor3("reflectivity"),
  30967. BABYLON.expandToProperty(null)
  30968. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  30969. __decorate([
  30970. BABYLON.serializeAsColor3("reflection"),
  30971. BABYLON.expandToProperty(null)
  30972. ], PBRMaterial.prototype, "reflectionColor", void 0);
  30973. __decorate([
  30974. BABYLON.serializeAsColor3("emissive"),
  30975. BABYLON.expandToProperty(null)
  30976. ], PBRMaterial.prototype, "emissiveColor", void 0);
  30977. __decorate([
  30978. BABYLON.serialize(),
  30979. BABYLON.expandToProperty(null)
  30980. ], PBRMaterial.prototype, "microSurface", void 0);
  30981. __decorate([
  30982. BABYLON.serialize(),
  30983. BABYLON.expandToProperty(null)
  30984. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  30985. __decorate([
  30986. BABYLON.serialize(),
  30987. BABYLON.expandToProperty(null)
  30988. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  30989. __decorate([
  30990. BABYLON.serializeAsFresnelParameters(),
  30991. BABYLON.expandToProperty(null)
  30992. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  30993. __decorate([
  30994. BABYLON.serializeAsFresnelParameters(),
  30995. BABYLON.expandToProperty(null)
  30996. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  30997. __decorate([
  30998. BABYLON.serialize(),
  30999. BABYLON.expandToProperty(null)
  31000. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  31001. __decorate([
  31002. BABYLON.serialize(),
  31003. BABYLON.expandToProperty(null)
  31004. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31005. __decorate([
  31006. BABYLON.serialize(),
  31007. BABYLON.expandToProperty(null)
  31008. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31009. __decorate([
  31010. BABYLON.serialize(),
  31011. BABYLON.expandToProperty(null)
  31012. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  31013. __decorate([
  31014. BABYLON.serialize(),
  31015. BABYLON.expandToProperty(null)
  31016. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  31017. __decorate([
  31018. BABYLON.serialize(),
  31019. BABYLON.expandToProperty(null)
  31020. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  31021. __decorate([
  31022. BABYLON.serialize(),
  31023. BABYLON.expandToProperty(null)
  31024. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  31025. __decorate([
  31026. BABYLON.serialize(),
  31027. BABYLON.expandToProperty(null)
  31028. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  31029. __decorate([
  31030. BABYLON.serialize(),
  31031. BABYLON.expandToProperty(null)
  31032. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  31033. __decorate([
  31034. BABYLON.serialize(),
  31035. BABYLON.expandToProperty(null)
  31036. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  31037. __decorate([
  31038. BABYLON.serialize(),
  31039. BABYLON.expandToProperty(null)
  31040. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  31041. __decorate([
  31042. BABYLON.serialize(),
  31043. BABYLON.expandToProperty(null)
  31044. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  31045. __decorate([
  31046. BABYLON.serialize(),
  31047. BABYLON.expandToProperty(null)
  31048. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  31049. __decorate([
  31050. BABYLON.serialize(),
  31051. BABYLON.expandToProperty(null)
  31052. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  31053. __decorate([
  31054. BABYLON.serialize(),
  31055. BABYLON.expandToProperty(null)
  31056. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  31057. __decorate([
  31058. BABYLON.serialize(),
  31059. BABYLON.expandToProperty(null)
  31060. ], PBRMaterial.prototype, "useParallax", void 0);
  31061. __decorate([
  31062. BABYLON.serialize(),
  31063. BABYLON.expandToProperty(null)
  31064. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  31065. __decorate([
  31066. BABYLON.serialize(),
  31067. BABYLON.expandToProperty(null)
  31068. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  31069. __decorate([
  31070. BABYLON.serialize(),
  31071. BABYLON.expandToProperty(null)
  31072. ], PBRMaterial.prototype, "disableLighting", void 0);
  31073. __decorate([
  31074. BABYLON.serialize(),
  31075. BABYLON.expandToProperty(null)
  31076. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  31077. __decorate([
  31078. BABYLON.serialize(),
  31079. BABYLON.expandToProperty(null)
  31080. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  31081. __decorate([
  31082. BABYLON.serialize(),
  31083. BABYLON.expandToProperty(null)
  31084. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  31085. __decorate([
  31086. BABYLON.serialize(),
  31087. BABYLON.expandToProperty(null)
  31088. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  31089. BABYLON.PBRMaterial = PBRMaterial;
  31090. })(BABYLON || (BABYLON = {}));
  31091. //# sourceMappingURL=babylon.pbrMaterial.js.map
  31092. var BABYLON;
  31093. (function (BABYLON) {
  31094. /**
  31095. * The PBR material of BJS following the metal roughness convention.
  31096. *
  31097. * This fits to the define PBR convention in the GLTF definition:
  31098. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  31099. */
  31100. var PBRMetallicRoughnessMaterial = (function (_super) {
  31101. __extends(PBRMetallicRoughnessMaterial, _super);
  31102. /**
  31103. * Instantiates a new PBRMetalRoughnessMaterial instance.
  31104. *
  31105. * @param name The material name
  31106. * @param scene The scene the material will be use in.
  31107. */
  31108. function PBRMetallicRoughnessMaterial(name, scene) {
  31109. var _this = _super.call(this, name, scene) || this;
  31110. _this._useRoughnessFromMetallicTextureGreen = true;
  31111. _this._useMetallnessFromMetallicTextureBlue = true;
  31112. return _this;
  31113. }
  31114. /**
  31115. * Return the currrent class name of the material.
  31116. */
  31117. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  31118. return "PBRMetallicRoughnessMaterial";
  31119. };
  31120. /**
  31121. * Serialize the material to a parsable JSON object.
  31122. */
  31123. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  31124. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31125. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  31126. return serializationObject;
  31127. };
  31128. /**
  31129. * Parses a JSON object correponding to the serialize function.
  31130. */
  31131. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  31132. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  31133. };
  31134. return PBRMetallicRoughnessMaterial;
  31135. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31136. __decorate([
  31137. BABYLON.serializeAsTexture(),
  31138. BABYLON.expandToProperty(null, "_albedoColor")
  31139. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  31140. __decorate([
  31141. BABYLON.serializeAsTexture(),
  31142. BABYLON.expandToProperty(null, "_albedoTexture")
  31143. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  31144. __decorate([
  31145. BABYLON.serialize(),
  31146. BABYLON.expandToProperty(null)
  31147. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  31148. __decorate([
  31149. BABYLON.serialize(),
  31150. BABYLON.expandToProperty(null)
  31151. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  31152. __decorate([
  31153. BABYLON.serializeAsTexture(),
  31154. BABYLON.expandToProperty(null, "_metallicTexture")
  31155. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  31156. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  31157. })(BABYLON || (BABYLON = {}));
  31158. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  31159. var BABYLON;
  31160. (function (BABYLON) {
  31161. /**
  31162. * The PBR material of BJS following the specular glossiness convention.
  31163. *
  31164. * This fits to the define PBR convention in the GLTF definition:
  31165. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  31166. */
  31167. var PBRSpecularGlossinessMaterial = (function (_super) {
  31168. __extends(PBRSpecularGlossinessMaterial, _super);
  31169. /**
  31170. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  31171. *
  31172. * @param name The material name
  31173. * @param scene The scene the material will be use in.
  31174. */
  31175. function PBRSpecularGlossinessMaterial(name, scene) {
  31176. var _this = _super.call(this, name, scene) || this;
  31177. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  31178. return _this;
  31179. }
  31180. /**
  31181. * Return the currrent class name of the material.
  31182. */
  31183. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  31184. return "PBRSpecularGlossinessMaterial";
  31185. };
  31186. /**
  31187. * Serialize the material to a parsable JSON object.
  31188. */
  31189. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  31190. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31191. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  31192. return serializationObject;
  31193. };
  31194. /**
  31195. * Parses a JSON object correponding to the serialize function.
  31196. */
  31197. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  31198. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  31199. };
  31200. return PBRSpecularGlossinessMaterial;
  31201. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31202. __decorate([
  31203. BABYLON.serializeAsColor3(),
  31204. BABYLON.expandToProperty(null, "_albedoColor")
  31205. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  31206. __decorate([
  31207. BABYLON.serializeAsTexture(),
  31208. BABYLON.expandToProperty(null, "_albedoTexture")
  31209. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  31210. __decorate([
  31211. BABYLON.serializeAsColor3(),
  31212. BABYLON.expandToProperty(null, "_reflectivityColor")
  31213. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  31214. __decorate([
  31215. BABYLON.serialize(),
  31216. BABYLON.expandToProperty(null, "_microSurface")
  31217. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  31218. __decorate([
  31219. BABYLON.serializeAsTexture(),
  31220. BABYLON.expandToProperty(null, "_reflectivityTexture")
  31221. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  31222. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  31223. })(BABYLON || (BABYLON = {}));
  31224. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  31225. var BABYLON;
  31226. (function (BABYLON) {
  31227. BABYLON.CameraInputTypes = {};
  31228. var CameraInputsManager = (function () {
  31229. function CameraInputsManager(camera) {
  31230. this.attached = {};
  31231. this.camera = camera;
  31232. this.checkInputs = function () { };
  31233. }
  31234. CameraInputsManager.prototype.add = function (input) {
  31235. var type = input.getSimpleName();
  31236. if (this.attached[type]) {
  31237. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31238. return;
  31239. }
  31240. this.attached[type] = input;
  31241. input.camera = this.camera;
  31242. //for checkInputs, we are dynamically creating a function
  31243. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31244. if (input.checkInputs) {
  31245. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31246. }
  31247. if (this.attachedElement) {
  31248. input.attachControl(this.attachedElement);
  31249. }
  31250. };
  31251. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31252. for (var cam in this.attached) {
  31253. var input = this.attached[cam];
  31254. if (input === inputToRemove) {
  31255. input.detachControl(this.attachedElement);
  31256. delete this.attached[cam];
  31257. this.rebuildInputCheck();
  31258. }
  31259. }
  31260. };
  31261. CameraInputsManager.prototype.removeByType = function (inputType) {
  31262. for (var cam in this.attached) {
  31263. var input = this.attached[cam];
  31264. if (input.getTypeName() === inputType) {
  31265. input.detachControl(this.attachedElement);
  31266. delete this.attached[cam];
  31267. this.rebuildInputCheck();
  31268. }
  31269. }
  31270. };
  31271. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31272. var current = this.checkInputs;
  31273. return function () {
  31274. current();
  31275. fn();
  31276. };
  31277. };
  31278. CameraInputsManager.prototype.attachInput = function (input) {
  31279. input.attachControl(this.attachedElement, this.noPreventDefault);
  31280. };
  31281. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31282. if (this.attachedElement) {
  31283. return;
  31284. }
  31285. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31286. this.attachedElement = element;
  31287. this.noPreventDefault = noPreventDefault;
  31288. for (var cam in this.attached) {
  31289. var input = this.attached[cam];
  31290. this.attached[cam].attachControl(element, noPreventDefault);
  31291. }
  31292. };
  31293. CameraInputsManager.prototype.detachElement = function (element) {
  31294. if (this.attachedElement !== element) {
  31295. return;
  31296. }
  31297. for (var cam in this.attached) {
  31298. var input = this.attached[cam];
  31299. this.attached[cam].detachControl(element);
  31300. }
  31301. this.attachedElement = null;
  31302. };
  31303. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31304. this.checkInputs = function () { };
  31305. for (var cam in this.attached) {
  31306. var input = this.attached[cam];
  31307. if (input.checkInputs) {
  31308. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31309. }
  31310. }
  31311. };
  31312. CameraInputsManager.prototype.clear = function () {
  31313. if (this.attachedElement) {
  31314. this.detachElement(this.attachedElement);
  31315. }
  31316. this.attached = {};
  31317. this.attachedElement = null;
  31318. this.checkInputs = function () { };
  31319. };
  31320. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31321. var inputs = {};
  31322. for (var cam in this.attached) {
  31323. var input = this.attached[cam];
  31324. var res = BABYLON.SerializationHelper.Serialize(input);
  31325. inputs[input.getTypeName()] = res;
  31326. }
  31327. serializedCamera.inputsmgr = inputs;
  31328. };
  31329. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31330. var parsedInputs = parsedCamera.inputsmgr;
  31331. if (parsedInputs) {
  31332. this.clear();
  31333. for (var n in parsedInputs) {
  31334. var construct = BABYLON.CameraInputTypes[n];
  31335. if (construct) {
  31336. var parsedinput = parsedInputs[n];
  31337. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31338. this.add(input);
  31339. }
  31340. }
  31341. }
  31342. else {
  31343. //2016-03-08 this part is for managing backward compatibility
  31344. for (var n in this.attached) {
  31345. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  31346. if (construct) {
  31347. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31348. this.remove(this.attached[n]);
  31349. this.add(input);
  31350. }
  31351. }
  31352. }
  31353. };
  31354. return CameraInputsManager;
  31355. }());
  31356. BABYLON.CameraInputsManager = CameraInputsManager;
  31357. })(BABYLON || (BABYLON = {}));
  31358. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31359. var BABYLON;
  31360. (function (BABYLON) {
  31361. var FreeCameraMouseInput = (function () {
  31362. function FreeCameraMouseInput(touchEnabled) {
  31363. if (touchEnabled === void 0) { touchEnabled = true; }
  31364. this.touchEnabled = touchEnabled;
  31365. this.buttons = [0, 1, 2];
  31366. this.angularSensibility = 2000.0;
  31367. }
  31368. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  31369. var _this = this;
  31370. var engine = this.camera.getEngine();
  31371. if (!this._pointerInput) {
  31372. this._pointerInput = function (p, s) {
  31373. var evt = p.event;
  31374. if (!_this.touchEnabled && evt.pointerType === "touch") {
  31375. return;
  31376. }
  31377. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31378. return;
  31379. }
  31380. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31381. try {
  31382. evt.srcElement.setPointerCapture(evt.pointerId);
  31383. }
  31384. catch (e) {
  31385. //Nothing to do with the error. Execution will continue.
  31386. }
  31387. _this.previousPosition = {
  31388. x: evt.clientX,
  31389. y: evt.clientY
  31390. };
  31391. if (!noPreventDefault) {
  31392. evt.preventDefault();
  31393. element.focus();
  31394. }
  31395. }
  31396. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31397. try {
  31398. evt.srcElement.releasePointerCapture(evt.pointerId);
  31399. }
  31400. catch (e) {
  31401. //Nothing to do with the error.
  31402. }
  31403. _this.previousPosition = null;
  31404. if (!noPreventDefault) {
  31405. evt.preventDefault();
  31406. }
  31407. }
  31408. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  31409. if (!_this.previousPosition || engine.isPointerLock) {
  31410. return;
  31411. }
  31412. var offsetX = evt.clientX - _this.previousPosition.x;
  31413. var offsetY = evt.clientY - _this.previousPosition.y;
  31414. if (_this.camera.getScene().useRightHandedSystem) {
  31415. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  31416. }
  31417. else {
  31418. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  31419. }
  31420. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  31421. _this.previousPosition = {
  31422. x: evt.clientX,
  31423. y: evt.clientY
  31424. };
  31425. if (!noPreventDefault) {
  31426. evt.preventDefault();
  31427. }
  31428. }
  31429. };
  31430. }
  31431. this._onMouseMove = function (evt) {
  31432. if (!engine.isPointerLock) {
  31433. return;
  31434. }
  31435. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31436. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31437. if (_this.camera.getScene().useRightHandedSystem) {
  31438. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  31439. }
  31440. else {
  31441. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  31442. }
  31443. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  31444. _this.previousPosition = null;
  31445. if (!noPreventDefault) {
  31446. evt.preventDefault();
  31447. }
  31448. };
  31449. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31450. element.addEventListener("mousemove", this._onMouseMove, false);
  31451. };
  31452. FreeCameraMouseInput.prototype.detachControl = function (element) {
  31453. if (this._observer && element) {
  31454. this.camera.getScene().onPointerObservable.remove(this._observer);
  31455. element.removeEventListener("mousemove", this._onMouseMove);
  31456. this._observer = null;
  31457. this._onMouseMove = null;
  31458. this.previousPosition = null;
  31459. }
  31460. };
  31461. FreeCameraMouseInput.prototype.getTypeName = function () {
  31462. return "FreeCameraMouseInput";
  31463. };
  31464. FreeCameraMouseInput.prototype.getSimpleName = function () {
  31465. return "mouse";
  31466. };
  31467. return FreeCameraMouseInput;
  31468. }());
  31469. __decorate([
  31470. BABYLON.serialize()
  31471. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  31472. __decorate([
  31473. BABYLON.serialize()
  31474. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  31475. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  31476. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  31477. })(BABYLON || (BABYLON = {}));
  31478. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  31479. var BABYLON;
  31480. (function (BABYLON) {
  31481. var FreeCameraKeyboardMoveInput = (function () {
  31482. function FreeCameraKeyboardMoveInput() {
  31483. this._keys = [];
  31484. this.keysUp = [38];
  31485. this.keysDown = [40];
  31486. this.keysLeft = [37];
  31487. this.keysRight = [39];
  31488. }
  31489. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31490. var _this = this;
  31491. if (!this._onKeyDown) {
  31492. element.tabIndex = 1;
  31493. this._onKeyDown = function (evt) {
  31494. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31495. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31496. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31497. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31498. var index = _this._keys.indexOf(evt.keyCode);
  31499. if (index === -1) {
  31500. _this._keys.push(evt.keyCode);
  31501. }
  31502. if (!noPreventDefault) {
  31503. evt.preventDefault();
  31504. }
  31505. }
  31506. };
  31507. this._onKeyUp = function (evt) {
  31508. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31509. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31510. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31511. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31512. var index = _this._keys.indexOf(evt.keyCode);
  31513. if (index >= 0) {
  31514. _this._keys.splice(index, 1);
  31515. }
  31516. if (!noPreventDefault) {
  31517. evt.preventDefault();
  31518. }
  31519. }
  31520. };
  31521. element.addEventListener("keydown", this._onKeyDown, false);
  31522. element.addEventListener("keyup", this._onKeyUp, false);
  31523. BABYLON.Tools.RegisterTopRootEvents([
  31524. { name: "blur", handler: this._onLostFocus }
  31525. ]);
  31526. }
  31527. };
  31528. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31529. if (this._onKeyDown) {
  31530. element.removeEventListener("keydown", this._onKeyDown);
  31531. element.removeEventListener("keyup", this._onKeyUp);
  31532. BABYLON.Tools.UnregisterTopRootEvents([
  31533. { name: "blur", handler: this._onLostFocus }
  31534. ]);
  31535. this._keys = [];
  31536. this._onKeyDown = null;
  31537. this._onKeyUp = null;
  31538. }
  31539. };
  31540. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31541. if (this._onKeyDown) {
  31542. var camera = this.camera;
  31543. // Keyboard
  31544. for (var index = 0; index < this._keys.length; index++) {
  31545. var keyCode = this._keys[index];
  31546. var speed = camera._computeLocalCameraSpeed();
  31547. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31548. camera._localDirection.copyFromFloats(-speed, 0, 0);
  31549. }
  31550. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31551. camera._localDirection.copyFromFloats(0, 0, speed);
  31552. }
  31553. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31554. camera._localDirection.copyFromFloats(speed, 0, 0);
  31555. }
  31556. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31557. camera._localDirection.copyFromFloats(0, 0, -speed);
  31558. }
  31559. if (camera.getScene().useRightHandedSystem) {
  31560. camera._localDirection.z *= -1;
  31561. }
  31562. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  31563. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  31564. camera.cameraDirection.addInPlace(camera._transformedDirection);
  31565. }
  31566. }
  31567. };
  31568. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  31569. return "FreeCameraKeyboardMoveInput";
  31570. };
  31571. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  31572. this._keys = [];
  31573. };
  31574. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31575. return "keyboard";
  31576. };
  31577. return FreeCameraKeyboardMoveInput;
  31578. }());
  31579. __decorate([
  31580. BABYLON.serialize()
  31581. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31582. __decorate([
  31583. BABYLON.serialize()
  31584. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  31585. __decorate([
  31586. BABYLON.serialize()
  31587. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  31588. __decorate([
  31589. BABYLON.serialize()
  31590. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  31591. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  31592. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  31593. })(BABYLON || (BABYLON = {}));
  31594. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  31595. var BABYLON;
  31596. (function (BABYLON) {
  31597. var FreeCameraInputsManager = (function (_super) {
  31598. __extends(FreeCameraInputsManager, _super);
  31599. function FreeCameraInputsManager(camera) {
  31600. return _super.call(this, camera) || this;
  31601. }
  31602. FreeCameraInputsManager.prototype.addKeyboard = function () {
  31603. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  31604. return this;
  31605. };
  31606. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  31607. if (touchEnabled === void 0) { touchEnabled = true; }
  31608. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  31609. return this;
  31610. };
  31611. FreeCameraInputsManager.prototype.addGamepad = function () {
  31612. this.add(new BABYLON.FreeCameraGamepadInput());
  31613. return this;
  31614. };
  31615. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  31616. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  31617. return this;
  31618. };
  31619. FreeCameraInputsManager.prototype.addTouch = function () {
  31620. this.add(new BABYLON.FreeCameraTouchInput());
  31621. return this;
  31622. };
  31623. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  31624. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  31625. return this;
  31626. };
  31627. return FreeCameraInputsManager;
  31628. }(BABYLON.CameraInputsManager));
  31629. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  31630. })(BABYLON || (BABYLON = {}));
  31631. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  31632. /// <reference path="babylon.camera.ts" />
  31633. var BABYLON;
  31634. (function (BABYLON) {
  31635. var TargetCamera = (function (_super) {
  31636. __extends(TargetCamera, _super);
  31637. function TargetCamera(name, position, scene) {
  31638. var _this = _super.call(this, name, position, scene) || this;
  31639. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31640. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31641. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31642. _this.speed = 2.0;
  31643. _this.noRotationConstraint = false;
  31644. _this.lockedTarget = null;
  31645. _this._currentTarget = BABYLON.Vector3.Zero();
  31646. _this._viewMatrix = BABYLON.Matrix.Zero();
  31647. _this._camMatrix = BABYLON.Matrix.Zero();
  31648. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31649. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31650. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31651. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31652. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31653. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31654. _this._tempMatrix = BABYLON.Matrix.Zero();
  31655. return _this;
  31656. }
  31657. TargetCamera.prototype.getFrontPosition = function (distance) {
  31658. var direction = this.getTarget().subtract(this.position);
  31659. direction.normalize();
  31660. direction.scaleInPlace(distance);
  31661. return this.globalPosition.add(direction);
  31662. };
  31663. TargetCamera.prototype._getLockedTargetPosition = function () {
  31664. if (!this.lockedTarget) {
  31665. return null;
  31666. }
  31667. if (this.lockedTarget.absolutePosition) {
  31668. this.lockedTarget.computeWorldMatrix();
  31669. }
  31670. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31671. };
  31672. // Cache
  31673. TargetCamera.prototype._initCache = function () {
  31674. _super.prototype._initCache.call(this);
  31675. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31676. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31677. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31678. };
  31679. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31680. if (!ignoreParentClass) {
  31681. _super.prototype._updateCache.call(this);
  31682. }
  31683. var lockedTargetPosition = this._getLockedTargetPosition();
  31684. if (!lockedTargetPosition) {
  31685. this._cache.lockedTarget = null;
  31686. }
  31687. else {
  31688. if (!this._cache.lockedTarget) {
  31689. this._cache.lockedTarget = lockedTargetPosition.clone();
  31690. }
  31691. else {
  31692. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31693. }
  31694. }
  31695. this._cache.rotation.copyFrom(this.rotation);
  31696. if (this.rotationQuaternion)
  31697. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31698. };
  31699. // Synchronized
  31700. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31701. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31702. return false;
  31703. }
  31704. var lockedTargetPosition = this._getLockedTargetPosition();
  31705. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31706. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31707. };
  31708. // Methods
  31709. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31710. var engine = this.getEngine();
  31711. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31712. };
  31713. // Target
  31714. TargetCamera.prototype.setTarget = function (target) {
  31715. this.upVector.normalize();
  31716. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31717. this._camMatrix.invert();
  31718. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31719. var vDir = target.subtract(this.position);
  31720. if (vDir.x >= 0.0) {
  31721. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31722. }
  31723. else {
  31724. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31725. }
  31726. this.rotation.z = 0;
  31727. if (isNaN(this.rotation.x)) {
  31728. this.rotation.x = 0;
  31729. }
  31730. if (isNaN(this.rotation.y)) {
  31731. this.rotation.y = 0;
  31732. }
  31733. if (isNaN(this.rotation.z)) {
  31734. this.rotation.z = 0;
  31735. }
  31736. if (this.rotationQuaternion) {
  31737. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31738. }
  31739. };
  31740. /**
  31741. * Return the current target position of the camera. This value is expressed in local space.
  31742. */
  31743. TargetCamera.prototype.getTarget = function () {
  31744. return this._currentTarget;
  31745. };
  31746. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31747. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31748. };
  31749. TargetCamera.prototype._updatePosition = function () {
  31750. if (this.parent) {
  31751. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31752. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31753. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31754. return;
  31755. }
  31756. this.position.addInPlace(this.cameraDirection);
  31757. };
  31758. TargetCamera.prototype._checkInputs = function () {
  31759. var needToMove = this._decideIfNeedsToMove();
  31760. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31761. // Move
  31762. if (needToMove) {
  31763. this._updatePosition();
  31764. }
  31765. // Rotate
  31766. if (needToRotate) {
  31767. this.rotation.x += this.cameraRotation.x;
  31768. this.rotation.y += this.cameraRotation.y;
  31769. //rotate, if quaternion is set and rotation was used
  31770. if (this.rotationQuaternion) {
  31771. var len = this.rotation.lengthSquared();
  31772. if (len) {
  31773. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31774. }
  31775. }
  31776. if (!this.noRotationConstraint) {
  31777. var limit = (Math.PI / 2) * 0.95;
  31778. if (this.rotation.x > limit)
  31779. this.rotation.x = limit;
  31780. if (this.rotation.x < -limit)
  31781. this.rotation.x = -limit;
  31782. }
  31783. }
  31784. // Inertia
  31785. if (needToMove) {
  31786. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31787. this.cameraDirection.x = 0;
  31788. }
  31789. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31790. this.cameraDirection.y = 0;
  31791. }
  31792. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31793. this.cameraDirection.z = 0;
  31794. }
  31795. this.cameraDirection.scaleInPlace(this.inertia);
  31796. }
  31797. if (needToRotate) {
  31798. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31799. this.cameraRotation.x = 0;
  31800. }
  31801. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31802. this.cameraRotation.y = 0;
  31803. }
  31804. this.cameraRotation.scaleInPlace(this.inertia);
  31805. }
  31806. _super.prototype._checkInputs.call(this);
  31807. };
  31808. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31809. if (this.rotationQuaternion) {
  31810. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31811. //update the up vector!
  31812. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31813. }
  31814. else {
  31815. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31816. }
  31817. };
  31818. TargetCamera.prototype._getViewMatrix = function () {
  31819. if (!this.lockedTarget) {
  31820. // Compute
  31821. this._updateCameraRotationMatrix();
  31822. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31823. // Computing target and final matrix
  31824. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31825. }
  31826. else {
  31827. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31828. }
  31829. if (this.getScene().useRightHandedSystem) {
  31830. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31831. }
  31832. else {
  31833. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31834. }
  31835. return this._viewMatrix;
  31836. };
  31837. /**
  31838. * @override
  31839. * Override Camera.createRigCamera
  31840. */
  31841. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31842. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31843. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31844. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31845. if (!this.rotationQuaternion) {
  31846. this.rotationQuaternion = new BABYLON.Quaternion();
  31847. }
  31848. rigCamera._cameraRigParams = {};
  31849. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31850. }
  31851. return rigCamera;
  31852. }
  31853. return null;
  31854. };
  31855. /**
  31856. * @override
  31857. * Override Camera._updateRigCameras
  31858. */
  31859. TargetCamera.prototype._updateRigCameras = function () {
  31860. var camLeft = this._rigCameras[0];
  31861. var camRight = this._rigCameras[1];
  31862. switch (this.cameraRigMode) {
  31863. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31864. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31865. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31866. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31867. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31868. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31869. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31870. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31871. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31872. camLeft.setTarget(this.getTarget());
  31873. camRight.setTarget(this.getTarget());
  31874. break;
  31875. case BABYLON.Camera.RIG_MODE_VR:
  31876. if (camLeft.rotationQuaternion) {
  31877. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31878. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31879. }
  31880. else {
  31881. camLeft.rotation.copyFrom(this.rotation);
  31882. camRight.rotation.copyFrom(this.rotation);
  31883. }
  31884. camLeft.position.copyFrom(this.position);
  31885. camRight.position.copyFrom(this.position);
  31886. break;
  31887. }
  31888. _super.prototype._updateRigCameras.call(this);
  31889. };
  31890. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  31891. if (!this._rigCamTransformMatrix) {
  31892. this._rigCamTransformMatrix = new BABYLON.Matrix();
  31893. }
  31894. var target = this.getTarget();
  31895. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  31896. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  31897. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  31898. };
  31899. TargetCamera.prototype.getClassName = function () {
  31900. return "TargetCamera";
  31901. };
  31902. return TargetCamera;
  31903. }(BABYLON.Camera));
  31904. __decorate([
  31905. BABYLON.serializeAsVector3()
  31906. ], TargetCamera.prototype, "rotation", void 0);
  31907. __decorate([
  31908. BABYLON.serialize()
  31909. ], TargetCamera.prototype, "speed", void 0);
  31910. __decorate([
  31911. BABYLON.serializeAsMeshReference("lockedTargetId")
  31912. ], TargetCamera.prototype, "lockedTarget", void 0);
  31913. BABYLON.TargetCamera = TargetCamera;
  31914. })(BABYLON || (BABYLON = {}));
  31915. //# sourceMappingURL=babylon.targetCamera.js.map
  31916. var BABYLON;
  31917. (function (BABYLON) {
  31918. var FreeCamera = (function (_super) {
  31919. __extends(FreeCamera, _super);
  31920. function FreeCamera(name, position, scene) {
  31921. var _this = _super.call(this, name, position, scene) || this;
  31922. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  31923. _this.checkCollisions = false;
  31924. _this.applyGravity = false;
  31925. _this._needMoveForGravity = false;
  31926. _this._oldPosition = BABYLON.Vector3.Zero();
  31927. _this._diffPosition = BABYLON.Vector3.Zero();
  31928. _this._newPosition = BABYLON.Vector3.Zero();
  31929. // Collisions
  31930. _this._collisionMask = -1;
  31931. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  31932. if (collidedMesh === void 0) { collidedMesh = null; }
  31933. //TODO move this to the collision coordinator!
  31934. if (_this.getScene().workerCollisions)
  31935. newPosition.multiplyInPlace(_this._collider.radius);
  31936. var updatePosition = function (newPos) {
  31937. _this._newPosition.copyFrom(newPos);
  31938. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  31939. var oldPosition = _this.position.clone();
  31940. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  31941. _this.position.addInPlace(_this._diffPosition);
  31942. if (_this.onCollide && collidedMesh) {
  31943. _this.onCollide(collidedMesh);
  31944. }
  31945. }
  31946. };
  31947. updatePosition(newPosition);
  31948. };
  31949. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  31950. _this.inputs.addKeyboard().addMouse();
  31951. return _this;
  31952. }
  31953. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  31954. //-- begin properties for backward compatibility for inputs
  31955. get: function () {
  31956. var mouse = this.inputs.attached["mouse"];
  31957. if (mouse)
  31958. return mouse.angularSensibility;
  31959. },
  31960. set: function (value) {
  31961. var mouse = this.inputs.attached["mouse"];
  31962. if (mouse)
  31963. mouse.angularSensibility = value;
  31964. },
  31965. enumerable: true,
  31966. configurable: true
  31967. });
  31968. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  31969. get: function () {
  31970. var keyboard = this.inputs.attached["keyboard"];
  31971. if (keyboard)
  31972. return keyboard.keysUp;
  31973. },
  31974. set: function (value) {
  31975. var keyboard = this.inputs.attached["keyboard"];
  31976. if (keyboard)
  31977. keyboard.keysUp = value;
  31978. },
  31979. enumerable: true,
  31980. configurable: true
  31981. });
  31982. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  31983. get: function () {
  31984. var keyboard = this.inputs.attached["keyboard"];
  31985. if (keyboard)
  31986. return keyboard.keysDown;
  31987. },
  31988. set: function (value) {
  31989. var keyboard = this.inputs.attached["keyboard"];
  31990. if (keyboard)
  31991. keyboard.keysDown = value;
  31992. },
  31993. enumerable: true,
  31994. configurable: true
  31995. });
  31996. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  31997. get: function () {
  31998. var keyboard = this.inputs.attached["keyboard"];
  31999. if (keyboard)
  32000. return keyboard.keysLeft;
  32001. },
  32002. set: function (value) {
  32003. var keyboard = this.inputs.attached["keyboard"];
  32004. if (keyboard)
  32005. keyboard.keysLeft = value;
  32006. },
  32007. enumerable: true,
  32008. configurable: true
  32009. });
  32010. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  32011. get: function () {
  32012. var keyboard = this.inputs.attached["keyboard"];
  32013. if (keyboard)
  32014. return keyboard.keysRight;
  32015. },
  32016. set: function (value) {
  32017. var keyboard = this.inputs.attached["keyboard"];
  32018. if (keyboard)
  32019. keyboard.keysRight = value;
  32020. },
  32021. enumerable: true,
  32022. configurable: true
  32023. });
  32024. // Controls
  32025. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32026. this.inputs.attachElement(element, noPreventDefault);
  32027. };
  32028. FreeCamera.prototype.detachControl = function (element) {
  32029. this.inputs.detachElement(element);
  32030. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  32031. this.cameraRotation = new BABYLON.Vector2(0, 0);
  32032. };
  32033. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  32034. get: function () {
  32035. return this._collisionMask;
  32036. },
  32037. set: function (mask) {
  32038. this._collisionMask = !isNaN(mask) ? mask : -1;
  32039. },
  32040. enumerable: true,
  32041. configurable: true
  32042. });
  32043. FreeCamera.prototype._collideWithWorld = function (velocity) {
  32044. var globalPosition;
  32045. if (this.parent) {
  32046. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  32047. }
  32048. else {
  32049. globalPosition = this.position;
  32050. }
  32051. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  32052. if (!this._collider) {
  32053. this._collider = new BABYLON.Collider();
  32054. }
  32055. this._collider.radius = this.ellipsoid;
  32056. this._collider.collisionMask = this._collisionMask;
  32057. //no need for clone, as long as gravity is not on.
  32058. var actualVelocity = velocity;
  32059. //add gravity to the velocity to prevent the dual-collision checking
  32060. if (this.applyGravity) {
  32061. //this prevents mending with cameraDirection, a global variable of the free camera class.
  32062. actualVelocity = velocity.add(this.getScene().gravity);
  32063. }
  32064. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32065. };
  32066. FreeCamera.prototype._checkInputs = function () {
  32067. if (!this._localDirection) {
  32068. this._localDirection = BABYLON.Vector3.Zero();
  32069. this._transformedDirection = BABYLON.Vector3.Zero();
  32070. }
  32071. this.inputs.checkInputs();
  32072. _super.prototype._checkInputs.call(this);
  32073. };
  32074. FreeCamera.prototype._decideIfNeedsToMove = function () {
  32075. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  32076. };
  32077. FreeCamera.prototype._updatePosition = function () {
  32078. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  32079. this._collideWithWorld(this.cameraDirection);
  32080. }
  32081. else {
  32082. _super.prototype._updatePosition.call(this);
  32083. }
  32084. };
  32085. FreeCamera.prototype.dispose = function () {
  32086. this.inputs.clear();
  32087. _super.prototype.dispose.call(this);
  32088. };
  32089. FreeCamera.prototype.getClassName = function () {
  32090. return "FreeCamera";
  32091. };
  32092. return FreeCamera;
  32093. }(BABYLON.TargetCamera));
  32094. __decorate([
  32095. BABYLON.serializeAsVector3()
  32096. ], FreeCamera.prototype, "ellipsoid", void 0);
  32097. __decorate([
  32098. BABYLON.serialize()
  32099. ], FreeCamera.prototype, "checkCollisions", void 0);
  32100. __decorate([
  32101. BABYLON.serialize()
  32102. ], FreeCamera.prototype, "applyGravity", void 0);
  32103. BABYLON.FreeCamera = FreeCamera;
  32104. })(BABYLON || (BABYLON = {}));
  32105. //# sourceMappingURL=babylon.freeCamera.js.map
  32106. var BABYLON;
  32107. (function (BABYLON) {
  32108. var ArcRotateCameraKeyboardMoveInput = (function () {
  32109. function ArcRotateCameraKeyboardMoveInput() {
  32110. this._keys = [];
  32111. this.keysUp = [38];
  32112. this.keysDown = [40];
  32113. this.keysLeft = [37];
  32114. this.keysRight = [39];
  32115. }
  32116. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  32117. var _this = this;
  32118. element.tabIndex = 1;
  32119. this._onKeyDown = function (evt) {
  32120. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32121. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32122. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32123. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32124. var index = _this._keys.indexOf(evt.keyCode);
  32125. if (index === -1) {
  32126. _this._keys.push(evt.keyCode);
  32127. }
  32128. if (evt.preventDefault) {
  32129. if (!noPreventDefault) {
  32130. evt.preventDefault();
  32131. }
  32132. }
  32133. }
  32134. };
  32135. this._onKeyUp = function (evt) {
  32136. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32137. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32138. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32139. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32140. var index = _this._keys.indexOf(evt.keyCode);
  32141. if (index >= 0) {
  32142. _this._keys.splice(index, 1);
  32143. }
  32144. if (evt.preventDefault) {
  32145. if (!noPreventDefault) {
  32146. evt.preventDefault();
  32147. }
  32148. }
  32149. }
  32150. };
  32151. this._onLostFocus = function () {
  32152. _this._keys = [];
  32153. };
  32154. element.addEventListener("keydown", this._onKeyDown, false);
  32155. element.addEventListener("keyup", this._onKeyUp, false);
  32156. BABYLON.Tools.RegisterTopRootEvents([
  32157. { name: "blur", handler: this._onLostFocus }
  32158. ]);
  32159. };
  32160. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  32161. if (element) {
  32162. element.removeEventListener("keydown", this._onKeyDown);
  32163. element.removeEventListener("keyup", this._onKeyUp);
  32164. }
  32165. BABYLON.Tools.UnregisterTopRootEvents([
  32166. { name: "blur", handler: this._onLostFocus }
  32167. ]);
  32168. this._keys = [];
  32169. this._onKeyDown = null;
  32170. this._onKeyUp = null;
  32171. this._onLostFocus = null;
  32172. };
  32173. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  32174. if (this._onKeyDown) {
  32175. var camera = this.camera;
  32176. for (var index = 0; index < this._keys.length; index++) {
  32177. var keyCode = this._keys[index];
  32178. if (this.keysLeft.indexOf(keyCode) !== -1) {
  32179. camera.inertialAlphaOffset -= 0.01;
  32180. }
  32181. else if (this.keysUp.indexOf(keyCode) !== -1) {
  32182. camera.inertialBetaOffset -= 0.01;
  32183. }
  32184. else if (this.keysRight.indexOf(keyCode) !== -1) {
  32185. camera.inertialAlphaOffset += 0.01;
  32186. }
  32187. else if (this.keysDown.indexOf(keyCode) !== -1) {
  32188. camera.inertialBetaOffset += 0.01;
  32189. }
  32190. }
  32191. }
  32192. };
  32193. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  32194. return "ArcRotateCameraKeyboardMoveInput";
  32195. };
  32196. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  32197. return "keyboard";
  32198. };
  32199. return ArcRotateCameraKeyboardMoveInput;
  32200. }());
  32201. __decorate([
  32202. BABYLON.serialize()
  32203. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  32204. __decorate([
  32205. BABYLON.serialize()
  32206. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32207. __decorate([
  32208. BABYLON.serialize()
  32209. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32210. __decorate([
  32211. BABYLON.serialize()
  32212. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32213. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  32214. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  32215. })(BABYLON || (BABYLON = {}));
  32216. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  32217. var BABYLON;
  32218. (function (BABYLON) {
  32219. var ArcRotateCameraMouseWheelInput = (function () {
  32220. function ArcRotateCameraMouseWheelInput() {
  32221. this.wheelPrecision = 3.0;
  32222. }
  32223. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  32224. var _this = this;
  32225. this._wheel = function (p, s) {
  32226. //sanity check - this should be a PointerWheel event.
  32227. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  32228. return;
  32229. var event = p.event;
  32230. var delta = 0;
  32231. if (event.wheelDelta) {
  32232. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  32233. }
  32234. else if (event.detail) {
  32235. delta = -event.detail / _this.wheelPrecision;
  32236. }
  32237. if (delta)
  32238. _this.camera.inertialRadiusOffset += delta;
  32239. if (event.preventDefault) {
  32240. if (!noPreventDefault) {
  32241. event.preventDefault();
  32242. }
  32243. }
  32244. };
  32245. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  32246. };
  32247. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  32248. if (this._observer && element) {
  32249. this.camera.getScene().onPointerObservable.remove(this._observer);
  32250. this._observer = null;
  32251. this._wheel = null;
  32252. }
  32253. };
  32254. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  32255. return "ArcRotateCameraMouseWheelInput";
  32256. };
  32257. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  32258. return "mousewheel";
  32259. };
  32260. return ArcRotateCameraMouseWheelInput;
  32261. }());
  32262. __decorate([
  32263. BABYLON.serialize()
  32264. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  32265. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  32266. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  32267. })(BABYLON || (BABYLON = {}));
  32268. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  32269. var BABYLON;
  32270. (function (BABYLON) {
  32271. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  32272. var ArcRotateCameraPointersInput = (function () {
  32273. function ArcRotateCameraPointersInput() {
  32274. this.buttons = [0, 1, 2];
  32275. this.angularSensibilityX = 1000.0;
  32276. this.angularSensibilityY = 1000.0;
  32277. this.pinchPrecision = 6.0;
  32278. this.panningSensibility = 50.0;
  32279. this._isPanClick = false;
  32280. this.pinchInwards = true;
  32281. }
  32282. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  32283. var _this = this;
  32284. var engine = this.camera.getEngine();
  32285. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  32286. var pointA, pointB;
  32287. var previousPinchDistance = 0;
  32288. this._pointerInput = function (p, s) {
  32289. var evt = p.event;
  32290. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  32291. return;
  32292. }
  32293. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  32294. try {
  32295. evt.srcElement.setPointerCapture(evt.pointerId);
  32296. }
  32297. catch (e) {
  32298. //Nothing to do with the error. Execution will continue.
  32299. }
  32300. // Manage panning with pan button click
  32301. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  32302. // manage pointers
  32303. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  32304. if (pointA === undefined) {
  32305. pointA = cacheSoloPointer;
  32306. }
  32307. else if (pointB === undefined) {
  32308. pointB = cacheSoloPointer;
  32309. }
  32310. if (!noPreventDefault) {
  32311. evt.preventDefault();
  32312. element.focus();
  32313. }
  32314. }
  32315. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  32316. try {
  32317. evt.srcElement.releasePointerCapture(evt.pointerId);
  32318. }
  32319. catch (e) {
  32320. //Nothing to do with the error.
  32321. }
  32322. cacheSoloPointer = null;
  32323. previousPinchDistance = 0;
  32324. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  32325. //but emptying completly pointers collection is required to fix a bug on iPhone :
  32326. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  32327. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  32328. pointA = pointB = undefined;
  32329. if (!noPreventDefault) {
  32330. evt.preventDefault();
  32331. }
  32332. }
  32333. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32334. if (!noPreventDefault) {
  32335. evt.preventDefault();
  32336. }
  32337. // One button down
  32338. if (pointA && pointB === undefined) {
  32339. if (_this.panningSensibility !== 0 &&
  32340. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  32341. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  32342. _this.camera
  32343. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  32344. _this.camera
  32345. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  32346. }
  32347. else {
  32348. var offsetX = evt.clientX - cacheSoloPointer.x;
  32349. var offsetY = evt.clientY - cacheSoloPointer.y;
  32350. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32351. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32352. }
  32353. cacheSoloPointer.x = evt.clientX;
  32354. cacheSoloPointer.y = evt.clientY;
  32355. }
  32356. else if (pointA && pointB) {
  32357. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  32358. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  32359. ed.x = evt.clientX;
  32360. ed.y = evt.clientY;
  32361. var direction = _this.pinchInwards ? 1 : -1;
  32362. var distX = pointA.x - pointB.x;
  32363. var distY = pointA.y - pointB.y;
  32364. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  32365. if (previousPinchDistance === 0) {
  32366. previousPinchDistance = pinchSquaredDistance;
  32367. return;
  32368. }
  32369. if (pinchSquaredDistance !== previousPinchDistance) {
  32370. _this.camera
  32371. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  32372. (_this.pinchPrecision *
  32373. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  32374. direction);
  32375. previousPinchDistance = pinchSquaredDistance;
  32376. }
  32377. }
  32378. }
  32379. };
  32380. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  32381. this._onContextMenu = function (evt) {
  32382. evt.preventDefault();
  32383. };
  32384. if (!this.camera._useCtrlForPanning) {
  32385. element.addEventListener("contextmenu", this._onContextMenu, false);
  32386. }
  32387. this._onLostFocus = function () {
  32388. //this._keys = [];
  32389. pointA = pointB = undefined;
  32390. previousPinchDistance = 0;
  32391. cacheSoloPointer = null;
  32392. };
  32393. this._onMouseMove = function (evt) {
  32394. if (!engine.isPointerLock) {
  32395. return;
  32396. }
  32397. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32398. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32399. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32400. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32401. if (!noPreventDefault) {
  32402. evt.preventDefault();
  32403. }
  32404. };
  32405. this._onGestureStart = function (e) {
  32406. if (window.MSGesture === undefined) {
  32407. return;
  32408. }
  32409. if (!_this._MSGestureHandler) {
  32410. _this._MSGestureHandler = new MSGesture();
  32411. _this._MSGestureHandler.target = element;
  32412. }
  32413. _this._MSGestureHandler.addPointer(e.pointerId);
  32414. };
  32415. this._onGesture = function (e) {
  32416. _this.camera.radius *= e.scale;
  32417. if (e.preventDefault) {
  32418. if (!noPreventDefault) {
  32419. e.stopPropagation();
  32420. e.preventDefault();
  32421. }
  32422. }
  32423. };
  32424. element.addEventListener("mousemove", this._onMouseMove, false);
  32425. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  32426. element.addEventListener("MSGestureChange", this._onGesture, false);
  32427. BABYLON.Tools.RegisterTopRootEvents([
  32428. { name: "blur", handler: this._onLostFocus }
  32429. ]);
  32430. };
  32431. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  32432. if (element && this._observer) {
  32433. this.camera.getScene().onPointerObservable.remove(this._observer);
  32434. this._observer = null;
  32435. element.removeEventListener("contextmenu", this._onContextMenu);
  32436. element.removeEventListener("mousemove", this._onMouseMove);
  32437. element.removeEventListener("MSPointerDown", this._onGestureStart);
  32438. element.removeEventListener("MSGestureChange", this._onGesture);
  32439. this._isPanClick = false;
  32440. this.pinchInwards = true;
  32441. this._onMouseMove = null;
  32442. this._onGestureStart = null;
  32443. this._onGesture = null;
  32444. this._MSGestureHandler = null;
  32445. this._onLostFocus = null;
  32446. this._onContextMenu = null;
  32447. }
  32448. BABYLON.Tools.UnregisterTopRootEvents([
  32449. { name: "blur", handler: this._onLostFocus }
  32450. ]);
  32451. };
  32452. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  32453. return "ArcRotateCameraPointersInput";
  32454. };
  32455. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  32456. return "pointers";
  32457. };
  32458. return ArcRotateCameraPointersInput;
  32459. }());
  32460. __decorate([
  32461. BABYLON.serialize()
  32462. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  32463. __decorate([
  32464. BABYLON.serialize()
  32465. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  32466. __decorate([
  32467. BABYLON.serialize()
  32468. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  32469. __decorate([
  32470. BABYLON.serialize()
  32471. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  32472. __decorate([
  32473. BABYLON.serialize()
  32474. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  32475. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  32476. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  32477. })(BABYLON || (BABYLON = {}));
  32478. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  32479. /// <reference path="babylon.targetCamera.ts" />
  32480. /// <reference path="..\Tools\babylon.tools.ts" />
  32481. var BABYLON;
  32482. (function (BABYLON) {
  32483. var ArcRotateCamera = (function (_super) {
  32484. __extends(ArcRotateCamera, _super);
  32485. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  32486. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  32487. _this.inertialAlphaOffset = 0;
  32488. _this.inertialBetaOffset = 0;
  32489. _this.inertialRadiusOffset = 0;
  32490. _this.lowerAlphaLimit = null;
  32491. _this.upperAlphaLimit = null;
  32492. _this.lowerBetaLimit = 0.01;
  32493. _this.upperBetaLimit = Math.PI;
  32494. _this.lowerRadiusLimit = null;
  32495. _this.upperRadiusLimit = null;
  32496. _this.inertialPanningX = 0;
  32497. _this.inertialPanningY = 0;
  32498. _this.panningInertia = 0.9;
  32499. //-- end properties for backward compatibility for inputs
  32500. _this.zoomOnFactor = 1;
  32501. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  32502. _this.allowUpsideDown = true;
  32503. _this._viewMatrix = new BABYLON.Matrix();
  32504. // Panning
  32505. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  32506. _this.checkCollisions = false;
  32507. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32508. _this._previousPosition = BABYLON.Vector3.Zero();
  32509. _this._collisionVelocity = BABYLON.Vector3.Zero();
  32510. _this._newPosition = BABYLON.Vector3.Zero();
  32511. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32512. if (collidedMesh === void 0) { collidedMesh = null; }
  32513. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  32514. newPosition.multiplyInPlace(_this._collider.radius);
  32515. }
  32516. if (!collidedMesh) {
  32517. _this._previousPosition.copyFrom(_this.position);
  32518. }
  32519. else {
  32520. _this.setPosition(newPosition);
  32521. if (_this.onCollide) {
  32522. _this.onCollide(collidedMesh);
  32523. }
  32524. }
  32525. // Recompute because of constraints
  32526. var cosa = Math.cos(_this.alpha);
  32527. var sina = Math.sin(_this.alpha);
  32528. var cosb = Math.cos(_this.beta);
  32529. var sinb = Math.sin(_this.beta);
  32530. if (sinb === 0) {
  32531. sinb = 0.0001;
  32532. }
  32533. var target = _this._getTargetPosition();
  32534. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  32535. _this.position.copyFrom(_this._newPosition);
  32536. var up = _this.upVector;
  32537. if (_this.allowUpsideDown && _this.beta < 0) {
  32538. up = up.clone();
  32539. up = up.negate();
  32540. }
  32541. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  32542. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  32543. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  32544. _this._collisionTriggered = false;
  32545. };
  32546. _this._target = BABYLON.Vector3.Zero();
  32547. if (target) {
  32548. _this.setTarget(target);
  32549. }
  32550. _this.alpha = alpha;
  32551. _this.beta = beta;
  32552. _this.radius = radius;
  32553. _this.getViewMatrix();
  32554. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  32555. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  32556. return _this;
  32557. }
  32558. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  32559. get: function () {
  32560. return this._target;
  32561. },
  32562. set: function (value) {
  32563. this.setTarget(value);
  32564. },
  32565. enumerable: true,
  32566. configurable: true
  32567. });
  32568. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  32569. //-- begin properties for backward compatibility for inputs
  32570. get: function () {
  32571. var pointers = this.inputs.attached["pointers"];
  32572. if (pointers)
  32573. return pointers.angularSensibilityX;
  32574. },
  32575. set: function (value) {
  32576. var pointers = this.inputs.attached["pointers"];
  32577. if (pointers) {
  32578. pointers.angularSensibilityX = value;
  32579. }
  32580. },
  32581. enumerable: true,
  32582. configurable: true
  32583. });
  32584. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  32585. get: function () {
  32586. var pointers = this.inputs.attached["pointers"];
  32587. if (pointers)
  32588. return pointers.angularSensibilityY;
  32589. },
  32590. set: function (value) {
  32591. var pointers = this.inputs.attached["pointers"];
  32592. if (pointers) {
  32593. pointers.angularSensibilityY = value;
  32594. }
  32595. },
  32596. enumerable: true,
  32597. configurable: true
  32598. });
  32599. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  32600. get: function () {
  32601. var pointers = this.inputs.attached["pointers"];
  32602. if (pointers)
  32603. return pointers.pinchPrecision;
  32604. },
  32605. set: function (value) {
  32606. var pointers = this.inputs.attached["pointers"];
  32607. if (pointers) {
  32608. pointers.pinchPrecision = value;
  32609. }
  32610. },
  32611. enumerable: true,
  32612. configurable: true
  32613. });
  32614. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  32615. get: function () {
  32616. var pointers = this.inputs.attached["pointers"];
  32617. if (pointers)
  32618. return pointers.panningSensibility;
  32619. },
  32620. set: function (value) {
  32621. var pointers = this.inputs.attached["pointers"];
  32622. if (pointers) {
  32623. pointers.panningSensibility = value;
  32624. }
  32625. },
  32626. enumerable: true,
  32627. configurable: true
  32628. });
  32629. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  32630. get: function () {
  32631. var keyboard = this.inputs.attached["keyboard"];
  32632. if (keyboard)
  32633. return keyboard.keysUp;
  32634. },
  32635. set: function (value) {
  32636. var keyboard = this.inputs.attached["keyboard"];
  32637. if (keyboard)
  32638. keyboard.keysUp = value;
  32639. },
  32640. enumerable: true,
  32641. configurable: true
  32642. });
  32643. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  32644. get: function () {
  32645. var keyboard = this.inputs.attached["keyboard"];
  32646. if (keyboard)
  32647. return keyboard.keysDown;
  32648. },
  32649. set: function (value) {
  32650. var keyboard = this.inputs.attached["keyboard"];
  32651. if (keyboard)
  32652. keyboard.keysDown = value;
  32653. },
  32654. enumerable: true,
  32655. configurable: true
  32656. });
  32657. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  32658. get: function () {
  32659. var keyboard = this.inputs.attached["keyboard"];
  32660. if (keyboard)
  32661. return keyboard.keysLeft;
  32662. },
  32663. set: function (value) {
  32664. var keyboard = this.inputs.attached["keyboard"];
  32665. if (keyboard)
  32666. keyboard.keysLeft = value;
  32667. },
  32668. enumerable: true,
  32669. configurable: true
  32670. });
  32671. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  32672. get: function () {
  32673. var keyboard = this.inputs.attached["keyboard"];
  32674. if (keyboard)
  32675. return keyboard.keysRight;
  32676. },
  32677. set: function (value) {
  32678. var keyboard = this.inputs.attached["keyboard"];
  32679. if (keyboard)
  32680. keyboard.keysRight = value;
  32681. },
  32682. enumerable: true,
  32683. configurable: true
  32684. });
  32685. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  32686. get: function () {
  32687. var mousewheel = this.inputs.attached["mousewheel"];
  32688. if (mousewheel)
  32689. return mousewheel.wheelPrecision;
  32690. },
  32691. set: function (value) {
  32692. var mousewheel = this.inputs.attached["mousewheel"];
  32693. if (mousewheel)
  32694. mousewheel.wheelPrecision = value;
  32695. },
  32696. enumerable: true,
  32697. configurable: true
  32698. });
  32699. // Cache
  32700. ArcRotateCamera.prototype._initCache = function () {
  32701. _super.prototype._initCache.call(this);
  32702. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32703. this._cache.alpha = undefined;
  32704. this._cache.beta = undefined;
  32705. this._cache.radius = undefined;
  32706. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  32707. };
  32708. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  32709. if (!ignoreParentClass) {
  32710. _super.prototype._updateCache.call(this);
  32711. }
  32712. this._cache._target.copyFrom(this._getTargetPosition());
  32713. this._cache.alpha = this.alpha;
  32714. this._cache.beta = this.beta;
  32715. this._cache.radius = this.radius;
  32716. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  32717. };
  32718. ArcRotateCamera.prototype._getTargetPosition = function () {
  32719. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  32720. var pos = this._targetHost.getAbsolutePosition();
  32721. if (this._targetBoundingCenter) {
  32722. pos.addToRef(this._targetBoundingCenter, this._target);
  32723. }
  32724. else {
  32725. this._target.copyFrom(pos);
  32726. }
  32727. }
  32728. return this._target;
  32729. };
  32730. // Synchronized
  32731. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  32732. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  32733. return false;
  32734. return this._cache._target.equals(this._target)
  32735. && this._cache.alpha === this.alpha
  32736. && this._cache.beta === this.beta
  32737. && this._cache.radius === this.radius
  32738. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32739. };
  32740. // Methods
  32741. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32742. var _this = this;
  32743. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32744. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32745. this._useCtrlForPanning = useCtrlForPanning;
  32746. this._panningMouseButton = panningMouseButton;
  32747. this.inputs.attachElement(element, noPreventDefault);
  32748. this._reset = function () {
  32749. _this.inertialAlphaOffset = 0;
  32750. _this.inertialBetaOffset = 0;
  32751. _this.inertialRadiusOffset = 0;
  32752. };
  32753. };
  32754. ArcRotateCamera.prototype.detachControl = function (element) {
  32755. this.inputs.detachElement(element);
  32756. if (this._reset) {
  32757. this._reset();
  32758. }
  32759. };
  32760. ArcRotateCamera.prototype._checkInputs = function () {
  32761. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32762. if (this._collisionTriggered) {
  32763. return;
  32764. }
  32765. this.inputs.checkInputs();
  32766. // Inertia
  32767. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32768. if (this.getScene().useRightHandedSystem) {
  32769. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32770. }
  32771. else {
  32772. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32773. }
  32774. this.beta += this.inertialBetaOffset;
  32775. this.radius -= this.inertialRadiusOffset;
  32776. this.inertialAlphaOffset *= this.inertia;
  32777. this.inertialBetaOffset *= this.inertia;
  32778. this.inertialRadiusOffset *= this.inertia;
  32779. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  32780. this.inertialAlphaOffset = 0;
  32781. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  32782. this.inertialBetaOffset = 0;
  32783. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32784. this.inertialRadiusOffset = 0;
  32785. }
  32786. // Panning inertia
  32787. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32788. if (!this._localDirection) {
  32789. this._localDirection = BABYLON.Vector3.Zero();
  32790. this._transformedDirection = BABYLON.Vector3.Zero();
  32791. }
  32792. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32793. this._localDirection.multiplyInPlace(this.panningAxis);
  32794. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32795. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32796. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32797. if (!this.panningAxis.y) {
  32798. this._transformedDirection.y = 0;
  32799. }
  32800. if (!this._targetHost) {
  32801. this._target.addInPlace(this._transformedDirection);
  32802. }
  32803. this.inertialPanningX *= this.panningInertia;
  32804. this.inertialPanningY *= this.panningInertia;
  32805. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32806. this.inertialPanningX = 0;
  32807. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32808. this.inertialPanningY = 0;
  32809. }
  32810. // Limits
  32811. this._checkLimits();
  32812. _super.prototype._checkInputs.call(this);
  32813. };
  32814. ArcRotateCamera.prototype._checkLimits = function () {
  32815. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32816. if (this.allowUpsideDown && this.beta > Math.PI) {
  32817. this.beta = this.beta - (2 * Math.PI);
  32818. }
  32819. }
  32820. else {
  32821. if (this.beta < this.lowerBetaLimit) {
  32822. this.beta = this.lowerBetaLimit;
  32823. }
  32824. }
  32825. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32826. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32827. this.beta = this.beta + (2 * Math.PI);
  32828. }
  32829. }
  32830. else {
  32831. if (this.beta > this.upperBetaLimit) {
  32832. this.beta = this.upperBetaLimit;
  32833. }
  32834. }
  32835. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32836. this.alpha = this.lowerAlphaLimit;
  32837. }
  32838. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32839. this.alpha = this.upperAlphaLimit;
  32840. }
  32841. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32842. this.radius = this.lowerRadiusLimit;
  32843. }
  32844. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32845. this.radius = this.upperRadiusLimit;
  32846. }
  32847. };
  32848. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32849. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32850. this.radius = radiusv3.length();
  32851. // Alpha
  32852. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32853. if (radiusv3.z < 0) {
  32854. this.alpha = 2 * Math.PI - this.alpha;
  32855. }
  32856. // Beta
  32857. this.beta = Math.acos(radiusv3.y / this.radius);
  32858. this._checkLimits();
  32859. };
  32860. ArcRotateCamera.prototype.setPosition = function (position) {
  32861. if (this.position.equals(position)) {
  32862. return;
  32863. }
  32864. this.position.copyFrom(position);
  32865. this.rebuildAnglesAndRadius();
  32866. };
  32867. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32868. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32869. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32870. if (target.getBoundingInfo) {
  32871. if (toBoundingCenter) {
  32872. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32873. }
  32874. else {
  32875. this._targetBoundingCenter = null;
  32876. }
  32877. this._targetHost = target;
  32878. this._target = this._getTargetPosition();
  32879. }
  32880. else {
  32881. var newTarget = target;
  32882. var currentTarget = this._getTargetPosition();
  32883. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32884. return;
  32885. }
  32886. this._target = newTarget;
  32887. this._targetBoundingCenter = null;
  32888. }
  32889. this.rebuildAnglesAndRadius();
  32890. };
  32891. ArcRotateCamera.prototype._getViewMatrix = function () {
  32892. // Compute
  32893. var cosa = Math.cos(this.alpha);
  32894. var sina = Math.sin(this.alpha);
  32895. var cosb = Math.cos(this.beta);
  32896. var sinb = Math.sin(this.beta);
  32897. if (sinb === 0) {
  32898. sinb = 0.0001;
  32899. }
  32900. var target = this._getTargetPosition();
  32901. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  32902. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  32903. if (!this._collider) {
  32904. this._collider = new BABYLON.Collider();
  32905. }
  32906. this._collider.radius = this.collisionRadius;
  32907. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  32908. this._collisionTriggered = true;
  32909. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32910. }
  32911. else {
  32912. this.position.copyFrom(this._newPosition);
  32913. var up = this.upVector;
  32914. if (this.allowUpsideDown && sinb < 0) {
  32915. up = up.clone();
  32916. up = up.negate();
  32917. }
  32918. if (this.getScene().useRightHandedSystem) {
  32919. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  32920. }
  32921. else {
  32922. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  32923. }
  32924. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  32925. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  32926. }
  32927. this._currentTarget = target;
  32928. return this._viewMatrix;
  32929. };
  32930. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  32931. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32932. meshes = meshes || this.getScene().meshes;
  32933. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  32934. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  32935. this.radius = distance * this.zoomOnFactor;
  32936. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  32937. };
  32938. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  32939. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32940. var meshesOrMinMaxVector;
  32941. var distance;
  32942. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  32943. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  32944. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  32945. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  32946. }
  32947. else {
  32948. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  32949. distance = meshesOrMinMaxVectorAndDistance.distance;
  32950. }
  32951. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  32952. if (!doNotUpdateMaxZ) {
  32953. this.maxZ = distance * 2;
  32954. }
  32955. };
  32956. /**
  32957. * @override
  32958. * Override Camera.createRigCamera
  32959. */
  32960. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32961. var alphaShift;
  32962. switch (this.cameraRigMode) {
  32963. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32964. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32965. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32966. case BABYLON.Camera.RIG_MODE_VR:
  32967. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  32968. break;
  32969. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32970. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  32971. break;
  32972. }
  32973. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  32974. rigCam._cameraRigParams = {};
  32975. return rigCam;
  32976. };
  32977. /**
  32978. * @override
  32979. * Override Camera._updateRigCameras
  32980. */
  32981. ArcRotateCamera.prototype._updateRigCameras = function () {
  32982. var camLeft = this._rigCameras[0];
  32983. var camRight = this._rigCameras[1];
  32984. camLeft.beta = camRight.beta = this.beta;
  32985. camLeft.radius = camRight.radius = this.radius;
  32986. switch (this.cameraRigMode) {
  32987. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32988. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32989. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32990. case BABYLON.Camera.RIG_MODE_VR:
  32991. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32992. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32993. break;
  32994. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32995. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32996. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32997. break;
  32998. }
  32999. _super.prototype._updateRigCameras.call(this);
  33000. };
  33001. ArcRotateCamera.prototype.dispose = function () {
  33002. this.inputs.clear();
  33003. _super.prototype.dispose.call(this);
  33004. };
  33005. ArcRotateCamera.prototype.getClassName = function () {
  33006. return "ArcRotateCamera";
  33007. };
  33008. return ArcRotateCamera;
  33009. }(BABYLON.TargetCamera));
  33010. __decorate([
  33011. BABYLON.serialize()
  33012. ], ArcRotateCamera.prototype, "alpha", void 0);
  33013. __decorate([
  33014. BABYLON.serialize()
  33015. ], ArcRotateCamera.prototype, "beta", void 0);
  33016. __decorate([
  33017. BABYLON.serialize()
  33018. ], ArcRotateCamera.prototype, "radius", void 0);
  33019. __decorate([
  33020. BABYLON.serializeAsVector3("target")
  33021. ], ArcRotateCamera.prototype, "_target", void 0);
  33022. __decorate([
  33023. BABYLON.serialize()
  33024. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  33025. __decorate([
  33026. BABYLON.serialize()
  33027. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  33028. __decorate([
  33029. BABYLON.serialize()
  33030. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  33031. __decorate([
  33032. BABYLON.serialize()
  33033. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  33034. __decorate([
  33035. BABYLON.serialize()
  33036. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  33037. __decorate([
  33038. BABYLON.serialize()
  33039. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  33040. __decorate([
  33041. BABYLON.serialize()
  33042. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  33043. __decorate([
  33044. BABYLON.serialize()
  33045. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  33046. __decorate([
  33047. BABYLON.serialize()
  33048. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  33049. __decorate([
  33050. BABYLON.serialize()
  33051. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  33052. __decorate([
  33053. BABYLON.serialize()
  33054. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  33055. __decorate([
  33056. BABYLON.serialize()
  33057. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  33058. __decorate([
  33059. BABYLON.serialize()
  33060. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  33061. __decorate([
  33062. BABYLON.serialize()
  33063. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  33064. BABYLON.ArcRotateCamera = ArcRotateCamera;
  33065. })(BABYLON || (BABYLON = {}));
  33066. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  33067. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  33068. var BABYLON;
  33069. (function (BABYLON) {
  33070. var ArcRotateCameraInputsManager = (function (_super) {
  33071. __extends(ArcRotateCameraInputsManager, _super);
  33072. function ArcRotateCameraInputsManager(camera) {
  33073. return _super.call(this, camera) || this;
  33074. }
  33075. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  33076. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  33077. return this;
  33078. };
  33079. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  33080. this.add(new BABYLON.ArcRotateCameraPointersInput());
  33081. return this;
  33082. };
  33083. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  33084. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  33085. return this;
  33086. };
  33087. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  33088. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  33089. return this;
  33090. };
  33091. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  33092. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  33093. return this;
  33094. };
  33095. return ArcRotateCameraInputsManager;
  33096. }(BABYLON.CameraInputsManager));
  33097. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  33098. })(BABYLON || (BABYLON = {}));
  33099. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  33100. var BABYLON;
  33101. (function (BABYLON) {
  33102. var HemisphericLight = (function (_super) {
  33103. __extends(HemisphericLight, _super);
  33104. /**
  33105. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  33106. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  33107. * The HemisphericLight can't cast shadows.
  33108. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33109. */
  33110. function HemisphericLight(name, direction, scene) {
  33111. var _this = _super.call(this, name, scene) || this;
  33112. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  33113. _this.direction = direction || BABYLON.Vector3.Up();
  33114. return _this;
  33115. }
  33116. HemisphericLight.prototype._buildUniformLayout = function () {
  33117. this._uniformBuffer.addUniform("vLightData", 4);
  33118. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33119. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33120. this._uniformBuffer.addUniform("vLightGround", 3);
  33121. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33122. this._uniformBuffer.create();
  33123. };
  33124. /**
  33125. * Returns the string "HemisphericLight".
  33126. */
  33127. HemisphericLight.prototype.getClassName = function () {
  33128. return "HemisphericLight";
  33129. };
  33130. /**
  33131. * Sets the HemisphericLight direction towards the passed target (Vector3).
  33132. * Returns the updated direction.
  33133. */
  33134. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  33135. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  33136. return this.direction;
  33137. };
  33138. HemisphericLight.prototype.getShadowGenerator = function () {
  33139. return null;
  33140. };
  33141. /**
  33142. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  33143. * Returns the HemisphericLight.
  33144. */
  33145. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  33146. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  33147. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  33148. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  33149. return this;
  33150. };
  33151. HemisphericLight.prototype._getWorldMatrix = function () {
  33152. if (!this._worldMatrix) {
  33153. this._worldMatrix = BABYLON.Matrix.Identity();
  33154. }
  33155. return this._worldMatrix;
  33156. };
  33157. /**
  33158. * Returns the integer 3.
  33159. */
  33160. HemisphericLight.prototype.getTypeID = function () {
  33161. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  33162. };
  33163. return HemisphericLight;
  33164. }(BABYLON.Light));
  33165. __decorate([
  33166. BABYLON.serializeAsColor3()
  33167. ], HemisphericLight.prototype, "groundColor", void 0);
  33168. __decorate([
  33169. BABYLON.serializeAsVector3()
  33170. ], HemisphericLight.prototype, "direction", void 0);
  33171. BABYLON.HemisphericLight = HemisphericLight;
  33172. })(BABYLON || (BABYLON = {}));
  33173. //# sourceMappingURL=babylon.hemisphericLight.js.map
  33174. var BABYLON;
  33175. (function (BABYLON) {
  33176. var ShadowLight = (function (_super) {
  33177. __extends(ShadowLight, _super);
  33178. function ShadowLight() {
  33179. var _this = _super !== null && _super.apply(this, arguments) || this;
  33180. _this._needProjectionMatrixCompute = true;
  33181. return _this;
  33182. }
  33183. Object.defineProperty(ShadowLight.prototype, "direction", {
  33184. get: function () {
  33185. return this._direction;
  33186. },
  33187. set: function (value) {
  33188. this._direction = value;
  33189. },
  33190. enumerable: true,
  33191. configurable: true
  33192. });
  33193. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  33194. get: function () {
  33195. return this._shadowMinZ;
  33196. },
  33197. set: function (value) {
  33198. this._shadowMinZ = value;
  33199. this.forceProjectionMatrixCompute();
  33200. },
  33201. enumerable: true,
  33202. configurable: true
  33203. });
  33204. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  33205. get: function () {
  33206. return this._shadowMaxZ;
  33207. },
  33208. set: function (value) {
  33209. this._shadowMaxZ = value;
  33210. this.forceProjectionMatrixCompute();
  33211. },
  33212. enumerable: true,
  33213. configurable: true
  33214. });
  33215. /**
  33216. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  33217. */
  33218. ShadowLight.prototype.computeTransformedInformation = function () {
  33219. if (this.parent && this.parent.getWorldMatrix) {
  33220. if (!this.transformedPosition) {
  33221. this.transformedPosition = BABYLON.Vector3.Zero();
  33222. }
  33223. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  33224. // In case the direction is present.
  33225. if (this.direction) {
  33226. if (!this.transformedDirection) {
  33227. this.transformedDirection = BABYLON.Vector3.Zero();
  33228. }
  33229. BABYLON.Vector3.TransformCoordinatesToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  33230. }
  33231. return true;
  33232. }
  33233. return false;
  33234. };
  33235. /**
  33236. * Return the depth scale used for the shadow map.
  33237. */
  33238. ShadowLight.prototype.getDepthScale = function () {
  33239. return 30.0;
  33240. };
  33241. /**
  33242. * Returns the light direction (Vector3) for any passed face index.
  33243. */
  33244. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  33245. return this.transformedDirection ? this.transformedDirection : this.direction;
  33246. };
  33247. /**
  33248. * Returns the DirectionalLight absolute position in the World.
  33249. */
  33250. ShadowLight.prototype.getAbsolutePosition = function () {
  33251. return this.transformedPosition ? this.transformedPosition : this.position;
  33252. };
  33253. /**
  33254. * Sets the DirectionalLight direction toward the passed target (Vector3).
  33255. * Returns the updated DirectionalLight direction (Vector3).
  33256. */
  33257. ShadowLight.prototype.setDirectionToTarget = function (target) {
  33258. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  33259. return this.direction;
  33260. };
  33261. /**
  33262. * Returns the light rotation (Vector3).
  33263. */
  33264. ShadowLight.prototype.getRotation = function () {
  33265. this.direction.normalize();
  33266. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  33267. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  33268. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  33269. };
  33270. /**
  33271. * Boolean : false by default.
  33272. */
  33273. ShadowLight.prototype.needCube = function () {
  33274. return false;
  33275. };
  33276. /**
  33277. * Specifies wether or not the projection matrix should be recomputed this frame.
  33278. */
  33279. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  33280. return this._needProjectionMatrixCompute;
  33281. };
  33282. /**
  33283. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  33284. */
  33285. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  33286. this._needProjectionMatrixCompute = true;
  33287. };
  33288. /**
  33289. * Get the world matrix of the sahdow lights.
  33290. */
  33291. ShadowLight.prototype._getWorldMatrix = function () {
  33292. if (!this._worldMatrix) {
  33293. this._worldMatrix = BABYLON.Matrix.Identity();
  33294. }
  33295. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  33296. return this._worldMatrix;
  33297. };
  33298. /**
  33299. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  33300. * Returns the light.
  33301. */
  33302. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33303. if (this.customProjectionMatrixBuilder) {
  33304. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  33305. }
  33306. else {
  33307. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  33308. }
  33309. return this;
  33310. };
  33311. return ShadowLight;
  33312. }(BABYLON.Light));
  33313. __decorate([
  33314. BABYLON.serializeAsVector3()
  33315. ], ShadowLight.prototype, "position", void 0);
  33316. __decorate([
  33317. BABYLON.serializeAsVector3()
  33318. ], ShadowLight.prototype, "direction", null);
  33319. __decorate([
  33320. BABYLON.serialize()
  33321. ], ShadowLight.prototype, "shadowMinZ", null);
  33322. __decorate([
  33323. BABYLON.serialize()
  33324. ], ShadowLight.prototype, "shadowMaxZ", null);
  33325. BABYLON.ShadowLight = ShadowLight;
  33326. })(BABYLON || (BABYLON = {}));
  33327. //# sourceMappingURL=babylon.shadowLight.js.map
  33328. var BABYLON;
  33329. (function (BABYLON) {
  33330. var PointLight = (function (_super) {
  33331. __extends(PointLight, _super);
  33332. /**
  33333. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  33334. * A PointLight emits the light in every direction.
  33335. * It can cast shadows.
  33336. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  33337. * ```javascript
  33338. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  33339. * ```
  33340. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33341. */
  33342. function PointLight(name, position, scene) {
  33343. var _this = _super.call(this, name, scene) || this;
  33344. _this._shadowAngle = Math.PI / 2;
  33345. _this.position = position;
  33346. return _this;
  33347. }
  33348. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  33349. /**
  33350. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33351. * This specifies what angle the shadow will use to be created.
  33352. *
  33353. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33354. */
  33355. get: function () {
  33356. return this._shadowAngle;
  33357. },
  33358. /**
  33359. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33360. * This specifies what angle the shadow will use to be created.
  33361. *
  33362. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33363. */
  33364. set: function (value) {
  33365. this._shadowAngle = value;
  33366. this.forceProjectionMatrixCompute();
  33367. },
  33368. enumerable: true,
  33369. configurable: true
  33370. });
  33371. Object.defineProperty(PointLight.prototype, "direction", {
  33372. get: function () {
  33373. return this._direction;
  33374. },
  33375. /**
  33376. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33377. */
  33378. set: function (value) {
  33379. var previousNeedCube = this.needCube();
  33380. this._direction = value;
  33381. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  33382. this._shadowGenerator.recreateShadowMap();
  33383. }
  33384. },
  33385. enumerable: true,
  33386. configurable: true
  33387. });
  33388. /**
  33389. * Returns the string "PointLight"
  33390. */
  33391. PointLight.prototype.getClassName = function () {
  33392. return "PointLight";
  33393. };
  33394. /**
  33395. * Returns the integer 0.
  33396. */
  33397. PointLight.prototype.getTypeID = function () {
  33398. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  33399. };
  33400. /**
  33401. * Specifies wether or not the shadowmap should be a cube texture.
  33402. */
  33403. PointLight.prototype.needCube = function () {
  33404. return !this.direction;
  33405. };
  33406. /**
  33407. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  33408. */
  33409. PointLight.prototype.getShadowDirection = function (faceIndex) {
  33410. if (this.direction) {
  33411. return _super.prototype.getShadowDirection.call(this, faceIndex);
  33412. }
  33413. else {
  33414. switch (faceIndex) {
  33415. case 0:
  33416. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  33417. case 1:
  33418. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  33419. case 2:
  33420. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  33421. case 3:
  33422. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  33423. case 4:
  33424. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  33425. case 5:
  33426. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  33427. }
  33428. }
  33429. return BABYLON.Vector3.Zero();
  33430. };
  33431. /**
  33432. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  33433. * - fov = PI / 2
  33434. * - aspect ratio : 1.0
  33435. * - z-near and far equal to the active camera minZ and maxZ.
  33436. * Returns the PointLight.
  33437. */
  33438. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33439. var activeCamera = this.getScene().activeCamera;
  33440. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  33441. };
  33442. PointLight.prototype._buildUniformLayout = function () {
  33443. this._uniformBuffer.addUniform("vLightData", 4);
  33444. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33445. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33446. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33447. this._uniformBuffer.create();
  33448. };
  33449. /**
  33450. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  33451. * Returns the PointLight.
  33452. */
  33453. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  33454. if (this.computeTransformedInformation()) {
  33455. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  33456. return this;
  33457. }
  33458. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  33459. return this;
  33460. };
  33461. return PointLight;
  33462. }(BABYLON.ShadowLight));
  33463. __decorate([
  33464. BABYLON.serialize()
  33465. ], PointLight.prototype, "shadowAngle", null);
  33466. BABYLON.PointLight = PointLight;
  33467. })(BABYLON || (BABYLON = {}));
  33468. //# sourceMappingURL=babylon.pointLight.js.map
  33469. /// <reference path="babylon.light.ts" />
  33470. var BABYLON;
  33471. (function (BABYLON) {
  33472. var DirectionalLight = (function (_super) {
  33473. __extends(DirectionalLight, _super);
  33474. /**
  33475. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  33476. * The directional light is emitted from everywhere in the given direction.
  33477. * It can cast shawdows.
  33478. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33479. */
  33480. function DirectionalLight(name, direction, scene) {
  33481. var _this = _super.call(this, name, scene) || this;
  33482. _this._shadowOrthoScale = 0.5;
  33483. _this.autoUpdateExtends = true;
  33484. // Cache
  33485. _this._orthoLeft = Number.MAX_VALUE;
  33486. _this._orthoRight = Number.MIN_VALUE;
  33487. _this._orthoTop = Number.MIN_VALUE;
  33488. _this._orthoBottom = Number.MAX_VALUE;
  33489. _this.position = direction.scale(-1.0);
  33490. _this.direction = direction;
  33491. return _this;
  33492. }
  33493. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  33494. get: function () {
  33495. return this._shadowOrthoScale;
  33496. },
  33497. set: function (value) {
  33498. this._shadowOrthoScale = value;
  33499. this.forceProjectionMatrixCompute();
  33500. },
  33501. enumerable: true,
  33502. configurable: true
  33503. });
  33504. /**
  33505. * Returns the string "DirectionalLight".
  33506. */
  33507. DirectionalLight.prototype.getClassName = function () {
  33508. return "DirectionalLight";
  33509. };
  33510. /**
  33511. * Returns the integer 1.
  33512. */
  33513. DirectionalLight.prototype.getTypeID = function () {
  33514. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  33515. };
  33516. /**
  33517. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  33518. * Returns the DirectionalLight.
  33519. */
  33520. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33521. var activeCamera = this.getScene().activeCamera;
  33522. // Check extends
  33523. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  33524. var tempVector3 = BABYLON.Vector3.Zero();
  33525. this._orthoLeft = Number.MAX_VALUE;
  33526. this._orthoRight = Number.MIN_VALUE;
  33527. this._orthoTop = Number.MIN_VALUE;
  33528. this._orthoBottom = Number.MAX_VALUE;
  33529. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  33530. var mesh = renderList[meshIndex];
  33531. if (!mesh) {
  33532. continue;
  33533. }
  33534. var boundingInfo = mesh.getBoundingInfo();
  33535. if (!boundingInfo) {
  33536. continue;
  33537. }
  33538. var boundingBox = boundingInfo.boundingBox;
  33539. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  33540. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  33541. if (tempVector3.x < this._orthoLeft)
  33542. this._orthoLeft = tempVector3.x;
  33543. if (tempVector3.y < this._orthoBottom)
  33544. this._orthoBottom = tempVector3.y;
  33545. if (tempVector3.x > this._orthoRight)
  33546. this._orthoRight = tempVector3.x;
  33547. if (tempVector3.y > this._orthoTop)
  33548. this._orthoTop = tempVector3.y;
  33549. }
  33550. }
  33551. }
  33552. var xOffset = this._orthoRight - this._orthoLeft;
  33553. var yOffset = this._orthoTop - this._orthoBottom;
  33554. 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);
  33555. };
  33556. DirectionalLight.prototype._buildUniformLayout = function () {
  33557. this._uniformBuffer.addUniform("vLightData", 4);
  33558. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33559. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33560. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33561. this._uniformBuffer.create();
  33562. };
  33563. /**
  33564. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  33565. * Returns the DirectionalLight.
  33566. */
  33567. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  33568. if (this.computeTransformedInformation()) {
  33569. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  33570. return this;
  33571. }
  33572. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  33573. return this;
  33574. };
  33575. return DirectionalLight;
  33576. }(BABYLON.ShadowLight));
  33577. __decorate([
  33578. BABYLON.serialize()
  33579. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  33580. __decorate([
  33581. BABYLON.serialize()
  33582. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  33583. BABYLON.DirectionalLight = DirectionalLight;
  33584. })(BABYLON || (BABYLON = {}));
  33585. //# sourceMappingURL=babylon.directionalLight.js.map
  33586. var BABYLON;
  33587. (function (BABYLON) {
  33588. var SpotLight = (function (_super) {
  33589. __extends(SpotLight, _super);
  33590. /**
  33591. * Creates a SpotLight object in the scene with the passed parameters :
  33592. * - `position` (Vector3) is the initial SpotLight position,
  33593. * - `direction` (Vector3) is the initial SpotLight direction,
  33594. * - `angle` (float, in radians) is the spot light cone angle,
  33595. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  33596. * A spot light is a simply light oriented cone.
  33597. * It can cast shadows.
  33598. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33599. */
  33600. function SpotLight(name, position, direction, angle, exponent, scene) {
  33601. var _this = _super.call(this, name, scene) || this;
  33602. _this.position = position;
  33603. _this.direction = direction;
  33604. _this.angle = angle;
  33605. _this.exponent = exponent;
  33606. return _this;
  33607. }
  33608. Object.defineProperty(SpotLight.prototype, "angle", {
  33609. get: function () {
  33610. return this._angle;
  33611. },
  33612. set: function (value) {
  33613. this._angle = value;
  33614. this.forceProjectionMatrixCompute();
  33615. },
  33616. enumerable: true,
  33617. configurable: true
  33618. });
  33619. /**
  33620. * Returns the string "SpotLight".
  33621. */
  33622. SpotLight.prototype.getClassName = function () {
  33623. return "SpotLight";
  33624. };
  33625. /**
  33626. * Returns the integer 2.
  33627. */
  33628. SpotLight.prototype.getTypeID = function () {
  33629. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  33630. };
  33631. /**
  33632. * 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.
  33633. * Returns the SpotLight.
  33634. */
  33635. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33636. var activeCamera = this.getScene().activeCamera;
  33637. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  33638. };
  33639. SpotLight.prototype._buildUniformLayout = function () {
  33640. this._uniformBuffer.addUniform("vLightData", 4);
  33641. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33642. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33643. this._uniformBuffer.addUniform("vLightDirection", 3);
  33644. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33645. this._uniformBuffer.create();
  33646. };
  33647. /**
  33648. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  33649. * Return the SpotLight.
  33650. */
  33651. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  33652. var normalizeDirection;
  33653. if (this.computeTransformedInformation()) {
  33654. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  33655. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  33656. }
  33657. else {
  33658. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  33659. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  33660. }
  33661. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  33662. return this;
  33663. };
  33664. return SpotLight;
  33665. }(BABYLON.ShadowLight));
  33666. __decorate([
  33667. BABYLON.serialize()
  33668. ], SpotLight.prototype, "angle", null);
  33669. __decorate([
  33670. BABYLON.serialize()
  33671. ], SpotLight.prototype, "exponent", void 0);
  33672. BABYLON.SpotLight = SpotLight;
  33673. })(BABYLON || (BABYLON = {}));
  33674. //# sourceMappingURL=babylon.spotLight.js.map
  33675. var BABYLON;
  33676. (function (BABYLON) {
  33677. var AnimationRange = (function () {
  33678. function AnimationRange(name, from, to) {
  33679. this.name = name;
  33680. this.from = from;
  33681. this.to = to;
  33682. }
  33683. AnimationRange.prototype.clone = function () {
  33684. return new AnimationRange(this.name, this.from, this.to);
  33685. };
  33686. return AnimationRange;
  33687. }());
  33688. BABYLON.AnimationRange = AnimationRange;
  33689. /**
  33690. * Composed of a frame, and an action function
  33691. */
  33692. var AnimationEvent = (function () {
  33693. function AnimationEvent(frame, action, onlyOnce) {
  33694. this.frame = frame;
  33695. this.action = action;
  33696. this.onlyOnce = onlyOnce;
  33697. this.isDone = false;
  33698. }
  33699. return AnimationEvent;
  33700. }());
  33701. BABYLON.AnimationEvent = AnimationEvent;
  33702. var PathCursor = (function () {
  33703. function PathCursor(path) {
  33704. this.path = path;
  33705. this._onchange = new Array();
  33706. this.value = 0;
  33707. this.animations = new Array();
  33708. }
  33709. PathCursor.prototype.getPoint = function () {
  33710. var point = this.path.getPointAtLengthPosition(this.value);
  33711. return new BABYLON.Vector3(point.x, 0, point.y);
  33712. };
  33713. PathCursor.prototype.moveAhead = function (step) {
  33714. if (step === void 0) { step = 0.002; }
  33715. this.move(step);
  33716. return this;
  33717. };
  33718. PathCursor.prototype.moveBack = function (step) {
  33719. if (step === void 0) { step = 0.002; }
  33720. this.move(-step);
  33721. return this;
  33722. };
  33723. PathCursor.prototype.move = function (step) {
  33724. if (Math.abs(step) > 1) {
  33725. throw "step size should be less than 1.";
  33726. }
  33727. this.value += step;
  33728. this.ensureLimits();
  33729. this.raiseOnChange();
  33730. return this;
  33731. };
  33732. PathCursor.prototype.ensureLimits = function () {
  33733. while (this.value > 1) {
  33734. this.value -= 1;
  33735. }
  33736. while (this.value < 0) {
  33737. this.value += 1;
  33738. }
  33739. return this;
  33740. };
  33741. // used by animation engine
  33742. PathCursor.prototype.markAsDirty = function (propertyName) {
  33743. this.ensureLimits();
  33744. this.raiseOnChange();
  33745. return this;
  33746. };
  33747. PathCursor.prototype.raiseOnChange = function () {
  33748. var _this = this;
  33749. this._onchange.forEach(function (f) { return f(_this); });
  33750. return this;
  33751. };
  33752. PathCursor.prototype.onchange = function (f) {
  33753. this._onchange.push(f);
  33754. return this;
  33755. };
  33756. return PathCursor;
  33757. }());
  33758. BABYLON.PathCursor = PathCursor;
  33759. var Animation = (function () {
  33760. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  33761. this.name = name;
  33762. this.targetProperty = targetProperty;
  33763. this.framePerSecond = framePerSecond;
  33764. this.dataType = dataType;
  33765. this.loopMode = loopMode;
  33766. this.enableBlending = enableBlending;
  33767. this._offsetsCache = {};
  33768. this._highLimitsCache = {};
  33769. this._stopped = false;
  33770. this._blendingFactor = 0;
  33771. // The set of event that will be linked to this animation
  33772. this._events = new Array();
  33773. this.allowMatricesInterpolation = false;
  33774. this.blendingSpeed = 0.01;
  33775. this._ranges = {};
  33776. this.targetPropertyPath = targetProperty.split(".");
  33777. this.dataType = dataType;
  33778. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  33779. }
  33780. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  33781. var dataType = undefined;
  33782. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  33783. dataType = Animation.ANIMATIONTYPE_FLOAT;
  33784. }
  33785. else if (from instanceof BABYLON.Quaternion) {
  33786. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  33787. }
  33788. else if (from instanceof BABYLON.Vector3) {
  33789. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  33790. }
  33791. else if (from instanceof BABYLON.Vector2) {
  33792. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  33793. }
  33794. else if (from instanceof BABYLON.Color3) {
  33795. dataType = Animation.ANIMATIONTYPE_COLOR3;
  33796. }
  33797. else if (from instanceof BABYLON.Size) {
  33798. dataType = Animation.ANIMATIONTYPE_SIZE;
  33799. }
  33800. if (dataType == undefined) {
  33801. return null;
  33802. }
  33803. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  33804. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  33805. animation.setKeys(keys);
  33806. if (easingFunction !== undefined) {
  33807. animation.setEasingFunction(easingFunction);
  33808. }
  33809. return animation;
  33810. };
  33811. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  33812. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  33813. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  33814. };
  33815. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  33816. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  33817. node.animations.push(animation);
  33818. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  33819. };
  33820. // Methods
  33821. /**
  33822. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  33823. */
  33824. Animation.prototype.toString = function (fullDetails) {
  33825. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  33826. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  33827. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  33828. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  33829. if (fullDetails) {
  33830. ret += ", Ranges: {";
  33831. var first = true;
  33832. for (var name in this._ranges) {
  33833. if (first) {
  33834. ret += ", ";
  33835. first = false;
  33836. }
  33837. ret += name;
  33838. }
  33839. ret += "}";
  33840. }
  33841. return ret;
  33842. };
  33843. /**
  33844. * Add an event to this animation.
  33845. */
  33846. Animation.prototype.addEvent = function (event) {
  33847. this._events.push(event);
  33848. };
  33849. /**
  33850. * Remove all events found at the given frame
  33851. * @param frame
  33852. */
  33853. Animation.prototype.removeEvents = function (frame) {
  33854. for (var index = 0; index < this._events.length; index++) {
  33855. if (this._events[index].frame === frame) {
  33856. this._events.splice(index, 1);
  33857. index--;
  33858. }
  33859. }
  33860. };
  33861. Animation.prototype.createRange = function (name, from, to) {
  33862. // check name not already in use; could happen for bones after serialized
  33863. if (!this._ranges[name]) {
  33864. this._ranges[name] = new AnimationRange(name, from, to);
  33865. }
  33866. };
  33867. Animation.prototype.deleteRange = function (name, deleteFrames) {
  33868. if (deleteFrames === void 0) { deleteFrames = true; }
  33869. if (this._ranges[name]) {
  33870. if (deleteFrames) {
  33871. var from = this._ranges[name].from;
  33872. var to = this._ranges[name].to;
  33873. // this loop MUST go high to low for multiple splices to work
  33874. for (var key = this._keys.length - 1; key >= 0; key--) {
  33875. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  33876. this._keys.splice(key, 1);
  33877. }
  33878. }
  33879. }
  33880. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  33881. }
  33882. };
  33883. Animation.prototype.getRange = function (name) {
  33884. return this._ranges[name];
  33885. };
  33886. Animation.prototype.reset = function () {
  33887. this._offsetsCache = {};
  33888. this._highLimitsCache = {};
  33889. this.currentFrame = 0;
  33890. this._blendingFactor = 0;
  33891. this._originalBlendValue = null;
  33892. };
  33893. Animation.prototype.isStopped = function () {
  33894. return this._stopped;
  33895. };
  33896. Animation.prototype.getKeys = function () {
  33897. return this._keys;
  33898. };
  33899. Animation.prototype.getHighestFrame = function () {
  33900. var ret = 0;
  33901. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  33902. if (ret < this._keys[key].frame) {
  33903. ret = this._keys[key].frame;
  33904. }
  33905. }
  33906. return ret;
  33907. };
  33908. Animation.prototype.getEasingFunction = function () {
  33909. return this._easingFunction;
  33910. };
  33911. Animation.prototype.setEasingFunction = function (easingFunction) {
  33912. this._easingFunction = easingFunction;
  33913. };
  33914. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  33915. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  33916. };
  33917. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  33918. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  33919. };
  33920. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  33921. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  33922. };
  33923. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  33924. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  33925. };
  33926. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  33927. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  33928. };
  33929. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  33930. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  33931. };
  33932. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  33933. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  33934. };
  33935. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  33936. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  33937. };
  33938. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  33939. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  33940. };
  33941. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  33942. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  33943. };
  33944. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  33945. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  33946. };
  33947. Animation.prototype.clone = function () {
  33948. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  33949. clone.enableBlending = this.enableBlending;
  33950. clone.blendingSpeed = this.blendingSpeed;
  33951. if (this._keys) {
  33952. clone.setKeys(this._keys);
  33953. }
  33954. if (this._ranges) {
  33955. clone._ranges = {};
  33956. for (var name in this._ranges) {
  33957. clone._ranges[name] = this._ranges[name].clone();
  33958. }
  33959. }
  33960. return clone;
  33961. };
  33962. Animation.prototype.setKeys = function (values) {
  33963. this._keys = values.slice(0);
  33964. this._offsetsCache = {};
  33965. this._highLimitsCache = {};
  33966. };
  33967. Animation.prototype._getKeyValue = function (value) {
  33968. if (typeof value === "function") {
  33969. return value();
  33970. }
  33971. return value;
  33972. };
  33973. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  33974. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  33975. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  33976. }
  33977. this.currentFrame = currentFrame;
  33978. // Try to get a hash to find the right key
  33979. var startKeyIndex = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  33980. if (this._keys[startKeyIndex].frame >= currentFrame) {
  33981. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  33982. startKeyIndex--;
  33983. }
  33984. }
  33985. for (var key = startKeyIndex; key < this._keys.length; key++) {
  33986. var endKey = this._keys[key + 1];
  33987. if (endKey.frame >= currentFrame) {
  33988. var startKey = this._keys[key];
  33989. var startValue = this._getKeyValue(startKey.value);
  33990. var endValue = this._getKeyValue(endKey.value);
  33991. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  33992. var frameDelta = endKey.frame - startKey.frame;
  33993. // gradient : percent of currentFrame between the frame inf and the frame sup
  33994. var gradient = (currentFrame - startKey.frame) / frameDelta;
  33995. // check for easingFunction and correction of gradient
  33996. if (this._easingFunction != null) {
  33997. gradient = this._easingFunction.ease(gradient);
  33998. }
  33999. switch (this.dataType) {
  34000. // Float
  34001. case Animation.ANIMATIONTYPE_FLOAT:
  34002. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  34003. switch (loopMode) {
  34004. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34005. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34006. return floatValue;
  34007. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34008. return offsetValue * repeatCount + floatValue;
  34009. }
  34010. break;
  34011. // Quaternion
  34012. case Animation.ANIMATIONTYPE_QUATERNION:
  34013. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  34014. switch (loopMode) {
  34015. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34016. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34017. return quatValue;
  34018. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34019. return quatValue.add(offsetValue.scale(repeatCount));
  34020. }
  34021. return quatValue;
  34022. // Vector3
  34023. case Animation.ANIMATIONTYPE_VECTOR3:
  34024. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  34025. switch (loopMode) {
  34026. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34027. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34028. return vec3Value;
  34029. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34030. return vec3Value.add(offsetValue.scale(repeatCount));
  34031. }
  34032. // Vector2
  34033. case Animation.ANIMATIONTYPE_VECTOR2:
  34034. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  34035. switch (loopMode) {
  34036. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34037. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34038. return vec2Value;
  34039. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34040. return vec2Value.add(offsetValue.scale(repeatCount));
  34041. }
  34042. // Size
  34043. case Animation.ANIMATIONTYPE_SIZE:
  34044. switch (loopMode) {
  34045. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34046. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34047. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  34048. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34049. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34050. }
  34051. // Color3
  34052. case Animation.ANIMATIONTYPE_COLOR3:
  34053. switch (loopMode) {
  34054. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34055. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34056. return this.color3InterpolateFunction(startValue, endValue, gradient);
  34057. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34058. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34059. }
  34060. // Matrix
  34061. case Animation.ANIMATIONTYPE_MATRIX:
  34062. switch (loopMode) {
  34063. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34064. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34065. if (this.allowMatricesInterpolation) {
  34066. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  34067. }
  34068. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34069. return startValue;
  34070. }
  34071. default:
  34072. break;
  34073. }
  34074. break;
  34075. }
  34076. }
  34077. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  34078. };
  34079. Animation.prototype.setValue = function (currentValue, blend) {
  34080. if (blend === void 0) { blend = false; }
  34081. // Set value
  34082. var path;
  34083. var destination;
  34084. if (this.targetPropertyPath.length > 1) {
  34085. var property = this._target[this.targetPropertyPath[0]];
  34086. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  34087. property = property[this.targetPropertyPath[index]];
  34088. }
  34089. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  34090. destination = property;
  34091. }
  34092. else {
  34093. path = this.targetPropertyPath[0];
  34094. destination = this._target;
  34095. }
  34096. // Blending
  34097. if (this.enableBlending && this._blendingFactor <= 1.0) {
  34098. if (!this._originalBlendValue) {
  34099. if (destination[path].clone) {
  34100. this._originalBlendValue = destination[path].clone();
  34101. }
  34102. else {
  34103. this._originalBlendValue = destination[path];
  34104. }
  34105. }
  34106. if (this._originalBlendValue.prototype) {
  34107. if (this._originalBlendValue.prototype.Lerp) {
  34108. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  34109. }
  34110. else {
  34111. destination[path] = currentValue;
  34112. }
  34113. }
  34114. else if (this._originalBlendValue.m) {
  34115. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  34116. }
  34117. else {
  34118. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  34119. }
  34120. this._blendingFactor += this.blendingSpeed;
  34121. }
  34122. else {
  34123. destination[path] = currentValue;
  34124. }
  34125. if (this._target.markAsDirty) {
  34126. this._target.markAsDirty(this.targetProperty);
  34127. }
  34128. };
  34129. Animation.prototype.goToFrame = function (frame) {
  34130. if (frame < this._keys[0].frame) {
  34131. frame = this._keys[0].frame;
  34132. }
  34133. else if (frame > this._keys[this._keys.length - 1].frame) {
  34134. frame = this._keys[this._keys.length - 1].frame;
  34135. }
  34136. var currentValue = this._interpolate(frame, 0, this.loopMode);
  34137. this.setValue(currentValue);
  34138. };
  34139. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  34140. if (blend === void 0) { blend = false; }
  34141. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  34142. this._stopped = true;
  34143. return false;
  34144. }
  34145. var returnValue = true;
  34146. // Adding a start key at frame 0 if missing
  34147. if (this._keys[0].frame !== 0) {
  34148. var newKey = { frame: 0, value: this._keys[0].value };
  34149. this._keys.splice(0, 0, newKey);
  34150. }
  34151. // Check limits
  34152. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  34153. from = this._keys[0].frame;
  34154. }
  34155. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  34156. to = this._keys[this._keys.length - 1].frame;
  34157. }
  34158. //to and from cannot be the same key
  34159. if (from === to) {
  34160. from++;
  34161. }
  34162. // Compute ratio
  34163. var range = to - from;
  34164. var offsetValue;
  34165. // ratio represents the frame delta between from and to
  34166. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  34167. var highLimitValue = 0;
  34168. if (ratio > range && !loop) {
  34169. returnValue = false;
  34170. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  34171. }
  34172. else {
  34173. // Get max value if required
  34174. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  34175. var keyOffset = to.toString() + from.toString();
  34176. if (!this._offsetsCache[keyOffset]) {
  34177. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34178. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34179. switch (this.dataType) {
  34180. // Float
  34181. case Animation.ANIMATIONTYPE_FLOAT:
  34182. this._offsetsCache[keyOffset] = toValue - fromValue;
  34183. break;
  34184. // Quaternion
  34185. case Animation.ANIMATIONTYPE_QUATERNION:
  34186. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34187. break;
  34188. // Vector3
  34189. case Animation.ANIMATIONTYPE_VECTOR3:
  34190. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34191. // Vector2
  34192. case Animation.ANIMATIONTYPE_VECTOR2:
  34193. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34194. // Size
  34195. case Animation.ANIMATIONTYPE_SIZE:
  34196. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34197. // Color3
  34198. case Animation.ANIMATIONTYPE_COLOR3:
  34199. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34200. default:
  34201. break;
  34202. }
  34203. this._highLimitsCache[keyOffset] = toValue;
  34204. }
  34205. highLimitValue = this._highLimitsCache[keyOffset];
  34206. offsetValue = this._offsetsCache[keyOffset];
  34207. }
  34208. }
  34209. if (offsetValue === undefined) {
  34210. switch (this.dataType) {
  34211. // Float
  34212. case Animation.ANIMATIONTYPE_FLOAT:
  34213. offsetValue = 0;
  34214. break;
  34215. // Quaternion
  34216. case Animation.ANIMATIONTYPE_QUATERNION:
  34217. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  34218. break;
  34219. // Vector3
  34220. case Animation.ANIMATIONTYPE_VECTOR3:
  34221. offsetValue = BABYLON.Vector3.Zero();
  34222. break;
  34223. // Vector2
  34224. case Animation.ANIMATIONTYPE_VECTOR2:
  34225. offsetValue = BABYLON.Vector2.Zero();
  34226. break;
  34227. // Size
  34228. case Animation.ANIMATIONTYPE_SIZE:
  34229. offsetValue = BABYLON.Size.Zero();
  34230. break;
  34231. // Color3
  34232. case Animation.ANIMATIONTYPE_COLOR3:
  34233. offsetValue = BABYLON.Color3.Black();
  34234. }
  34235. }
  34236. // Compute value
  34237. var repeatCount = (ratio / range) >> 0;
  34238. var currentFrame = returnValue ? from + ratio % range : to;
  34239. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  34240. // Set value
  34241. this.setValue(currentValue);
  34242. // Check events
  34243. for (var index = 0; index < this._events.length; index++) {
  34244. if (currentFrame >= this._events[index].frame) {
  34245. var event = this._events[index];
  34246. if (!event.isDone) {
  34247. // If event should be done only once, remove it.
  34248. if (event.onlyOnce) {
  34249. this._events.splice(index, 1);
  34250. index--;
  34251. }
  34252. event.isDone = true;
  34253. event.action();
  34254. } // Don't do anything if the event has already be done.
  34255. }
  34256. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  34257. // reset event, the animation is looping
  34258. this._events[index].isDone = false;
  34259. }
  34260. }
  34261. if (!returnValue) {
  34262. this._stopped = true;
  34263. }
  34264. return returnValue;
  34265. };
  34266. Animation.prototype.serialize = function () {
  34267. var serializationObject = {};
  34268. serializationObject.name = this.name;
  34269. serializationObject.property = this.targetProperty;
  34270. serializationObject.framePerSecond = this.framePerSecond;
  34271. serializationObject.dataType = this.dataType;
  34272. serializationObject.loopBehavior = this.loopMode;
  34273. serializationObject.enableBlending = this.enableBlending;
  34274. serializationObject.blendingSpeed = this.blendingSpeed;
  34275. var dataType = this.dataType;
  34276. serializationObject.keys = [];
  34277. var keys = this.getKeys();
  34278. for (var index = 0; index < keys.length; index++) {
  34279. var animationKey = keys[index];
  34280. var key = {};
  34281. key.frame = animationKey.frame;
  34282. switch (dataType) {
  34283. case Animation.ANIMATIONTYPE_FLOAT:
  34284. key.values = [animationKey.value];
  34285. break;
  34286. case Animation.ANIMATIONTYPE_QUATERNION:
  34287. case Animation.ANIMATIONTYPE_MATRIX:
  34288. case Animation.ANIMATIONTYPE_VECTOR3:
  34289. case Animation.ANIMATIONTYPE_COLOR3:
  34290. key.values = animationKey.value.asArray();
  34291. break;
  34292. }
  34293. serializationObject.keys.push(key);
  34294. }
  34295. serializationObject.ranges = [];
  34296. for (var name in this._ranges) {
  34297. var range = {};
  34298. range.name = name;
  34299. range.from = this._ranges[name].from;
  34300. range.to = this._ranges[name].to;
  34301. serializationObject.ranges.push(range);
  34302. }
  34303. return serializationObject;
  34304. };
  34305. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  34306. get: function () {
  34307. return Animation._ANIMATIONTYPE_FLOAT;
  34308. },
  34309. enumerable: true,
  34310. configurable: true
  34311. });
  34312. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  34313. get: function () {
  34314. return Animation._ANIMATIONTYPE_VECTOR3;
  34315. },
  34316. enumerable: true,
  34317. configurable: true
  34318. });
  34319. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  34320. get: function () {
  34321. return Animation._ANIMATIONTYPE_VECTOR2;
  34322. },
  34323. enumerable: true,
  34324. configurable: true
  34325. });
  34326. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  34327. get: function () {
  34328. return Animation._ANIMATIONTYPE_SIZE;
  34329. },
  34330. enumerable: true,
  34331. configurable: true
  34332. });
  34333. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  34334. get: function () {
  34335. return Animation._ANIMATIONTYPE_QUATERNION;
  34336. },
  34337. enumerable: true,
  34338. configurable: true
  34339. });
  34340. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  34341. get: function () {
  34342. return Animation._ANIMATIONTYPE_MATRIX;
  34343. },
  34344. enumerable: true,
  34345. configurable: true
  34346. });
  34347. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  34348. get: function () {
  34349. return Animation._ANIMATIONTYPE_COLOR3;
  34350. },
  34351. enumerable: true,
  34352. configurable: true
  34353. });
  34354. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  34355. get: function () {
  34356. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  34357. },
  34358. enumerable: true,
  34359. configurable: true
  34360. });
  34361. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  34362. get: function () {
  34363. return Animation._ANIMATIONLOOPMODE_CYCLE;
  34364. },
  34365. enumerable: true,
  34366. configurable: true
  34367. });
  34368. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  34369. get: function () {
  34370. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  34371. },
  34372. enumerable: true,
  34373. configurable: true
  34374. });
  34375. Animation.Parse = function (parsedAnimation) {
  34376. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  34377. var dataType = parsedAnimation.dataType;
  34378. var keys = [];
  34379. var data;
  34380. var index;
  34381. if (parsedAnimation.enableBlending) {
  34382. animation.enableBlending = parsedAnimation.enableBlending;
  34383. }
  34384. if (parsedAnimation.blendingSpeed) {
  34385. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  34386. }
  34387. for (index = 0; index < parsedAnimation.keys.length; index++) {
  34388. var key = parsedAnimation.keys[index];
  34389. switch (dataType) {
  34390. case Animation.ANIMATIONTYPE_FLOAT:
  34391. data = key.values[0];
  34392. break;
  34393. case Animation.ANIMATIONTYPE_QUATERNION:
  34394. data = BABYLON.Quaternion.FromArray(key.values);
  34395. break;
  34396. case Animation.ANIMATIONTYPE_MATRIX:
  34397. data = BABYLON.Matrix.FromArray(key.values);
  34398. break;
  34399. case Animation.ANIMATIONTYPE_COLOR3:
  34400. data = BABYLON.Color3.FromArray(key.values);
  34401. break;
  34402. case Animation.ANIMATIONTYPE_VECTOR3:
  34403. default:
  34404. data = BABYLON.Vector3.FromArray(key.values);
  34405. break;
  34406. }
  34407. keys.push({
  34408. frame: key.frame,
  34409. value: data
  34410. });
  34411. }
  34412. animation.setKeys(keys);
  34413. if (parsedAnimation.ranges) {
  34414. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  34415. data = parsedAnimation.ranges[index];
  34416. animation.createRange(data.name, data.from, data.to);
  34417. }
  34418. }
  34419. return animation;
  34420. };
  34421. Animation.AppendSerializedAnimations = function (source, destination) {
  34422. if (source.animations) {
  34423. destination.animations = [];
  34424. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  34425. var animation = source.animations[animationIndex];
  34426. destination.animations.push(animation.serialize());
  34427. }
  34428. }
  34429. };
  34430. return Animation;
  34431. }());
  34432. // Statics
  34433. Animation._ANIMATIONTYPE_FLOAT = 0;
  34434. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  34435. Animation._ANIMATIONTYPE_QUATERNION = 2;
  34436. Animation._ANIMATIONTYPE_MATRIX = 3;
  34437. Animation._ANIMATIONTYPE_COLOR3 = 4;
  34438. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  34439. Animation._ANIMATIONTYPE_SIZE = 6;
  34440. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  34441. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  34442. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  34443. BABYLON.Animation = Animation;
  34444. })(BABYLON || (BABYLON = {}));
  34445. //# sourceMappingURL=babylon.animation.js.map
  34446. var BABYLON;
  34447. (function (BABYLON) {
  34448. var Animatable = (function () {
  34449. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  34450. if (fromFrame === void 0) { fromFrame = 0; }
  34451. if (toFrame === void 0) { toFrame = 100; }
  34452. if (loopAnimation === void 0) { loopAnimation = false; }
  34453. if (speedRatio === void 0) { speedRatio = 1.0; }
  34454. this.target = target;
  34455. this.fromFrame = fromFrame;
  34456. this.toFrame = toFrame;
  34457. this.loopAnimation = loopAnimation;
  34458. this.speedRatio = speedRatio;
  34459. this.onAnimationEnd = onAnimationEnd;
  34460. this._localDelayOffset = null;
  34461. this._pausedDelay = null;
  34462. this._animations = new Array();
  34463. this._paused = false;
  34464. this.animationStarted = false;
  34465. if (animations) {
  34466. this.appendAnimations(target, animations);
  34467. }
  34468. this._scene = scene;
  34469. scene._activeAnimatables.push(this);
  34470. }
  34471. // Methods
  34472. Animatable.prototype.getAnimations = function () {
  34473. return this._animations;
  34474. };
  34475. Animatable.prototype.appendAnimations = function (target, animations) {
  34476. for (var index = 0; index < animations.length; index++) {
  34477. var animation = animations[index];
  34478. animation._target = target;
  34479. this._animations.push(animation);
  34480. }
  34481. };
  34482. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  34483. var animations = this._animations;
  34484. for (var index = 0; index < animations.length; index++) {
  34485. if (animations[index].targetProperty === property) {
  34486. return animations[index];
  34487. }
  34488. }
  34489. return null;
  34490. };
  34491. Animatable.prototype.reset = function () {
  34492. var animations = this._animations;
  34493. for (var index = 0; index < animations.length; index++) {
  34494. animations[index].reset();
  34495. }
  34496. this._localDelayOffset = null;
  34497. this._pausedDelay = null;
  34498. };
  34499. Animatable.prototype.enableBlending = function (blendingSpeed) {
  34500. var animations = this._animations;
  34501. for (var index = 0; index < animations.length; index++) {
  34502. animations[index].enableBlending = true;
  34503. animations[index].blendingSpeed = blendingSpeed;
  34504. }
  34505. };
  34506. Animatable.prototype.disableBlending = function () {
  34507. var animations = this._animations;
  34508. for (var index = 0; index < animations.length; index++) {
  34509. animations[index].enableBlending = false;
  34510. }
  34511. };
  34512. Animatable.prototype.goToFrame = function (frame) {
  34513. var animations = this._animations;
  34514. if (animations[0]) {
  34515. var fps = animations[0].framePerSecond;
  34516. var currentFrame = animations[0].currentFrame;
  34517. var adjustTime = frame - currentFrame;
  34518. var delay = adjustTime * 1000 / fps;
  34519. this._localDelayOffset -= delay;
  34520. }
  34521. for (var index = 0; index < animations.length; index++) {
  34522. animations[index].goToFrame(frame);
  34523. }
  34524. };
  34525. Animatable.prototype.pause = function () {
  34526. if (this._paused) {
  34527. return;
  34528. }
  34529. this._paused = true;
  34530. };
  34531. Animatable.prototype.restart = function () {
  34532. this._paused = false;
  34533. };
  34534. Animatable.prototype.stop = function (animationName) {
  34535. if (animationName) {
  34536. var idx = this._scene._activeAnimatables.indexOf(this);
  34537. if (idx > -1) {
  34538. var animations = this._animations;
  34539. for (var index = animations.length - 1; index >= 0; index--) {
  34540. if (typeof animationName === "string" && animations[index].name != animationName) {
  34541. continue;
  34542. }
  34543. animations[index].reset();
  34544. animations.splice(index, 1);
  34545. }
  34546. if (animations.length == 0) {
  34547. this._scene._activeAnimatables.splice(idx, 1);
  34548. if (this.onAnimationEnd) {
  34549. this.onAnimationEnd();
  34550. }
  34551. }
  34552. }
  34553. }
  34554. else {
  34555. var index = this._scene._activeAnimatables.indexOf(this);
  34556. if (index > -1) {
  34557. this._scene._activeAnimatables.splice(index, 1);
  34558. var animations = this._animations;
  34559. for (var index = 0; index < animations.length; index++) {
  34560. animations[index].reset();
  34561. }
  34562. if (this.onAnimationEnd) {
  34563. this.onAnimationEnd();
  34564. }
  34565. }
  34566. }
  34567. };
  34568. Animatable.prototype._animate = function (delay) {
  34569. if (this._paused) {
  34570. this.animationStarted = false;
  34571. if (this._pausedDelay === null) {
  34572. this._pausedDelay = delay;
  34573. }
  34574. return true;
  34575. }
  34576. if (this._localDelayOffset === null) {
  34577. this._localDelayOffset = delay;
  34578. }
  34579. else if (this._pausedDelay !== null) {
  34580. this._localDelayOffset += delay - this._pausedDelay;
  34581. this._pausedDelay = null;
  34582. }
  34583. // Animating
  34584. var running = false;
  34585. var animations = this._animations;
  34586. var index;
  34587. for (index = 0; index < animations.length; index++) {
  34588. var animation = animations[index];
  34589. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  34590. running = running || isRunning;
  34591. }
  34592. this.animationStarted = running;
  34593. if (!running) {
  34594. // Remove from active animatables
  34595. index = this._scene._activeAnimatables.indexOf(this);
  34596. this._scene._activeAnimatables.splice(index, 1);
  34597. }
  34598. if (!running && this.onAnimationEnd) {
  34599. this.onAnimationEnd();
  34600. this.onAnimationEnd = null;
  34601. }
  34602. return running;
  34603. };
  34604. return Animatable;
  34605. }());
  34606. BABYLON.Animatable = Animatable;
  34607. })(BABYLON || (BABYLON = {}));
  34608. //# sourceMappingURL=babylon.animatable.js.map
  34609. var BABYLON;
  34610. (function (BABYLON) {
  34611. var EasingFunction = (function () {
  34612. function EasingFunction() {
  34613. // Properties
  34614. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  34615. }
  34616. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  34617. get: function () {
  34618. return EasingFunction._EASINGMODE_EASEIN;
  34619. },
  34620. enumerable: true,
  34621. configurable: true
  34622. });
  34623. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  34624. get: function () {
  34625. return EasingFunction._EASINGMODE_EASEOUT;
  34626. },
  34627. enumerable: true,
  34628. configurable: true
  34629. });
  34630. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  34631. get: function () {
  34632. return EasingFunction._EASINGMODE_EASEINOUT;
  34633. },
  34634. enumerable: true,
  34635. configurable: true
  34636. });
  34637. EasingFunction.prototype.setEasingMode = function (easingMode) {
  34638. var n = Math.min(Math.max(easingMode, 0), 2);
  34639. this._easingMode = n;
  34640. };
  34641. EasingFunction.prototype.getEasingMode = function () {
  34642. return this._easingMode;
  34643. };
  34644. EasingFunction.prototype.easeInCore = function (gradient) {
  34645. throw new Error('You must implement this method');
  34646. };
  34647. EasingFunction.prototype.ease = function (gradient) {
  34648. switch (this._easingMode) {
  34649. case EasingFunction.EASINGMODE_EASEIN:
  34650. return this.easeInCore(gradient);
  34651. case EasingFunction.EASINGMODE_EASEOUT:
  34652. return (1 - this.easeInCore(1 - gradient));
  34653. }
  34654. if (gradient >= 0.5) {
  34655. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  34656. }
  34657. return (this.easeInCore(gradient * 2) * 0.5);
  34658. };
  34659. return EasingFunction;
  34660. }());
  34661. //Statics
  34662. EasingFunction._EASINGMODE_EASEIN = 0;
  34663. EasingFunction._EASINGMODE_EASEOUT = 1;
  34664. EasingFunction._EASINGMODE_EASEINOUT = 2;
  34665. BABYLON.EasingFunction = EasingFunction;
  34666. var CircleEase = (function (_super) {
  34667. __extends(CircleEase, _super);
  34668. function CircleEase() {
  34669. return _super !== null && _super.apply(this, arguments) || this;
  34670. }
  34671. CircleEase.prototype.easeInCore = function (gradient) {
  34672. gradient = Math.max(0, Math.min(1, gradient));
  34673. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  34674. };
  34675. return CircleEase;
  34676. }(EasingFunction));
  34677. BABYLON.CircleEase = CircleEase;
  34678. var BackEase = (function (_super) {
  34679. __extends(BackEase, _super);
  34680. function BackEase(amplitude) {
  34681. if (amplitude === void 0) { amplitude = 1; }
  34682. var _this = _super.call(this) || this;
  34683. _this.amplitude = amplitude;
  34684. return _this;
  34685. }
  34686. BackEase.prototype.easeInCore = function (gradient) {
  34687. var num = Math.max(0, this.amplitude);
  34688. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  34689. };
  34690. return BackEase;
  34691. }(EasingFunction));
  34692. BABYLON.BackEase = BackEase;
  34693. var BounceEase = (function (_super) {
  34694. __extends(BounceEase, _super);
  34695. function BounceEase(bounces, bounciness) {
  34696. if (bounces === void 0) { bounces = 3; }
  34697. if (bounciness === void 0) { bounciness = 2; }
  34698. var _this = _super.call(this) || this;
  34699. _this.bounces = bounces;
  34700. _this.bounciness = bounciness;
  34701. return _this;
  34702. }
  34703. BounceEase.prototype.easeInCore = function (gradient) {
  34704. var y = Math.max(0.0, this.bounces);
  34705. var bounciness = this.bounciness;
  34706. if (bounciness <= 1.0) {
  34707. bounciness = 1.001;
  34708. }
  34709. var num9 = Math.pow(bounciness, y);
  34710. var num5 = 1.0 - bounciness;
  34711. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  34712. var num15 = gradient * num4;
  34713. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  34714. var num3 = Math.floor(num65);
  34715. var num13 = num3 + 1.0;
  34716. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  34717. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  34718. var num7 = (num8 + num12) * 0.5;
  34719. var num6 = gradient - num7;
  34720. var num2 = num7 - num8;
  34721. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  34722. };
  34723. return BounceEase;
  34724. }(EasingFunction));
  34725. BABYLON.BounceEase = BounceEase;
  34726. var CubicEase = (function (_super) {
  34727. __extends(CubicEase, _super);
  34728. function CubicEase() {
  34729. return _super !== null && _super.apply(this, arguments) || this;
  34730. }
  34731. CubicEase.prototype.easeInCore = function (gradient) {
  34732. return (gradient * gradient * gradient);
  34733. };
  34734. return CubicEase;
  34735. }(EasingFunction));
  34736. BABYLON.CubicEase = CubicEase;
  34737. var ElasticEase = (function (_super) {
  34738. __extends(ElasticEase, _super);
  34739. function ElasticEase(oscillations, springiness) {
  34740. if (oscillations === void 0) { oscillations = 3; }
  34741. if (springiness === void 0) { springiness = 3; }
  34742. var _this = _super.call(this) || this;
  34743. _this.oscillations = oscillations;
  34744. _this.springiness = springiness;
  34745. return _this;
  34746. }
  34747. ElasticEase.prototype.easeInCore = function (gradient) {
  34748. var num2;
  34749. var num3 = Math.max(0.0, this.oscillations);
  34750. var num = Math.max(0.0, this.springiness);
  34751. if (num == 0) {
  34752. num2 = gradient;
  34753. }
  34754. else {
  34755. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  34756. }
  34757. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  34758. };
  34759. return ElasticEase;
  34760. }(EasingFunction));
  34761. BABYLON.ElasticEase = ElasticEase;
  34762. var ExponentialEase = (function (_super) {
  34763. __extends(ExponentialEase, _super);
  34764. function ExponentialEase(exponent) {
  34765. if (exponent === void 0) { exponent = 2; }
  34766. var _this = _super.call(this) || this;
  34767. _this.exponent = exponent;
  34768. return _this;
  34769. }
  34770. ExponentialEase.prototype.easeInCore = function (gradient) {
  34771. if (this.exponent <= 0) {
  34772. return gradient;
  34773. }
  34774. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  34775. };
  34776. return ExponentialEase;
  34777. }(EasingFunction));
  34778. BABYLON.ExponentialEase = ExponentialEase;
  34779. var PowerEase = (function (_super) {
  34780. __extends(PowerEase, _super);
  34781. function PowerEase(power) {
  34782. if (power === void 0) { power = 2; }
  34783. var _this = _super.call(this) || this;
  34784. _this.power = power;
  34785. return _this;
  34786. }
  34787. PowerEase.prototype.easeInCore = function (gradient) {
  34788. var y = Math.max(0.0, this.power);
  34789. return Math.pow(gradient, y);
  34790. };
  34791. return PowerEase;
  34792. }(EasingFunction));
  34793. BABYLON.PowerEase = PowerEase;
  34794. var QuadraticEase = (function (_super) {
  34795. __extends(QuadraticEase, _super);
  34796. function QuadraticEase() {
  34797. return _super !== null && _super.apply(this, arguments) || this;
  34798. }
  34799. QuadraticEase.prototype.easeInCore = function (gradient) {
  34800. return (gradient * gradient);
  34801. };
  34802. return QuadraticEase;
  34803. }(EasingFunction));
  34804. BABYLON.QuadraticEase = QuadraticEase;
  34805. var QuarticEase = (function (_super) {
  34806. __extends(QuarticEase, _super);
  34807. function QuarticEase() {
  34808. return _super !== null && _super.apply(this, arguments) || this;
  34809. }
  34810. QuarticEase.prototype.easeInCore = function (gradient) {
  34811. return (gradient * gradient * gradient * gradient);
  34812. };
  34813. return QuarticEase;
  34814. }(EasingFunction));
  34815. BABYLON.QuarticEase = QuarticEase;
  34816. var QuinticEase = (function (_super) {
  34817. __extends(QuinticEase, _super);
  34818. function QuinticEase() {
  34819. return _super !== null && _super.apply(this, arguments) || this;
  34820. }
  34821. QuinticEase.prototype.easeInCore = function (gradient) {
  34822. return (gradient * gradient * gradient * gradient * gradient);
  34823. };
  34824. return QuinticEase;
  34825. }(EasingFunction));
  34826. BABYLON.QuinticEase = QuinticEase;
  34827. var SineEase = (function (_super) {
  34828. __extends(SineEase, _super);
  34829. function SineEase() {
  34830. return _super !== null && _super.apply(this, arguments) || this;
  34831. }
  34832. SineEase.prototype.easeInCore = function (gradient) {
  34833. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  34834. };
  34835. return SineEase;
  34836. }(EasingFunction));
  34837. BABYLON.SineEase = SineEase;
  34838. var BezierCurveEase = (function (_super) {
  34839. __extends(BezierCurveEase, _super);
  34840. function BezierCurveEase(x1, y1, x2, y2) {
  34841. if (x1 === void 0) { x1 = 0; }
  34842. if (y1 === void 0) { y1 = 0; }
  34843. if (x2 === void 0) { x2 = 1; }
  34844. if (y2 === void 0) { y2 = 1; }
  34845. var _this = _super.call(this) || this;
  34846. _this.x1 = x1;
  34847. _this.y1 = y1;
  34848. _this.x2 = x2;
  34849. _this.y2 = y2;
  34850. return _this;
  34851. }
  34852. BezierCurveEase.prototype.easeInCore = function (gradient) {
  34853. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  34854. };
  34855. return BezierCurveEase;
  34856. }(EasingFunction));
  34857. BABYLON.BezierCurveEase = BezierCurveEase;
  34858. })(BABYLON || (BABYLON = {}));
  34859. //# sourceMappingURL=babylon.easing.js.map
  34860. var BABYLON;
  34861. (function (BABYLON) {
  34862. var Condition = (function () {
  34863. function Condition(actionManager) {
  34864. this._actionManager = actionManager;
  34865. }
  34866. Condition.prototype.isValid = function () {
  34867. return true;
  34868. };
  34869. Condition.prototype._getProperty = function (propertyPath) {
  34870. return this._actionManager._getProperty(propertyPath);
  34871. };
  34872. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  34873. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34874. };
  34875. Condition.prototype.serialize = function () {
  34876. };
  34877. Condition.prototype._serialize = function (serializedCondition) {
  34878. return {
  34879. type: 2,
  34880. children: [],
  34881. name: serializedCondition.name,
  34882. properties: serializedCondition.properties
  34883. };
  34884. };
  34885. return Condition;
  34886. }());
  34887. BABYLON.Condition = Condition;
  34888. var ValueCondition = (function (_super) {
  34889. __extends(ValueCondition, _super);
  34890. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  34891. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  34892. var _this = _super.call(this, actionManager) || this;
  34893. _this.propertyPath = propertyPath;
  34894. _this.value = value;
  34895. _this.operator = operator;
  34896. _this._target = target;
  34897. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  34898. _this._property = _this._getProperty(_this.propertyPath);
  34899. return _this;
  34900. }
  34901. Object.defineProperty(ValueCondition, "IsEqual", {
  34902. get: function () {
  34903. return ValueCondition._IsEqual;
  34904. },
  34905. enumerable: true,
  34906. configurable: true
  34907. });
  34908. Object.defineProperty(ValueCondition, "IsDifferent", {
  34909. get: function () {
  34910. return ValueCondition._IsDifferent;
  34911. },
  34912. enumerable: true,
  34913. configurable: true
  34914. });
  34915. Object.defineProperty(ValueCondition, "IsGreater", {
  34916. get: function () {
  34917. return ValueCondition._IsGreater;
  34918. },
  34919. enumerable: true,
  34920. configurable: true
  34921. });
  34922. Object.defineProperty(ValueCondition, "IsLesser", {
  34923. get: function () {
  34924. return ValueCondition._IsLesser;
  34925. },
  34926. enumerable: true,
  34927. configurable: true
  34928. });
  34929. // Methods
  34930. ValueCondition.prototype.isValid = function () {
  34931. switch (this.operator) {
  34932. case ValueCondition.IsGreater:
  34933. return this._effectiveTarget[this._property] > this.value;
  34934. case ValueCondition.IsLesser:
  34935. return this._effectiveTarget[this._property] < this.value;
  34936. case ValueCondition.IsEqual:
  34937. case ValueCondition.IsDifferent:
  34938. var check;
  34939. if (this.value.equals) {
  34940. check = this.value.equals(this._effectiveTarget[this._property]);
  34941. }
  34942. else {
  34943. check = this.value === this._effectiveTarget[this._property];
  34944. }
  34945. return this.operator === ValueCondition.IsEqual ? check : !check;
  34946. }
  34947. return false;
  34948. };
  34949. ValueCondition.prototype.serialize = function () {
  34950. return this._serialize({
  34951. name: "ValueCondition",
  34952. properties: [
  34953. BABYLON.Action._GetTargetProperty(this._target),
  34954. { name: "propertyPath", value: this.propertyPath },
  34955. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34956. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  34957. ]
  34958. });
  34959. };
  34960. ValueCondition.GetOperatorName = function (operator) {
  34961. switch (operator) {
  34962. case ValueCondition._IsEqual: return "IsEqual";
  34963. case ValueCondition._IsDifferent: return "IsDifferent";
  34964. case ValueCondition._IsGreater: return "IsGreater";
  34965. case ValueCondition._IsLesser: return "IsLesser";
  34966. default: return "";
  34967. }
  34968. };
  34969. return ValueCondition;
  34970. }(Condition));
  34971. // Statics
  34972. ValueCondition._IsEqual = 0;
  34973. ValueCondition._IsDifferent = 1;
  34974. ValueCondition._IsGreater = 2;
  34975. ValueCondition._IsLesser = 3;
  34976. BABYLON.ValueCondition = ValueCondition;
  34977. var PredicateCondition = (function (_super) {
  34978. __extends(PredicateCondition, _super);
  34979. function PredicateCondition(actionManager, predicate) {
  34980. var _this = _super.call(this, actionManager) || this;
  34981. _this.predicate = predicate;
  34982. return _this;
  34983. }
  34984. PredicateCondition.prototype.isValid = function () {
  34985. return this.predicate();
  34986. };
  34987. return PredicateCondition;
  34988. }(Condition));
  34989. BABYLON.PredicateCondition = PredicateCondition;
  34990. var StateCondition = (function (_super) {
  34991. __extends(StateCondition, _super);
  34992. function StateCondition(actionManager, target, value) {
  34993. var _this = _super.call(this, actionManager) || this;
  34994. _this.value = value;
  34995. _this._target = target;
  34996. return _this;
  34997. }
  34998. // Methods
  34999. StateCondition.prototype.isValid = function () {
  35000. return this._target.state === this.value;
  35001. };
  35002. StateCondition.prototype.serialize = function () {
  35003. return this._serialize({
  35004. name: "StateCondition",
  35005. properties: [
  35006. BABYLON.Action._GetTargetProperty(this._target),
  35007. { name: "value", value: this.value }
  35008. ]
  35009. });
  35010. };
  35011. return StateCondition;
  35012. }(Condition));
  35013. BABYLON.StateCondition = StateCondition;
  35014. })(BABYLON || (BABYLON = {}));
  35015. //# sourceMappingURL=babylon.condition.js.map
  35016. var BABYLON;
  35017. (function (BABYLON) {
  35018. var Action = (function () {
  35019. function Action(triggerOptions, condition) {
  35020. this.triggerOptions = triggerOptions;
  35021. if (triggerOptions.parameter) {
  35022. this.trigger = triggerOptions.trigger;
  35023. this._triggerParameter = triggerOptions.parameter;
  35024. }
  35025. else {
  35026. this.trigger = triggerOptions;
  35027. }
  35028. this._nextActiveAction = this;
  35029. this._condition = condition;
  35030. }
  35031. // Methods
  35032. Action.prototype._prepare = function () {
  35033. };
  35034. Action.prototype.getTriggerParameter = function () {
  35035. return this._triggerParameter;
  35036. };
  35037. Action.prototype._executeCurrent = function (evt) {
  35038. if (this._nextActiveAction._condition) {
  35039. var condition = this._nextActiveAction._condition;
  35040. var currentRenderId = this._actionManager.getScene().getRenderId();
  35041. // We cache the current evaluation for the current frame
  35042. if (condition._evaluationId === currentRenderId) {
  35043. if (!condition._currentResult) {
  35044. return;
  35045. }
  35046. }
  35047. else {
  35048. condition._evaluationId = currentRenderId;
  35049. if (!condition.isValid()) {
  35050. condition._currentResult = false;
  35051. return;
  35052. }
  35053. condition._currentResult = true;
  35054. }
  35055. }
  35056. this._nextActiveAction.execute(evt);
  35057. this.skipToNextActiveAction();
  35058. };
  35059. Action.prototype.execute = function (evt) {
  35060. };
  35061. Action.prototype.skipToNextActiveAction = function () {
  35062. if (this._nextActiveAction._child) {
  35063. if (!this._nextActiveAction._child._actionManager) {
  35064. this._nextActiveAction._child._actionManager = this._actionManager;
  35065. }
  35066. this._nextActiveAction = this._nextActiveAction._child;
  35067. }
  35068. else {
  35069. this._nextActiveAction = this;
  35070. }
  35071. };
  35072. Action.prototype.then = function (action) {
  35073. this._child = action;
  35074. action._actionManager = this._actionManager;
  35075. action._prepare();
  35076. return action;
  35077. };
  35078. Action.prototype._getProperty = function (propertyPath) {
  35079. return this._actionManager._getProperty(propertyPath);
  35080. };
  35081. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35082. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35083. };
  35084. Action.prototype.serialize = function (parent) {
  35085. };
  35086. // Called by BABYLON.Action objects in serialize(...). Internal use
  35087. Action.prototype._serialize = function (serializedAction, parent) {
  35088. var serializationObject = {
  35089. type: 1,
  35090. children: [],
  35091. name: serializedAction.name,
  35092. properties: serializedAction.properties || []
  35093. };
  35094. // Serialize child
  35095. if (this._child) {
  35096. this._child.serialize(serializationObject);
  35097. }
  35098. // Check if "this" has a condition
  35099. if (this._condition) {
  35100. var serializedCondition = this._condition.serialize();
  35101. serializedCondition.children.push(serializationObject);
  35102. if (parent) {
  35103. parent.children.push(serializedCondition);
  35104. }
  35105. return serializedCondition;
  35106. }
  35107. if (parent) {
  35108. parent.children.push(serializationObject);
  35109. }
  35110. return serializationObject;
  35111. };
  35112. return Action;
  35113. }());
  35114. Action._SerializeValueAsString = function (value) {
  35115. if (typeof value === "number") {
  35116. return value.toString();
  35117. }
  35118. if (typeof value === "boolean") {
  35119. return value ? "true" : "false";
  35120. }
  35121. if (value instanceof BABYLON.Vector2) {
  35122. return value.x + ", " + value.y;
  35123. }
  35124. if (value instanceof BABYLON.Vector3) {
  35125. return value.x + ", " + value.y + ", " + value.z;
  35126. }
  35127. if (value instanceof BABYLON.Color3) {
  35128. return value.r + ", " + value.g + ", " + value.b;
  35129. }
  35130. if (value instanceof BABYLON.Color4) {
  35131. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35132. }
  35133. return value; // string
  35134. };
  35135. Action._GetTargetProperty = function (target) {
  35136. return {
  35137. name: "target",
  35138. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35139. : target instanceof BABYLON.Light ? "LightProperties"
  35140. : target instanceof BABYLON.Camera ? "CameraProperties"
  35141. : "SceneProperties",
  35142. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35143. };
  35144. };
  35145. BABYLON.Action = Action;
  35146. })(BABYLON || (BABYLON = {}));
  35147. //# sourceMappingURL=babylon.action.js.map
  35148. var BABYLON;
  35149. (function (BABYLON) {
  35150. /**
  35151. * ActionEvent is the event beint sent when an action is triggered.
  35152. */
  35153. var ActionEvent = (function () {
  35154. /**
  35155. * @constructor
  35156. * @param source The mesh or sprite that triggered the action.
  35157. * @param pointerX The X mouse cursor position at the time of the event
  35158. * @param pointerY The Y mouse cursor position at the time of the event
  35159. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35160. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35161. */
  35162. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35163. this.source = source;
  35164. this.pointerX = pointerX;
  35165. this.pointerY = pointerY;
  35166. this.meshUnderPointer = meshUnderPointer;
  35167. this.sourceEvent = sourceEvent;
  35168. this.additionalData = additionalData;
  35169. }
  35170. /**
  35171. * Helper function to auto-create an ActionEvent from a source mesh.
  35172. * @param source The source mesh that triggered the event
  35173. * @param evt {Event} The original (browser) event
  35174. */
  35175. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35176. var scene = source.getScene();
  35177. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35178. };
  35179. /**
  35180. * Helper function to auto-create an ActionEvent from a source mesh.
  35181. * @param source The source sprite that triggered the event
  35182. * @param scene Scene associated with the sprite
  35183. * @param evt {Event} The original (browser) event
  35184. */
  35185. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35186. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35187. };
  35188. /**
  35189. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35190. * @param scene the scene where the event occurred
  35191. * @param evt {Event} The original (browser) event
  35192. */
  35193. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35194. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35195. };
  35196. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35197. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35198. };
  35199. return ActionEvent;
  35200. }());
  35201. BABYLON.ActionEvent = ActionEvent;
  35202. /**
  35203. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35204. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35205. */
  35206. var ActionManager = (function () {
  35207. function ActionManager(scene) {
  35208. // Members
  35209. this.actions = new Array();
  35210. this.hoverCursor = '';
  35211. this._scene = scene;
  35212. scene._actionManagers.push(this);
  35213. }
  35214. Object.defineProperty(ActionManager, "NothingTrigger", {
  35215. get: function () {
  35216. return ActionManager._NothingTrigger;
  35217. },
  35218. enumerable: true,
  35219. configurable: true
  35220. });
  35221. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35222. get: function () {
  35223. return ActionManager._OnPickTrigger;
  35224. },
  35225. enumerable: true,
  35226. configurable: true
  35227. });
  35228. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35229. get: function () {
  35230. return ActionManager._OnLeftPickTrigger;
  35231. },
  35232. enumerable: true,
  35233. configurable: true
  35234. });
  35235. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35236. get: function () {
  35237. return ActionManager._OnRightPickTrigger;
  35238. },
  35239. enumerable: true,
  35240. configurable: true
  35241. });
  35242. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35243. get: function () {
  35244. return ActionManager._OnCenterPickTrigger;
  35245. },
  35246. enumerable: true,
  35247. configurable: true
  35248. });
  35249. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35250. get: function () {
  35251. return ActionManager._OnPickDownTrigger;
  35252. },
  35253. enumerable: true,
  35254. configurable: true
  35255. });
  35256. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  35257. get: function () {
  35258. return ActionManager._OnDoublePickTrigger;
  35259. },
  35260. enumerable: true,
  35261. configurable: true
  35262. });
  35263. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35264. get: function () {
  35265. return ActionManager._OnPickUpTrigger;
  35266. },
  35267. enumerable: true,
  35268. configurable: true
  35269. });
  35270. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35271. /// This trigger will only be raised if you also declared a OnPickDown
  35272. get: function () {
  35273. return ActionManager._OnPickOutTrigger;
  35274. },
  35275. enumerable: true,
  35276. configurable: true
  35277. });
  35278. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35279. get: function () {
  35280. return ActionManager._OnLongPressTrigger;
  35281. },
  35282. enumerable: true,
  35283. configurable: true
  35284. });
  35285. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35286. get: function () {
  35287. return ActionManager._OnPointerOverTrigger;
  35288. },
  35289. enumerable: true,
  35290. configurable: true
  35291. });
  35292. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35293. get: function () {
  35294. return ActionManager._OnPointerOutTrigger;
  35295. },
  35296. enumerable: true,
  35297. configurable: true
  35298. });
  35299. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  35300. get: function () {
  35301. return ActionManager._OnEveryFrameTrigger;
  35302. },
  35303. enumerable: true,
  35304. configurable: true
  35305. });
  35306. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  35307. get: function () {
  35308. return ActionManager._OnIntersectionEnterTrigger;
  35309. },
  35310. enumerable: true,
  35311. configurable: true
  35312. });
  35313. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  35314. get: function () {
  35315. return ActionManager._OnIntersectionExitTrigger;
  35316. },
  35317. enumerable: true,
  35318. configurable: true
  35319. });
  35320. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  35321. get: function () {
  35322. return ActionManager._OnKeyDownTrigger;
  35323. },
  35324. enumerable: true,
  35325. configurable: true
  35326. });
  35327. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  35328. get: function () {
  35329. return ActionManager._OnKeyUpTrigger;
  35330. },
  35331. enumerable: true,
  35332. configurable: true
  35333. });
  35334. // Methods
  35335. ActionManager.prototype.dispose = function () {
  35336. var index = this._scene._actionManagers.indexOf(this);
  35337. for (var i = 0; i < this.actions.length; i++) {
  35338. var action = this.actions[i];
  35339. ActionManager.Triggers[action.trigger]--;
  35340. if (ActionManager.Triggers[action.trigger] === 0) {
  35341. delete ActionManager.Triggers[action.trigger];
  35342. }
  35343. }
  35344. if (index > -1) {
  35345. this._scene._actionManagers.splice(index, 1);
  35346. }
  35347. };
  35348. ActionManager.prototype.getScene = function () {
  35349. return this._scene;
  35350. };
  35351. /**
  35352. * Does this action manager handles actions of any of the given triggers
  35353. * @param {number[]} triggers - the triggers to be tested
  35354. * @return {boolean} whether one (or more) of the triggers is handeled
  35355. */
  35356. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  35357. for (var index = 0; index < this.actions.length; index++) {
  35358. var action = this.actions[index];
  35359. if (triggers.indexOf(action.trigger) > -1) {
  35360. return true;
  35361. }
  35362. }
  35363. return false;
  35364. };
  35365. /**
  35366. * Does this action manager handles actions of a given trigger
  35367. * @param {number} trigger - the trigger to be tested
  35368. * @return {boolean} whether the trigger is handeled
  35369. */
  35370. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  35371. for (var index = 0; index < this.actions.length; index++) {
  35372. var action = this.actions[index];
  35373. if (action.trigger === trigger) {
  35374. return true;
  35375. }
  35376. }
  35377. return false;
  35378. };
  35379. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  35380. /**
  35381. * Does this action manager has pointer triggers
  35382. * @return {boolean} whether or not it has pointer triggers
  35383. */
  35384. get: function () {
  35385. for (var index = 0; index < this.actions.length; index++) {
  35386. var action = this.actions[index];
  35387. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  35388. return true;
  35389. }
  35390. }
  35391. return false;
  35392. },
  35393. enumerable: true,
  35394. configurable: true
  35395. });
  35396. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  35397. /**
  35398. * Does this action manager has pick triggers
  35399. * @return {boolean} whether or not it has pick triggers
  35400. */
  35401. get: function () {
  35402. for (var index = 0; index < this.actions.length; index++) {
  35403. var action = this.actions[index];
  35404. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  35405. return true;
  35406. }
  35407. }
  35408. return false;
  35409. },
  35410. enumerable: true,
  35411. configurable: true
  35412. });
  35413. Object.defineProperty(ActionManager, "HasTriggers", {
  35414. /**
  35415. * Does exist one action manager with at least one trigger
  35416. * @return {boolean} whether or not it exists one action manager with one trigger
  35417. **/
  35418. get: function () {
  35419. for (var t in ActionManager.Triggers) {
  35420. if (ActionManager.Triggers.hasOwnProperty(t)) {
  35421. return true;
  35422. }
  35423. }
  35424. return false;
  35425. },
  35426. enumerable: true,
  35427. configurable: true
  35428. });
  35429. Object.defineProperty(ActionManager, "HasPickTriggers", {
  35430. /**
  35431. * Does exist one action manager with at least one pick trigger
  35432. * @return {boolean} whether or not it exists one action manager with one pick trigger
  35433. **/
  35434. get: function () {
  35435. for (var t in ActionManager.Triggers) {
  35436. if (ActionManager.Triggers.hasOwnProperty(t)) {
  35437. var t_int = parseInt(t);
  35438. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  35439. return true;
  35440. }
  35441. }
  35442. }
  35443. return false;
  35444. },
  35445. enumerable: true,
  35446. configurable: true
  35447. });
  35448. /**
  35449. * Does exist one action manager that handles actions of a given trigger
  35450. * @param {number} trigger - the trigger to be tested
  35451. * @return {boolean} whether the trigger is handeled by at least one action manager
  35452. **/
  35453. ActionManager.HasSpecificTrigger = function (trigger) {
  35454. for (var t in ActionManager.Triggers) {
  35455. if (ActionManager.Triggers.hasOwnProperty(t)) {
  35456. var t_int = parseInt(t);
  35457. if (t_int === trigger) {
  35458. return true;
  35459. }
  35460. }
  35461. }
  35462. return false;
  35463. };
  35464. /**
  35465. * Registers an action to this action manager
  35466. * @param {BABYLON.Action} action - the action to be registered
  35467. * @return {BABYLON.Action} the action amended (prepared) after registration
  35468. */
  35469. ActionManager.prototype.registerAction = function (action) {
  35470. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  35471. if (this.getScene().actionManager !== this) {
  35472. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  35473. return null;
  35474. }
  35475. }
  35476. this.actions.push(action);
  35477. if (ActionManager.Triggers[action.trigger]) {
  35478. ActionManager.Triggers[action.trigger]++;
  35479. }
  35480. else {
  35481. ActionManager.Triggers[action.trigger] = 1;
  35482. }
  35483. action._actionManager = this;
  35484. action._prepare();
  35485. return action;
  35486. };
  35487. /**
  35488. * Process a specific trigger
  35489. * @param {number} trigger - the trigger to process
  35490. * @param evt {BABYLON.ActionEvent} the event details to be processed
  35491. */
  35492. ActionManager.prototype.processTrigger = function (trigger, evt) {
  35493. for (var index = 0; index < this.actions.length; index++) {
  35494. var action = this.actions[index];
  35495. if (action.trigger === trigger) {
  35496. if (trigger === ActionManager.OnKeyUpTrigger
  35497. || trigger === ActionManager.OnKeyDownTrigger) {
  35498. var parameter = action.getTriggerParameter();
  35499. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  35500. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  35501. var actualkey = String.fromCharCode(unicode).toLowerCase();
  35502. if (actualkey !== parameter.toLowerCase()) {
  35503. continue;
  35504. }
  35505. }
  35506. }
  35507. action._executeCurrent(evt);
  35508. }
  35509. }
  35510. };
  35511. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  35512. var properties = propertyPath.split(".");
  35513. for (var index = 0; index < properties.length - 1; index++) {
  35514. target = target[properties[index]];
  35515. }
  35516. return target;
  35517. };
  35518. ActionManager.prototype._getProperty = function (propertyPath) {
  35519. var properties = propertyPath.split(".");
  35520. return properties[properties.length - 1];
  35521. };
  35522. ActionManager.prototype.serialize = function (name) {
  35523. var root = {
  35524. children: [],
  35525. name: name,
  35526. type: 3,
  35527. properties: [] // Empty for root but required
  35528. };
  35529. for (var i = 0; i < this.actions.length; i++) {
  35530. var triggerObject = {
  35531. type: 0,
  35532. children: [],
  35533. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  35534. properties: []
  35535. };
  35536. var triggerOptions = this.actions[i].triggerOptions;
  35537. if (triggerOptions && typeof triggerOptions !== "number") {
  35538. if (triggerOptions.parameter instanceof BABYLON.Node) {
  35539. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  35540. }
  35541. else {
  35542. var parameter = {};
  35543. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  35544. if (triggerOptions.parameter.mesh) {
  35545. parameter._meshId = triggerOptions.parameter.mesh.id;
  35546. }
  35547. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  35548. }
  35549. }
  35550. // Serialize child action, recursively
  35551. this.actions[i].serialize(triggerObject);
  35552. // Add serialized trigger
  35553. root.children.push(triggerObject);
  35554. }
  35555. return root;
  35556. };
  35557. ActionManager.Parse = function (parsedActions, object, scene) {
  35558. var actionManager = new BABYLON.ActionManager(scene);
  35559. if (object === null)
  35560. scene.actionManager = actionManager;
  35561. else
  35562. object.actionManager = actionManager;
  35563. // instanciate a new object
  35564. var instanciate = function (name, params) {
  35565. var newInstance = Object.create(BABYLON[name].prototype);
  35566. newInstance.constructor.apply(newInstance, params);
  35567. return newInstance;
  35568. };
  35569. var parseParameter = function (name, value, target, propertyPath) {
  35570. if (propertyPath === null) {
  35571. // String, boolean or float
  35572. var floatValue = parseFloat(value);
  35573. if (value === "true" || value === "false")
  35574. return value === "true";
  35575. else
  35576. return isNaN(floatValue) ? value : floatValue;
  35577. }
  35578. var effectiveTarget = propertyPath.split(".");
  35579. var values = value.split(",");
  35580. // Get effective Target
  35581. for (var i = 0; i < effectiveTarget.length; i++) {
  35582. target = target[effectiveTarget[i]];
  35583. }
  35584. // Return appropriate value with its type
  35585. if (typeof (target) === "boolean")
  35586. return values[0] === "true";
  35587. if (typeof (target) === "string")
  35588. return values[0];
  35589. // Parameters with multiple values such as Vector3 etc.
  35590. var split = new Array();
  35591. for (var i = 0; i < values.length; i++)
  35592. split.push(parseFloat(values[i]));
  35593. if (target instanceof BABYLON.Vector3)
  35594. return BABYLON.Vector3.FromArray(split);
  35595. if (target instanceof BABYLON.Vector4)
  35596. return BABYLON.Vector4.FromArray(split);
  35597. if (target instanceof BABYLON.Color3)
  35598. return BABYLON.Color3.FromArray(split);
  35599. if (target instanceof BABYLON.Color4)
  35600. return BABYLON.Color4.FromArray(split);
  35601. return parseFloat(values[0]);
  35602. };
  35603. // traverse graph per trigger
  35604. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  35605. if (combineArray === void 0) { combineArray = null; }
  35606. if (parsedAction.detached)
  35607. return;
  35608. var parameters = new Array();
  35609. var target = null;
  35610. var propertyPath = null;
  35611. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  35612. // Parameters
  35613. if (parsedAction.type === 2)
  35614. parameters.push(actionManager);
  35615. else
  35616. parameters.push(trigger);
  35617. if (combine) {
  35618. var actions = new Array();
  35619. for (var j = 0; j < parsedAction.combine.length; j++) {
  35620. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  35621. }
  35622. parameters.push(actions);
  35623. }
  35624. else {
  35625. for (var i = 0; i < parsedAction.properties.length; i++) {
  35626. var value = parsedAction.properties[i].value;
  35627. var name = parsedAction.properties[i].name;
  35628. var targetType = parsedAction.properties[i].targetType;
  35629. if (name === "target")
  35630. if (targetType !== null && targetType === "SceneProperties")
  35631. value = target = scene;
  35632. else
  35633. value = target = scene.getNodeByName(value);
  35634. else if (name === "parent")
  35635. value = scene.getNodeByName(value);
  35636. else if (name === "sound")
  35637. value = scene.getSoundByName(value);
  35638. else if (name !== "propertyPath") {
  35639. if (parsedAction.type === 2 && name === "operator")
  35640. value = BABYLON.ValueCondition[value];
  35641. else
  35642. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  35643. }
  35644. else {
  35645. propertyPath = value;
  35646. }
  35647. parameters.push(value);
  35648. }
  35649. }
  35650. if (combineArray === null) {
  35651. parameters.push(condition);
  35652. }
  35653. else {
  35654. parameters.push(null);
  35655. }
  35656. // If interpolate value action
  35657. if (parsedAction.name === "InterpolateValueAction") {
  35658. var param = parameters[parameters.length - 2];
  35659. parameters[parameters.length - 1] = param;
  35660. parameters[parameters.length - 2] = condition;
  35661. }
  35662. // Action or condition(s) and not CombineAction
  35663. var newAction = instanciate(parsedAction.name, parameters);
  35664. if (newAction instanceof BABYLON.Condition && condition !== null) {
  35665. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  35666. if (action)
  35667. action.then(nothing);
  35668. else
  35669. actionManager.registerAction(nothing);
  35670. action = nothing;
  35671. }
  35672. if (combineArray === null) {
  35673. if (newAction instanceof BABYLON.Condition) {
  35674. condition = newAction;
  35675. newAction = action;
  35676. }
  35677. else {
  35678. condition = null;
  35679. if (action)
  35680. action.then(newAction);
  35681. else
  35682. actionManager.registerAction(newAction);
  35683. }
  35684. }
  35685. else {
  35686. combineArray.push(newAction);
  35687. }
  35688. for (var i = 0; i < parsedAction.children.length; i++)
  35689. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  35690. };
  35691. // triggers
  35692. for (var i = 0; i < parsedActions.children.length; i++) {
  35693. var triggerParams;
  35694. var trigger = parsedActions.children[i];
  35695. if (trigger.properties.length > 0) {
  35696. var param = trigger.properties[0].value;
  35697. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  35698. if (value._meshId) {
  35699. value.mesh = scene.getMeshByID(value._meshId);
  35700. }
  35701. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  35702. }
  35703. else
  35704. triggerParams = BABYLON.ActionManager[trigger.name];
  35705. for (var j = 0; j < trigger.children.length; j++) {
  35706. if (!trigger.detached)
  35707. traverse(trigger.children[j], triggerParams, null, null);
  35708. }
  35709. }
  35710. };
  35711. ActionManager.GetTriggerName = function (trigger) {
  35712. switch (trigger) {
  35713. case 0: return "NothingTrigger";
  35714. case 1: return "OnPickTrigger";
  35715. case 2: return "OnLeftPickTrigger";
  35716. case 3: return "OnRightPickTrigger";
  35717. case 4: return "OnCenterPickTrigger";
  35718. case 5: return "OnPickDownTrigger";
  35719. case 6: return "OnPickUpTrigger";
  35720. case 7: return "OnLongPressTrigger";
  35721. case 8: return "OnPointerOverTrigger";
  35722. case 9: return "OnPointerOutTrigger";
  35723. case 10: return "OnEveryFrameTrigger";
  35724. case 11: return "OnIntersectionEnterTrigger";
  35725. case 12: return "OnIntersectionExitTrigger";
  35726. case 13: return "OnKeyDownTrigger";
  35727. case 14: return "OnKeyUpTrigger";
  35728. case 15: return "OnPickOutTrigger";
  35729. default: return "";
  35730. }
  35731. };
  35732. return ActionManager;
  35733. }());
  35734. // Statics
  35735. ActionManager._NothingTrigger = 0;
  35736. ActionManager._OnPickTrigger = 1;
  35737. ActionManager._OnLeftPickTrigger = 2;
  35738. ActionManager._OnRightPickTrigger = 3;
  35739. ActionManager._OnCenterPickTrigger = 4;
  35740. ActionManager._OnPickDownTrigger = 5;
  35741. ActionManager._OnDoublePickTrigger = 6;
  35742. ActionManager._OnPickUpTrigger = 7;
  35743. ActionManager._OnLongPressTrigger = 8;
  35744. ActionManager._OnPointerOverTrigger = 9;
  35745. ActionManager._OnPointerOutTrigger = 10;
  35746. ActionManager._OnEveryFrameTrigger = 11;
  35747. ActionManager._OnIntersectionEnterTrigger = 12;
  35748. ActionManager._OnIntersectionExitTrigger = 13;
  35749. ActionManager._OnKeyDownTrigger = 14;
  35750. ActionManager._OnKeyUpTrigger = 15;
  35751. ActionManager._OnPickOutTrigger = 16;
  35752. ActionManager.Triggers = {};
  35753. BABYLON.ActionManager = ActionManager;
  35754. })(BABYLON || (BABYLON = {}));
  35755. //# sourceMappingURL=babylon.actionManager.js.map
  35756. var BABYLON;
  35757. (function (BABYLON) {
  35758. var InterpolateValueAction = (function (_super) {
  35759. __extends(InterpolateValueAction, _super);
  35760. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  35761. if (duration === void 0) { duration = 1000; }
  35762. var _this = _super.call(this, triggerOptions, condition) || this;
  35763. _this.propertyPath = propertyPath;
  35764. _this.value = value;
  35765. _this.duration = duration;
  35766. _this.stopOtherAnimations = stopOtherAnimations;
  35767. _this.onInterpolationDone = onInterpolationDone;
  35768. _this._target = _this._effectiveTarget = target;
  35769. return _this;
  35770. }
  35771. InterpolateValueAction.prototype._prepare = function () {
  35772. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35773. this._property = this._getProperty(this.propertyPath);
  35774. };
  35775. InterpolateValueAction.prototype.execute = function () {
  35776. var scene = this._actionManager.getScene();
  35777. var keys = [
  35778. {
  35779. frame: 0,
  35780. value: this._effectiveTarget[this._property]
  35781. }, {
  35782. frame: 100,
  35783. value: this.value
  35784. }
  35785. ];
  35786. var dataType;
  35787. if (typeof this.value === "number") {
  35788. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  35789. }
  35790. else if (this.value instanceof BABYLON.Color3) {
  35791. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  35792. }
  35793. else if (this.value instanceof BABYLON.Vector3) {
  35794. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  35795. }
  35796. else if (this.value instanceof BABYLON.Matrix) {
  35797. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  35798. }
  35799. else if (this.value instanceof BABYLON.Quaternion) {
  35800. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  35801. }
  35802. else {
  35803. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  35804. return;
  35805. }
  35806. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  35807. animation.setKeys(keys);
  35808. if (this.stopOtherAnimations) {
  35809. scene.stopAnimation(this._effectiveTarget);
  35810. }
  35811. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  35812. };
  35813. InterpolateValueAction.prototype.serialize = function (parent) {
  35814. return _super.prototype._serialize.call(this, {
  35815. name: "InterpolateValueAction",
  35816. properties: [
  35817. BABYLON.Action._GetTargetProperty(this._target),
  35818. { name: "propertyPath", value: this.propertyPath },
  35819. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35820. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  35821. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  35822. ]
  35823. }, parent);
  35824. };
  35825. return InterpolateValueAction;
  35826. }(BABYLON.Action));
  35827. BABYLON.InterpolateValueAction = InterpolateValueAction;
  35828. })(BABYLON || (BABYLON = {}));
  35829. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  35830. var BABYLON;
  35831. (function (BABYLON) {
  35832. var SwitchBooleanAction = (function (_super) {
  35833. __extends(SwitchBooleanAction, _super);
  35834. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  35835. var _this = _super.call(this, triggerOptions, condition) || this;
  35836. _this.propertyPath = propertyPath;
  35837. _this._target = _this._effectiveTarget = target;
  35838. return _this;
  35839. }
  35840. SwitchBooleanAction.prototype._prepare = function () {
  35841. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35842. this._property = this._getProperty(this.propertyPath);
  35843. };
  35844. SwitchBooleanAction.prototype.execute = function () {
  35845. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  35846. };
  35847. SwitchBooleanAction.prototype.serialize = function (parent) {
  35848. return _super.prototype._serialize.call(this, {
  35849. name: "SwitchBooleanAction",
  35850. properties: [
  35851. BABYLON.Action._GetTargetProperty(this._target),
  35852. { name: "propertyPath", value: this.propertyPath }
  35853. ]
  35854. }, parent);
  35855. };
  35856. return SwitchBooleanAction;
  35857. }(BABYLON.Action));
  35858. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  35859. var SetStateAction = (function (_super) {
  35860. __extends(SetStateAction, _super);
  35861. function SetStateAction(triggerOptions, target, value, condition) {
  35862. var _this = _super.call(this, triggerOptions, condition) || this;
  35863. _this.value = value;
  35864. _this._target = target;
  35865. return _this;
  35866. }
  35867. SetStateAction.prototype.execute = function () {
  35868. this._target.state = this.value;
  35869. };
  35870. SetStateAction.prototype.serialize = function (parent) {
  35871. return _super.prototype._serialize.call(this, {
  35872. name: "SetStateAction",
  35873. properties: [
  35874. BABYLON.Action._GetTargetProperty(this._target),
  35875. { name: "value", value: this.value }
  35876. ]
  35877. }, parent);
  35878. };
  35879. return SetStateAction;
  35880. }(BABYLON.Action));
  35881. BABYLON.SetStateAction = SetStateAction;
  35882. var SetValueAction = (function (_super) {
  35883. __extends(SetValueAction, _super);
  35884. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  35885. var _this = _super.call(this, triggerOptions, condition) || this;
  35886. _this.propertyPath = propertyPath;
  35887. _this.value = value;
  35888. _this._target = _this._effectiveTarget = target;
  35889. return _this;
  35890. }
  35891. SetValueAction.prototype._prepare = function () {
  35892. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35893. this._property = this._getProperty(this.propertyPath);
  35894. };
  35895. SetValueAction.prototype.execute = function () {
  35896. this._effectiveTarget[this._property] = this.value;
  35897. if (this._target.markAsDirty) {
  35898. this._target.markAsDirty(this._property);
  35899. }
  35900. };
  35901. SetValueAction.prototype.serialize = function (parent) {
  35902. return _super.prototype._serialize.call(this, {
  35903. name: "SetValueAction",
  35904. properties: [
  35905. BABYLON.Action._GetTargetProperty(this._target),
  35906. { name: "propertyPath", value: this.propertyPath },
  35907. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35908. ]
  35909. }, parent);
  35910. };
  35911. return SetValueAction;
  35912. }(BABYLON.Action));
  35913. BABYLON.SetValueAction = SetValueAction;
  35914. var IncrementValueAction = (function (_super) {
  35915. __extends(IncrementValueAction, _super);
  35916. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  35917. var _this = _super.call(this, triggerOptions, condition) || this;
  35918. _this.propertyPath = propertyPath;
  35919. _this.value = value;
  35920. _this._target = _this._effectiveTarget = target;
  35921. return _this;
  35922. }
  35923. IncrementValueAction.prototype._prepare = function () {
  35924. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35925. this._property = this._getProperty(this.propertyPath);
  35926. if (typeof this._effectiveTarget[this._property] !== "number") {
  35927. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  35928. }
  35929. };
  35930. IncrementValueAction.prototype.execute = function () {
  35931. this._effectiveTarget[this._property] += this.value;
  35932. if (this._target.markAsDirty) {
  35933. this._target.markAsDirty(this._property);
  35934. }
  35935. };
  35936. IncrementValueAction.prototype.serialize = function (parent) {
  35937. return _super.prototype._serialize.call(this, {
  35938. name: "IncrementValueAction",
  35939. properties: [
  35940. BABYLON.Action._GetTargetProperty(this._target),
  35941. { name: "propertyPath", value: this.propertyPath },
  35942. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35943. ]
  35944. }, parent);
  35945. };
  35946. return IncrementValueAction;
  35947. }(BABYLON.Action));
  35948. BABYLON.IncrementValueAction = IncrementValueAction;
  35949. var PlayAnimationAction = (function (_super) {
  35950. __extends(PlayAnimationAction, _super);
  35951. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  35952. var _this = _super.call(this, triggerOptions, condition) || this;
  35953. _this.from = from;
  35954. _this.to = to;
  35955. _this.loop = loop;
  35956. _this._target = target;
  35957. return _this;
  35958. }
  35959. PlayAnimationAction.prototype._prepare = function () {
  35960. };
  35961. PlayAnimationAction.prototype.execute = function () {
  35962. var scene = this._actionManager.getScene();
  35963. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  35964. };
  35965. PlayAnimationAction.prototype.serialize = function (parent) {
  35966. return _super.prototype._serialize.call(this, {
  35967. name: "PlayAnimationAction",
  35968. properties: [
  35969. BABYLON.Action._GetTargetProperty(this._target),
  35970. { name: "from", value: String(this.from) },
  35971. { name: "to", value: String(this.to) },
  35972. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  35973. ]
  35974. }, parent);
  35975. };
  35976. return PlayAnimationAction;
  35977. }(BABYLON.Action));
  35978. BABYLON.PlayAnimationAction = PlayAnimationAction;
  35979. var StopAnimationAction = (function (_super) {
  35980. __extends(StopAnimationAction, _super);
  35981. function StopAnimationAction(triggerOptions, target, condition) {
  35982. var _this = _super.call(this, triggerOptions, condition) || this;
  35983. _this._target = target;
  35984. return _this;
  35985. }
  35986. StopAnimationAction.prototype._prepare = function () {
  35987. };
  35988. StopAnimationAction.prototype.execute = function () {
  35989. var scene = this._actionManager.getScene();
  35990. scene.stopAnimation(this._target);
  35991. };
  35992. StopAnimationAction.prototype.serialize = function (parent) {
  35993. return _super.prototype._serialize.call(this, {
  35994. name: "StopAnimationAction",
  35995. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  35996. }, parent);
  35997. };
  35998. return StopAnimationAction;
  35999. }(BABYLON.Action));
  36000. BABYLON.StopAnimationAction = StopAnimationAction;
  36001. var DoNothingAction = (function (_super) {
  36002. __extends(DoNothingAction, _super);
  36003. function DoNothingAction(triggerOptions, condition) {
  36004. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36005. return _super.call(this, triggerOptions, condition) || this;
  36006. }
  36007. DoNothingAction.prototype.execute = function () {
  36008. };
  36009. DoNothingAction.prototype.serialize = function (parent) {
  36010. return _super.prototype._serialize.call(this, {
  36011. name: "DoNothingAction",
  36012. properties: []
  36013. }, parent);
  36014. };
  36015. return DoNothingAction;
  36016. }(BABYLON.Action));
  36017. BABYLON.DoNothingAction = DoNothingAction;
  36018. var CombineAction = (function (_super) {
  36019. __extends(CombineAction, _super);
  36020. function CombineAction(triggerOptions, children, condition) {
  36021. var _this = _super.call(this, triggerOptions, condition) || this;
  36022. _this.children = children;
  36023. return _this;
  36024. }
  36025. CombineAction.prototype._prepare = function () {
  36026. for (var index = 0; index < this.children.length; index++) {
  36027. this.children[index]._actionManager = this._actionManager;
  36028. this.children[index]._prepare();
  36029. }
  36030. };
  36031. CombineAction.prototype.execute = function (evt) {
  36032. for (var index = 0; index < this.children.length; index++) {
  36033. this.children[index].execute(evt);
  36034. }
  36035. };
  36036. CombineAction.prototype.serialize = function (parent) {
  36037. var serializationObject = _super.prototype._serialize.call(this, {
  36038. name: "CombineAction",
  36039. properties: [],
  36040. combine: []
  36041. }, parent);
  36042. for (var i = 0; i < this.children.length; i++) {
  36043. serializationObject.combine.push(this.children[i].serialize(null));
  36044. }
  36045. return serializationObject;
  36046. };
  36047. return CombineAction;
  36048. }(BABYLON.Action));
  36049. BABYLON.CombineAction = CombineAction;
  36050. var ExecuteCodeAction = (function (_super) {
  36051. __extends(ExecuteCodeAction, _super);
  36052. function ExecuteCodeAction(triggerOptions, func, condition) {
  36053. var _this = _super.call(this, triggerOptions, condition) || this;
  36054. _this.func = func;
  36055. return _this;
  36056. }
  36057. ExecuteCodeAction.prototype.execute = function (evt) {
  36058. this.func(evt);
  36059. };
  36060. return ExecuteCodeAction;
  36061. }(BABYLON.Action));
  36062. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36063. var SetParentAction = (function (_super) {
  36064. __extends(SetParentAction, _super);
  36065. function SetParentAction(triggerOptions, target, parent, condition) {
  36066. var _this = _super.call(this, triggerOptions, condition) || this;
  36067. _this._target = target;
  36068. _this._parent = parent;
  36069. return _this;
  36070. }
  36071. SetParentAction.prototype._prepare = function () {
  36072. };
  36073. SetParentAction.prototype.execute = function () {
  36074. if (this._target.parent === this._parent) {
  36075. return;
  36076. }
  36077. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36078. invertParentWorldMatrix.invert();
  36079. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36080. this._target.parent = this._parent;
  36081. };
  36082. SetParentAction.prototype.serialize = function (parent) {
  36083. return _super.prototype._serialize.call(this, {
  36084. name: "SetParentAction",
  36085. properties: [
  36086. BABYLON.Action._GetTargetProperty(this._target),
  36087. BABYLON.Action._GetTargetProperty(this._parent),
  36088. ]
  36089. }, parent);
  36090. };
  36091. return SetParentAction;
  36092. }(BABYLON.Action));
  36093. BABYLON.SetParentAction = SetParentAction;
  36094. var PlaySoundAction = (function (_super) {
  36095. __extends(PlaySoundAction, _super);
  36096. function PlaySoundAction(triggerOptions, sound, condition) {
  36097. var _this = _super.call(this, triggerOptions, condition) || this;
  36098. _this._sound = sound;
  36099. return _this;
  36100. }
  36101. PlaySoundAction.prototype._prepare = function () {
  36102. };
  36103. PlaySoundAction.prototype.execute = function () {
  36104. if (this._sound !== undefined)
  36105. this._sound.play();
  36106. };
  36107. PlaySoundAction.prototype.serialize = function (parent) {
  36108. return _super.prototype._serialize.call(this, {
  36109. name: "PlaySoundAction",
  36110. properties: [{ name: "sound", value: this._sound.name }]
  36111. }, parent);
  36112. };
  36113. return PlaySoundAction;
  36114. }(BABYLON.Action));
  36115. BABYLON.PlaySoundAction = PlaySoundAction;
  36116. var StopSoundAction = (function (_super) {
  36117. __extends(StopSoundAction, _super);
  36118. function StopSoundAction(triggerOptions, sound, condition) {
  36119. var _this = _super.call(this, triggerOptions, condition) || this;
  36120. _this._sound = sound;
  36121. return _this;
  36122. }
  36123. StopSoundAction.prototype._prepare = function () {
  36124. };
  36125. StopSoundAction.prototype.execute = function () {
  36126. if (this._sound !== undefined)
  36127. this._sound.stop();
  36128. };
  36129. StopSoundAction.prototype.serialize = function (parent) {
  36130. return _super.prototype._serialize.call(this, {
  36131. name: "StopSoundAction",
  36132. properties: [{ name: "sound", value: this._sound.name }]
  36133. }, parent);
  36134. };
  36135. return StopSoundAction;
  36136. }(BABYLON.Action));
  36137. BABYLON.StopSoundAction = StopSoundAction;
  36138. })(BABYLON || (BABYLON = {}));
  36139. //# sourceMappingURL=babylon.directActions.js.map
  36140. var BABYLON;
  36141. (function (BABYLON) {
  36142. var SpriteManager = (function () {
  36143. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  36144. if (epsilon === void 0) { epsilon = 0.01; }
  36145. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36146. this.name = name;
  36147. this.sprites = new Array();
  36148. this.renderingGroupId = 0;
  36149. this.layerMask = 0x0FFFFFFF;
  36150. this.fogEnabled = true;
  36151. this.isPickable = false;
  36152. /**
  36153. * An event triggered when the manager is disposed.
  36154. * @type {BABYLON.Observable}
  36155. */
  36156. this.onDisposeObservable = new BABYLON.Observable();
  36157. this._vertexBuffers = {};
  36158. this._capacity = capacity;
  36159. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  36160. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36161. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36162. if (cellSize.width && cellSize.height) {
  36163. this.cellWidth = cellSize.width;
  36164. this.cellHeight = cellSize.height;
  36165. }
  36166. else if (cellSize !== undefined) {
  36167. this.cellWidth = cellSize;
  36168. this.cellHeight = cellSize;
  36169. }
  36170. else {
  36171. return;
  36172. }
  36173. this._epsilon = epsilon;
  36174. this._scene = scene;
  36175. this._scene.spriteManagers.push(this);
  36176. var indices = [];
  36177. var index = 0;
  36178. for (var count = 0; count < capacity; count++) {
  36179. indices.push(index);
  36180. indices.push(index + 1);
  36181. indices.push(index + 2);
  36182. indices.push(index);
  36183. indices.push(index + 2);
  36184. indices.push(index + 3);
  36185. index += 4;
  36186. }
  36187. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  36188. // VBO
  36189. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  36190. this._vertexData = new Float32Array(capacity * 16 * 4);
  36191. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  36192. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  36193. var options = this._buffer.createVertexBuffer("options", 4, 4);
  36194. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  36195. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  36196. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  36197. this._vertexBuffers["options"] = options;
  36198. this._vertexBuffers["cellInfo"] = cellInfo;
  36199. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  36200. // Effects
  36201. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  36202. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  36203. }
  36204. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  36205. set: function (callback) {
  36206. if (this._onDisposeObserver) {
  36207. this.onDisposeObservable.remove(this._onDisposeObserver);
  36208. }
  36209. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36210. },
  36211. enumerable: true,
  36212. configurable: true
  36213. });
  36214. Object.defineProperty(SpriteManager.prototype, "texture", {
  36215. get: function () {
  36216. return this._spriteTexture;
  36217. },
  36218. set: function (value) {
  36219. this._spriteTexture = value;
  36220. },
  36221. enumerable: true,
  36222. configurable: true
  36223. });
  36224. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  36225. var arrayOffset = index * 16;
  36226. if (offsetX === 0)
  36227. offsetX = this._epsilon;
  36228. else if (offsetX === 1)
  36229. offsetX = 1 - this._epsilon;
  36230. if (offsetY === 0)
  36231. offsetY = this._epsilon;
  36232. else if (offsetY === 1)
  36233. offsetY = 1 - this._epsilon;
  36234. this._vertexData[arrayOffset] = sprite.position.x;
  36235. this._vertexData[arrayOffset + 1] = sprite.position.y;
  36236. this._vertexData[arrayOffset + 2] = sprite.position.z;
  36237. this._vertexData[arrayOffset + 3] = sprite.angle;
  36238. this._vertexData[arrayOffset + 4] = sprite.width;
  36239. this._vertexData[arrayOffset + 5] = sprite.height;
  36240. this._vertexData[arrayOffset + 6] = offsetX;
  36241. this._vertexData[arrayOffset + 7] = offsetY;
  36242. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  36243. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  36244. var offset = (sprite.cellIndex / rowSize) >> 0;
  36245. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  36246. this._vertexData[arrayOffset + 11] = offset;
  36247. // Color
  36248. this._vertexData[arrayOffset + 12] = sprite.color.r;
  36249. this._vertexData[arrayOffset + 13] = sprite.color.g;
  36250. this._vertexData[arrayOffset + 14] = sprite.color.b;
  36251. this._vertexData[arrayOffset + 15] = sprite.color.a;
  36252. };
  36253. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  36254. var count = Math.min(this._capacity, this.sprites.length);
  36255. var min = BABYLON.Vector3.Zero();
  36256. var max = BABYLON.Vector3.Zero();
  36257. var distance = Number.MAX_VALUE;
  36258. var currentSprite;
  36259. var cameraSpacePosition = BABYLON.Vector3.Zero();
  36260. var cameraView = camera.getViewMatrix();
  36261. for (var index = 0; index < count; index++) {
  36262. var sprite = this.sprites[index];
  36263. if (!sprite) {
  36264. continue;
  36265. }
  36266. if (predicate) {
  36267. if (!predicate(sprite)) {
  36268. continue;
  36269. }
  36270. }
  36271. else if (!sprite.isPickable) {
  36272. continue;
  36273. }
  36274. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  36275. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  36276. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  36277. if (ray.intersectsBoxMinMax(min, max)) {
  36278. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  36279. if (distance > currentDistance) {
  36280. distance = currentDistance;
  36281. currentSprite = sprite;
  36282. if (fastCheck) {
  36283. break;
  36284. }
  36285. }
  36286. }
  36287. }
  36288. if (currentSprite) {
  36289. var result = new BABYLON.PickingInfo();
  36290. result.hit = true;
  36291. result.pickedSprite = currentSprite;
  36292. result.distance = distance;
  36293. return result;
  36294. }
  36295. return null;
  36296. };
  36297. SpriteManager.prototype.render = function () {
  36298. // Check
  36299. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  36300. return;
  36301. var engine = this._scene.getEngine();
  36302. var baseSize = this._spriteTexture.getBaseSize();
  36303. // Sprites
  36304. var deltaTime = engine.getDeltaTime();
  36305. var max = Math.min(this._capacity, this.sprites.length);
  36306. var rowSize = baseSize.width / this.cellWidth;
  36307. var offset = 0;
  36308. for (var index = 0; index < max; index++) {
  36309. var sprite = this.sprites[index];
  36310. if (!sprite) {
  36311. continue;
  36312. }
  36313. sprite._animate(deltaTime);
  36314. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  36315. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  36316. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  36317. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  36318. }
  36319. this._buffer.update(this._vertexData);
  36320. // Render
  36321. var effect = this._effectBase;
  36322. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  36323. effect = this._effectFog;
  36324. }
  36325. engine.enableEffect(effect);
  36326. var viewMatrix = this._scene.getViewMatrix();
  36327. effect.setTexture("diffuseSampler", this._spriteTexture);
  36328. effect.setMatrix("view", viewMatrix);
  36329. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  36330. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  36331. // Fog
  36332. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  36333. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  36334. effect.setColor3("vFogColor", this._scene.fogColor);
  36335. }
  36336. // VBOs
  36337. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36338. // Draw order
  36339. engine.setDepthFunctionToLessOrEqual();
  36340. effect.setBool("alphaTest", true);
  36341. engine.setColorWrite(false);
  36342. engine.draw(true, 0, max * 6);
  36343. engine.setColorWrite(true);
  36344. effect.setBool("alphaTest", false);
  36345. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36346. engine.draw(true, 0, max * 6);
  36347. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36348. };
  36349. SpriteManager.prototype.dispose = function () {
  36350. if (this._buffer) {
  36351. this._buffer.dispose();
  36352. this._buffer = null;
  36353. }
  36354. if (this._indexBuffer) {
  36355. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36356. this._indexBuffer = null;
  36357. }
  36358. if (this._spriteTexture) {
  36359. this._spriteTexture.dispose();
  36360. this._spriteTexture = null;
  36361. }
  36362. // Remove from scene
  36363. var index = this._scene.spriteManagers.indexOf(this);
  36364. this._scene.spriteManagers.splice(index, 1);
  36365. // Callback
  36366. this.onDisposeObservable.notifyObservers(this);
  36367. this.onDisposeObservable.clear();
  36368. };
  36369. return SpriteManager;
  36370. }());
  36371. BABYLON.SpriteManager = SpriteManager;
  36372. })(BABYLON || (BABYLON = {}));
  36373. //# sourceMappingURL=babylon.spriteManager.js.map
  36374. var BABYLON;
  36375. (function (BABYLON) {
  36376. var Sprite = (function () {
  36377. function Sprite(name, manager) {
  36378. this.name = name;
  36379. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  36380. this.width = 1.0;
  36381. this.height = 1.0;
  36382. this.angle = 0;
  36383. this.cellIndex = 0;
  36384. this.invertU = 0;
  36385. this.invertV = 0;
  36386. this.animations = new Array();
  36387. this.isPickable = false;
  36388. this._animationStarted = false;
  36389. this._loopAnimation = false;
  36390. this._fromIndex = 0;
  36391. this._toIndex = 0;
  36392. this._delay = 0;
  36393. this._direction = 1;
  36394. this._frameCount = 0;
  36395. this._time = 0;
  36396. this._manager = manager;
  36397. this._manager.sprites.push(this);
  36398. this.position = BABYLON.Vector3.Zero();
  36399. }
  36400. Object.defineProperty(Sprite.prototype, "size", {
  36401. get: function () {
  36402. return this.width;
  36403. },
  36404. set: function (value) {
  36405. this.width = value;
  36406. this.height = value;
  36407. },
  36408. enumerable: true,
  36409. configurable: true
  36410. });
  36411. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  36412. this._fromIndex = from;
  36413. this._toIndex = to;
  36414. this._loopAnimation = loop;
  36415. this._delay = delay;
  36416. this._animationStarted = true;
  36417. this._direction = from < to ? 1 : -1;
  36418. this.cellIndex = from;
  36419. this._time = 0;
  36420. this._onAnimationEnd = onAnimationEnd;
  36421. };
  36422. Sprite.prototype.stopAnimation = function () {
  36423. this._animationStarted = false;
  36424. };
  36425. Sprite.prototype._animate = function (deltaTime) {
  36426. if (!this._animationStarted)
  36427. return;
  36428. this._time += deltaTime;
  36429. if (this._time > this._delay) {
  36430. this._time = this._time % this._delay;
  36431. this.cellIndex += this._direction;
  36432. if (this.cellIndex === this._toIndex) {
  36433. if (this._loopAnimation) {
  36434. this.cellIndex = this._fromIndex;
  36435. }
  36436. else {
  36437. this._animationStarted = false;
  36438. if (this._onAnimationEnd) {
  36439. this._onAnimationEnd();
  36440. }
  36441. if (this.disposeWhenFinishedAnimating) {
  36442. this.dispose();
  36443. }
  36444. }
  36445. }
  36446. }
  36447. };
  36448. Sprite.prototype.dispose = function () {
  36449. for (var i = 0; i < this._manager.sprites.length; i++) {
  36450. if (this._manager.sprites[i] == this) {
  36451. this._manager.sprites.splice(i, 1);
  36452. }
  36453. }
  36454. };
  36455. return Sprite;
  36456. }());
  36457. BABYLON.Sprite = Sprite;
  36458. })(BABYLON || (BABYLON = {}));
  36459. //# sourceMappingURL=babylon.sprite.js.map
  36460. var BABYLON;
  36461. (function (BABYLON) {
  36462. var IntersectionInfo = (function () {
  36463. function IntersectionInfo(bu, bv, distance) {
  36464. this.bu = bu;
  36465. this.bv = bv;
  36466. this.distance = distance;
  36467. this.faceId = 0;
  36468. this.subMeshId = 0;
  36469. }
  36470. return IntersectionInfo;
  36471. }());
  36472. BABYLON.IntersectionInfo = IntersectionInfo;
  36473. var PickingInfo = (function () {
  36474. function PickingInfo() {
  36475. this.hit = false;
  36476. this.distance = 0;
  36477. this.pickedPoint = null;
  36478. this.pickedMesh = null;
  36479. this.bu = 0;
  36480. this.bv = 0;
  36481. this.faceId = -1;
  36482. this.subMeshId = 0;
  36483. this.pickedSprite = null;
  36484. }
  36485. // Methods
  36486. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  36487. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  36488. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  36489. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36490. return null;
  36491. }
  36492. var indices = this.pickedMesh.getIndices();
  36493. var result;
  36494. if (useVerticesNormals) {
  36495. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36496. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  36497. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  36498. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  36499. normal0 = normal0.scale(this.bu);
  36500. normal1 = normal1.scale(this.bv);
  36501. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  36502. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  36503. }
  36504. else {
  36505. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36506. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  36507. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  36508. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  36509. var p1p2 = vertex1.subtract(vertex2);
  36510. var p3p2 = vertex3.subtract(vertex2);
  36511. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  36512. }
  36513. if (useWorldCoordinates) {
  36514. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  36515. }
  36516. return BABYLON.Vector3.Normalize(result);
  36517. };
  36518. PickingInfo.prototype.getTextureCoordinates = function () {
  36519. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36520. return null;
  36521. }
  36522. var indices = this.pickedMesh.getIndices();
  36523. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36524. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  36525. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  36526. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  36527. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  36528. uv1 = uv1.scale(this.bu);
  36529. uv2 = uv2.scale(this.bv);
  36530. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  36531. };
  36532. return PickingInfo;
  36533. }());
  36534. BABYLON.PickingInfo = PickingInfo;
  36535. })(BABYLON || (BABYLON = {}));
  36536. //# sourceMappingURL=babylon.pickingInfo.js.map
  36537. var BABYLON;
  36538. (function (BABYLON) {
  36539. var Ray = (function () {
  36540. function Ray(origin, direction, length) {
  36541. if (length === void 0) { length = Number.MAX_VALUE; }
  36542. this.origin = origin;
  36543. this.direction = direction;
  36544. this.length = length;
  36545. }
  36546. // Methods
  36547. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  36548. var d = 0.0;
  36549. var maxValue = Number.MAX_VALUE;
  36550. var inv;
  36551. var min;
  36552. var max;
  36553. var temp;
  36554. if (Math.abs(this.direction.x) < 0.0000001) {
  36555. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  36556. return false;
  36557. }
  36558. }
  36559. else {
  36560. inv = 1.0 / this.direction.x;
  36561. min = (minimum.x - this.origin.x) * inv;
  36562. max = (maximum.x - this.origin.x) * inv;
  36563. if (max === -Infinity) {
  36564. max = Infinity;
  36565. }
  36566. if (min > max) {
  36567. temp = min;
  36568. min = max;
  36569. max = temp;
  36570. }
  36571. d = Math.max(min, d);
  36572. maxValue = Math.min(max, maxValue);
  36573. if (d > maxValue) {
  36574. return false;
  36575. }
  36576. }
  36577. if (Math.abs(this.direction.y) < 0.0000001) {
  36578. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  36579. return false;
  36580. }
  36581. }
  36582. else {
  36583. inv = 1.0 / this.direction.y;
  36584. min = (minimum.y - this.origin.y) * inv;
  36585. max = (maximum.y - this.origin.y) * inv;
  36586. if (max === -Infinity) {
  36587. max = Infinity;
  36588. }
  36589. if (min > max) {
  36590. temp = min;
  36591. min = max;
  36592. max = temp;
  36593. }
  36594. d = Math.max(min, d);
  36595. maxValue = Math.min(max, maxValue);
  36596. if (d > maxValue) {
  36597. return false;
  36598. }
  36599. }
  36600. if (Math.abs(this.direction.z) < 0.0000001) {
  36601. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  36602. return false;
  36603. }
  36604. }
  36605. else {
  36606. inv = 1.0 / this.direction.z;
  36607. min = (minimum.z - this.origin.z) * inv;
  36608. max = (maximum.z - this.origin.z) * inv;
  36609. if (max === -Infinity) {
  36610. max = Infinity;
  36611. }
  36612. if (min > max) {
  36613. temp = min;
  36614. min = max;
  36615. max = temp;
  36616. }
  36617. d = Math.max(min, d);
  36618. maxValue = Math.min(max, maxValue);
  36619. if (d > maxValue) {
  36620. return false;
  36621. }
  36622. }
  36623. return true;
  36624. };
  36625. Ray.prototype.intersectsBox = function (box) {
  36626. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  36627. };
  36628. Ray.prototype.intersectsSphere = function (sphere) {
  36629. var x = sphere.center.x - this.origin.x;
  36630. var y = sphere.center.y - this.origin.y;
  36631. var z = sphere.center.z - this.origin.z;
  36632. var pyth = (x * x) + (y * y) + (z * z);
  36633. var rr = sphere.radius * sphere.radius;
  36634. if (pyth <= rr) {
  36635. return true;
  36636. }
  36637. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  36638. if (dot < 0.0) {
  36639. return false;
  36640. }
  36641. var temp = pyth - (dot * dot);
  36642. return temp <= rr;
  36643. };
  36644. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  36645. if (!this._edge1) {
  36646. this._edge1 = BABYLON.Vector3.Zero();
  36647. this._edge2 = BABYLON.Vector3.Zero();
  36648. this._pvec = BABYLON.Vector3.Zero();
  36649. this._tvec = BABYLON.Vector3.Zero();
  36650. this._qvec = BABYLON.Vector3.Zero();
  36651. }
  36652. vertex1.subtractToRef(vertex0, this._edge1);
  36653. vertex2.subtractToRef(vertex0, this._edge2);
  36654. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  36655. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  36656. if (det === 0) {
  36657. return null;
  36658. }
  36659. var invdet = 1 / det;
  36660. this.origin.subtractToRef(vertex0, this._tvec);
  36661. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  36662. if (bu < 0 || bu > 1.0) {
  36663. return null;
  36664. }
  36665. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  36666. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  36667. if (bv < 0 || bu + bv > 1.0) {
  36668. return null;
  36669. }
  36670. //check if the distance is longer than the predefined length.
  36671. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  36672. if (distance > this.length) {
  36673. return null;
  36674. }
  36675. return new BABYLON.IntersectionInfo(bu, bv, distance);
  36676. };
  36677. Ray.prototype.intersectsPlane = function (plane) {
  36678. var distance;
  36679. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  36680. if (Math.abs(result1) < 9.99999997475243E-07) {
  36681. return null;
  36682. }
  36683. else {
  36684. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  36685. distance = (-plane.d - result2) / result1;
  36686. if (distance < 0.0) {
  36687. if (distance < -9.99999997475243E-07) {
  36688. return null;
  36689. }
  36690. else {
  36691. return 0;
  36692. }
  36693. }
  36694. return distance;
  36695. }
  36696. };
  36697. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  36698. var tm = BABYLON.Tmp.Matrix[0];
  36699. mesh.getWorldMatrix().invertToRef(tm);
  36700. if (this._tmpRay) {
  36701. Ray.TransformToRef(this, tm, this._tmpRay);
  36702. }
  36703. else {
  36704. this._tmpRay = Ray.Transform(this, tm);
  36705. }
  36706. return mesh.intersects(this._tmpRay, fastCheck);
  36707. };
  36708. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  36709. if (results) {
  36710. results.length = 0;
  36711. }
  36712. else {
  36713. results = [];
  36714. }
  36715. for (var i = 0; i < meshes.length; i++) {
  36716. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  36717. if (pickInfo.hit) {
  36718. results.push(pickInfo);
  36719. }
  36720. }
  36721. results.sort(this._comparePickingInfo);
  36722. return results;
  36723. };
  36724. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  36725. if (pickingInfoA.distance < pickingInfoB.distance) {
  36726. return -1;
  36727. }
  36728. else if (pickingInfoA.distance > pickingInfoB.distance) {
  36729. return 1;
  36730. }
  36731. else {
  36732. return 0;
  36733. }
  36734. };
  36735. /**
  36736. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  36737. * @param sega the first point of the segment to test the intersection against
  36738. * @param segb the second point of the segment to test the intersection against
  36739. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  36740. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  36741. */
  36742. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  36743. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  36744. var u = segb.subtract(sega);
  36745. var v = rsegb.subtract(this.origin);
  36746. var w = sega.subtract(this.origin);
  36747. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  36748. var b = BABYLON.Vector3.Dot(u, v);
  36749. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  36750. var d = BABYLON.Vector3.Dot(u, w);
  36751. var e = BABYLON.Vector3.Dot(v, w);
  36752. var D = a * c - b * b; // always >= 0
  36753. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  36754. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  36755. // compute the line parameters of the two closest points
  36756. if (D < Ray.smallnum) {
  36757. sN = 0.0; // force using point P0 on segment S1
  36758. sD = 1.0; // to prevent possible division by 0.0 later
  36759. tN = e;
  36760. tD = c;
  36761. }
  36762. else {
  36763. sN = (b * e - c * d);
  36764. tN = (a * e - b * d);
  36765. if (sN < 0.0) {
  36766. sN = 0.0;
  36767. tN = e;
  36768. tD = c;
  36769. }
  36770. else if (sN > sD) {
  36771. sN = sD;
  36772. tN = e + b;
  36773. tD = c;
  36774. }
  36775. }
  36776. if (tN < 0.0) {
  36777. tN = 0.0;
  36778. // recompute sc for this edge
  36779. if (-d < 0.0) {
  36780. sN = 0.0;
  36781. }
  36782. else if (-d > a)
  36783. sN = sD;
  36784. else {
  36785. sN = -d;
  36786. sD = a;
  36787. }
  36788. }
  36789. else if (tN > tD) {
  36790. tN = tD;
  36791. // recompute sc for this edge
  36792. if ((-d + b) < 0.0) {
  36793. sN = 0;
  36794. }
  36795. else if ((-d + b) > a) {
  36796. sN = sD;
  36797. }
  36798. else {
  36799. sN = (-d + b);
  36800. sD = a;
  36801. }
  36802. }
  36803. // finally do the division to get sc and tc
  36804. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  36805. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  36806. // get the difference of the two closest points
  36807. var qtc = v.multiplyByFloats(tc, tc, tc);
  36808. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  36809. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  36810. if (isIntersected) {
  36811. return qtc.length();
  36812. }
  36813. return -1;
  36814. };
  36815. // Statics
  36816. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  36817. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  36818. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  36819. var direction = end.subtract(start);
  36820. direction.normalize();
  36821. return new Ray(start, direction);
  36822. };
  36823. /**
  36824. * 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
  36825. * transformed to the given world matrix.
  36826. * @param origin The origin point
  36827. * @param end The end point
  36828. * @param world a matrix to transform the ray to. Default is the identity matrix.
  36829. */
  36830. Ray.CreateNewFromTo = function (origin, end, world) {
  36831. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  36832. var direction = end.subtract(origin);
  36833. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  36834. direction.normalize();
  36835. return Ray.Transform(new Ray(origin, direction, length), world);
  36836. };
  36837. Ray.Transform = function (ray, matrix) {
  36838. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  36839. Ray.TransformToRef(ray, matrix, result);
  36840. return result;
  36841. };
  36842. Ray.TransformToRef = function (ray, matrix, result) {
  36843. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  36844. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  36845. result.length = ray.length;
  36846. var dir = result.direction;
  36847. var len = dir.length();
  36848. if (!(len === 0 || len === 1)) {
  36849. var num = 1.0 / len;
  36850. dir.x *= num;
  36851. dir.y *= num;
  36852. dir.z *= num;
  36853. result.length *= len;
  36854. }
  36855. };
  36856. return Ray;
  36857. }());
  36858. Ray.smallnum = 0.00000001;
  36859. Ray.rayl = 10e8;
  36860. BABYLON.Ray = Ray;
  36861. })(BABYLON || (BABYLON = {}));
  36862. //# sourceMappingURL=babylon.ray.js.map
  36863. var BABYLON;
  36864. (function (BABYLON) {
  36865. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  36866. if (boxMin.x > sphereCenter.x + sphereRadius)
  36867. return false;
  36868. if (sphereCenter.x - sphereRadius > boxMax.x)
  36869. return false;
  36870. if (boxMin.y > sphereCenter.y + sphereRadius)
  36871. return false;
  36872. if (sphereCenter.y - sphereRadius > boxMax.y)
  36873. return false;
  36874. if (boxMin.z > sphereCenter.z + sphereRadius)
  36875. return false;
  36876. if (sphereCenter.z - sphereRadius > boxMax.z)
  36877. return false;
  36878. return true;
  36879. };
  36880. var getLowestRoot = (function () {
  36881. var result = { root: 0, found: false };
  36882. return function (a, b, c, maxR) {
  36883. result.root = 0;
  36884. result.found = false;
  36885. var determinant = b * b - 4.0 * a * c;
  36886. if (determinant < 0)
  36887. return result;
  36888. var sqrtD = Math.sqrt(determinant);
  36889. var r1 = (-b - sqrtD) / (2.0 * a);
  36890. var r2 = (-b + sqrtD) / (2.0 * a);
  36891. if (r1 > r2) {
  36892. var temp = r2;
  36893. r2 = r1;
  36894. r1 = temp;
  36895. }
  36896. if (r1 > 0 && r1 < maxR) {
  36897. result.root = r1;
  36898. result.found = true;
  36899. return result;
  36900. }
  36901. if (r2 > 0 && r2 < maxR) {
  36902. result.root = r2;
  36903. result.found = true;
  36904. return result;
  36905. }
  36906. return result;
  36907. };
  36908. })();
  36909. var Collider = (function () {
  36910. function Collider() {
  36911. this.radius = new BABYLON.Vector3(1, 1, 1);
  36912. this.retry = 0;
  36913. this.basePointWorld = BABYLON.Vector3.Zero();
  36914. this.velocityWorld = BABYLON.Vector3.Zero();
  36915. this.normalizedVelocity = BABYLON.Vector3.Zero();
  36916. this._collisionPoint = BABYLON.Vector3.Zero();
  36917. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  36918. this._tempVector = BABYLON.Vector3.Zero();
  36919. this._tempVector2 = BABYLON.Vector3.Zero();
  36920. this._tempVector3 = BABYLON.Vector3.Zero();
  36921. this._tempVector4 = BABYLON.Vector3.Zero();
  36922. this._edge = BABYLON.Vector3.Zero();
  36923. this._baseToVertex = BABYLON.Vector3.Zero();
  36924. this._destinationPoint = BABYLON.Vector3.Zero();
  36925. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  36926. this._displacementVector = BABYLON.Vector3.Zero();
  36927. this._collisionMask = -1;
  36928. }
  36929. Object.defineProperty(Collider.prototype, "collisionMask", {
  36930. get: function () {
  36931. return this._collisionMask;
  36932. },
  36933. set: function (mask) {
  36934. this._collisionMask = !isNaN(mask) ? mask : -1;
  36935. },
  36936. enumerable: true,
  36937. configurable: true
  36938. });
  36939. // Methods
  36940. Collider.prototype._initialize = function (source, dir, e) {
  36941. this.velocity = dir;
  36942. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  36943. this.basePoint = source;
  36944. source.multiplyToRef(this.radius, this.basePointWorld);
  36945. dir.multiplyToRef(this.radius, this.velocityWorld);
  36946. this.velocityWorldLength = this.velocityWorld.length();
  36947. this.epsilon = e;
  36948. this.collisionFound = false;
  36949. };
  36950. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  36951. pa.subtractToRef(point, this._tempVector);
  36952. pb.subtractToRef(point, this._tempVector2);
  36953. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  36954. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  36955. if (d < 0)
  36956. return false;
  36957. pc.subtractToRef(point, this._tempVector3);
  36958. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  36959. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  36960. if (d < 0)
  36961. return false;
  36962. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  36963. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  36964. return d >= 0;
  36965. };
  36966. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  36967. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  36968. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  36969. if (distance > this.velocityWorldLength + max + sphereRadius) {
  36970. return false;
  36971. }
  36972. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  36973. return false;
  36974. return true;
  36975. };
  36976. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  36977. var t0;
  36978. var embeddedInPlane = false;
  36979. //defensive programming, actually not needed.
  36980. if (!trianglePlaneArray) {
  36981. trianglePlaneArray = [];
  36982. }
  36983. if (!trianglePlaneArray[faceIndex]) {
  36984. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  36985. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  36986. }
  36987. var trianglePlane = trianglePlaneArray[faceIndex];
  36988. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  36989. return;
  36990. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  36991. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  36992. if (normalDotVelocity == 0) {
  36993. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  36994. return;
  36995. embeddedInPlane = true;
  36996. t0 = 0;
  36997. }
  36998. else {
  36999. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37000. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37001. if (t0 > t1) {
  37002. var temp = t1;
  37003. t1 = t0;
  37004. t0 = temp;
  37005. }
  37006. if (t0 > 1.0 || t1 < 0.0)
  37007. return;
  37008. if (t0 < 0)
  37009. t0 = 0;
  37010. if (t0 > 1.0)
  37011. t0 = 1.0;
  37012. }
  37013. this._collisionPoint.copyFromFloats(0, 0, 0);
  37014. var found = false;
  37015. var t = 1.0;
  37016. if (!embeddedInPlane) {
  37017. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  37018. this.velocity.scaleToRef(t0, this._tempVector);
  37019. this._planeIntersectionPoint.addInPlace(this._tempVector);
  37020. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  37021. found = true;
  37022. t = t0;
  37023. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  37024. }
  37025. }
  37026. if (!found) {
  37027. var velocitySquaredLength = this.velocity.lengthSquared();
  37028. var a = velocitySquaredLength;
  37029. this.basePoint.subtractToRef(p1, this._tempVector);
  37030. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37031. var c = this._tempVector.lengthSquared() - 1.0;
  37032. var lowestRoot = getLowestRoot(a, b, c, t);
  37033. if (lowestRoot.found) {
  37034. t = lowestRoot.root;
  37035. found = true;
  37036. this._collisionPoint.copyFrom(p1);
  37037. }
  37038. this.basePoint.subtractToRef(p2, this._tempVector);
  37039. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37040. c = this._tempVector.lengthSquared() - 1.0;
  37041. lowestRoot = getLowestRoot(a, b, c, t);
  37042. if (lowestRoot.found) {
  37043. t = lowestRoot.root;
  37044. found = true;
  37045. this._collisionPoint.copyFrom(p2);
  37046. }
  37047. this.basePoint.subtractToRef(p3, this._tempVector);
  37048. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37049. c = this._tempVector.lengthSquared() - 1.0;
  37050. lowestRoot = getLowestRoot(a, b, c, t);
  37051. if (lowestRoot.found) {
  37052. t = lowestRoot.root;
  37053. found = true;
  37054. this._collisionPoint.copyFrom(p3);
  37055. }
  37056. p2.subtractToRef(p1, this._edge);
  37057. p1.subtractToRef(this.basePoint, this._baseToVertex);
  37058. var edgeSquaredLength = this._edge.lengthSquared();
  37059. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37060. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37061. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37062. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37063. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37064. lowestRoot = getLowestRoot(a, b, c, t);
  37065. if (lowestRoot.found) {
  37066. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37067. if (f >= 0.0 && f <= 1.0) {
  37068. t = lowestRoot.root;
  37069. found = true;
  37070. this._edge.scaleInPlace(f);
  37071. p1.addToRef(this._edge, this._collisionPoint);
  37072. }
  37073. }
  37074. p3.subtractToRef(p2, this._edge);
  37075. p2.subtractToRef(this.basePoint, this._baseToVertex);
  37076. edgeSquaredLength = this._edge.lengthSquared();
  37077. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37078. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37079. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37080. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37081. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37082. lowestRoot = getLowestRoot(a, b, c, t);
  37083. if (lowestRoot.found) {
  37084. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37085. if (f >= 0.0 && f <= 1.0) {
  37086. t = lowestRoot.root;
  37087. found = true;
  37088. this._edge.scaleInPlace(f);
  37089. p2.addToRef(this._edge, this._collisionPoint);
  37090. }
  37091. }
  37092. p1.subtractToRef(p3, this._edge);
  37093. p3.subtractToRef(this.basePoint, this._baseToVertex);
  37094. edgeSquaredLength = this._edge.lengthSquared();
  37095. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37096. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37097. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37098. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37099. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37100. lowestRoot = getLowestRoot(a, b, c, t);
  37101. if (lowestRoot.found) {
  37102. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37103. if (f >= 0.0 && f <= 1.0) {
  37104. t = lowestRoot.root;
  37105. found = true;
  37106. this._edge.scaleInPlace(f);
  37107. p3.addToRef(this._edge, this._collisionPoint);
  37108. }
  37109. }
  37110. }
  37111. if (found) {
  37112. var distToCollision = t * this.velocity.length();
  37113. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  37114. if (!this.intersectionPoint) {
  37115. this.intersectionPoint = this._collisionPoint.clone();
  37116. }
  37117. else {
  37118. this.intersectionPoint.copyFrom(this._collisionPoint);
  37119. }
  37120. this.nearestDistance = distToCollision;
  37121. this.collisionFound = true;
  37122. }
  37123. }
  37124. };
  37125. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  37126. for (var i = indexStart; i < indexEnd; i += 3) {
  37127. var p1 = pts[indices[i] - decal];
  37128. var p2 = pts[indices[i + 1] - decal];
  37129. var p3 = pts[indices[i + 2] - decal];
  37130. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  37131. }
  37132. };
  37133. Collider.prototype._getResponse = function (pos, vel) {
  37134. pos.addToRef(vel, this._destinationPoint);
  37135. vel.scaleInPlace((this.nearestDistance / vel.length()));
  37136. this.basePoint.addToRef(vel, pos);
  37137. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  37138. this._slidePlaneNormal.normalize();
  37139. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  37140. pos.addInPlace(this._displacementVector);
  37141. this.intersectionPoint.addInPlace(this._displacementVector);
  37142. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  37143. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  37144. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  37145. };
  37146. return Collider;
  37147. }());
  37148. BABYLON.Collider = Collider;
  37149. })(BABYLON || (BABYLON = {}));
  37150. //# sourceMappingURL=babylon.collider.js.map
  37151. var BABYLON;
  37152. (function (BABYLON) {
  37153. //WebWorker code will be inserted to this variable.
  37154. BABYLON.CollisionWorker = "";
  37155. var WorkerTaskType;
  37156. (function (WorkerTaskType) {
  37157. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  37158. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  37159. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  37160. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  37161. var WorkerReplyType;
  37162. (function (WorkerReplyType) {
  37163. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  37164. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  37165. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  37166. var CollisionCoordinatorWorker = (function () {
  37167. function CollisionCoordinatorWorker() {
  37168. var _this = this;
  37169. this._scaledPosition = BABYLON.Vector3.Zero();
  37170. this._scaledVelocity = BABYLON.Vector3.Zero();
  37171. this.onMeshUpdated = function (mesh) {
  37172. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  37173. };
  37174. this.onGeometryUpdated = function (geometry) {
  37175. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  37176. };
  37177. this._afterRender = function () {
  37178. if (!_this._init)
  37179. return;
  37180. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  37181. return;
  37182. }
  37183. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  37184. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  37185. if (_this._runningUpdated > 4) {
  37186. return;
  37187. }
  37188. ++_this._runningUpdated;
  37189. var payload = {
  37190. updatedMeshes: _this._addUpdateMeshesList,
  37191. updatedGeometries: _this._addUpdateGeometriesList,
  37192. removedGeometries: _this._toRemoveGeometryArray,
  37193. removedMeshes: _this._toRemoveMeshesArray
  37194. };
  37195. var message = {
  37196. payload: payload,
  37197. taskType: WorkerTaskType.UPDATE
  37198. };
  37199. var serializable = [];
  37200. for (var id in payload.updatedGeometries) {
  37201. if (payload.updatedGeometries.hasOwnProperty(id)) {
  37202. //prepare transferables
  37203. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  37204. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  37205. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  37206. }
  37207. }
  37208. _this._worker.postMessage(message, serializable);
  37209. _this._addUpdateMeshesList = {};
  37210. _this._addUpdateGeometriesList = {};
  37211. _this._toRemoveGeometryArray = [];
  37212. _this._toRemoveMeshesArray = [];
  37213. };
  37214. this._onMessageFromWorker = function (e) {
  37215. var returnData = e.data;
  37216. if (returnData.error != WorkerReplyType.SUCCESS) {
  37217. //TODO what errors can be returned from the worker?
  37218. BABYLON.Tools.Warn("error returned from worker!");
  37219. return;
  37220. }
  37221. switch (returnData.taskType) {
  37222. case WorkerTaskType.INIT:
  37223. _this._init = true;
  37224. //Update the worked with ALL of the scene's current state
  37225. _this._scene.meshes.forEach(function (mesh) {
  37226. _this.onMeshAdded(mesh);
  37227. });
  37228. _this._scene.getGeometries().forEach(function (geometry) {
  37229. _this.onGeometryAdded(geometry);
  37230. });
  37231. break;
  37232. case WorkerTaskType.UPDATE:
  37233. _this._runningUpdated--;
  37234. break;
  37235. case WorkerTaskType.COLLIDE:
  37236. _this._runningCollisionTask = false;
  37237. var returnPayload = returnData.payload;
  37238. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  37239. return;
  37240. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  37241. //cleanup
  37242. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  37243. break;
  37244. }
  37245. };
  37246. this._collisionsCallbackArray = [];
  37247. this._init = false;
  37248. this._runningUpdated = 0;
  37249. this._runningCollisionTask = false;
  37250. this._addUpdateMeshesList = {};
  37251. this._addUpdateGeometriesList = {};
  37252. this._toRemoveGeometryArray = [];
  37253. this._toRemoveMeshesArray = [];
  37254. }
  37255. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  37256. if (!this._init)
  37257. return;
  37258. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  37259. return;
  37260. position.divideToRef(collider.radius, this._scaledPosition);
  37261. velocity.divideToRef(collider.radius, this._scaledVelocity);
  37262. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  37263. var payload = {
  37264. collider: {
  37265. position: this._scaledPosition.asArray(),
  37266. velocity: this._scaledVelocity.asArray(),
  37267. radius: collider.radius.asArray()
  37268. },
  37269. collisionId: collisionIndex,
  37270. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  37271. maximumRetry: maximumRetry
  37272. };
  37273. var message = {
  37274. payload: payload,
  37275. taskType: WorkerTaskType.COLLIDE
  37276. };
  37277. this._worker.postMessage(message);
  37278. };
  37279. CollisionCoordinatorWorker.prototype.init = function (scene) {
  37280. this._scene = scene;
  37281. this._scene.registerAfterRender(this._afterRender);
  37282. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  37283. this._worker = new Worker(workerUrl);
  37284. this._worker.onmessage = this._onMessageFromWorker;
  37285. var message = {
  37286. payload: {},
  37287. taskType: WorkerTaskType.INIT
  37288. };
  37289. this._worker.postMessage(message);
  37290. };
  37291. CollisionCoordinatorWorker.prototype.destroy = function () {
  37292. this._scene.unregisterAfterRender(this._afterRender);
  37293. this._worker.terminate();
  37294. };
  37295. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  37296. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  37297. this.onMeshUpdated(mesh);
  37298. };
  37299. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  37300. this._toRemoveMeshesArray.push(mesh.uniqueId);
  37301. };
  37302. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  37303. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  37304. geometry.onGeometryUpdated = this.onGeometryUpdated;
  37305. this.onGeometryUpdated(geometry);
  37306. };
  37307. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  37308. this._toRemoveGeometryArray.push(geometry.id);
  37309. };
  37310. return CollisionCoordinatorWorker;
  37311. }());
  37312. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  37313. var submeshes = [];
  37314. if (mesh.subMeshes) {
  37315. submeshes = mesh.subMeshes.map(function (sm, idx) {
  37316. return {
  37317. position: idx,
  37318. verticesStart: sm.verticesStart,
  37319. verticesCount: sm.verticesCount,
  37320. indexStart: sm.indexStart,
  37321. indexCount: sm.indexCount,
  37322. hasMaterial: !!sm.getMaterial(),
  37323. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  37324. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  37325. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  37326. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  37327. };
  37328. });
  37329. }
  37330. var geometryId = null;
  37331. if (mesh instanceof BABYLON.Mesh) {
  37332. geometryId = mesh.geometry ? mesh.geometry.id : null;
  37333. }
  37334. else if (mesh instanceof BABYLON.InstancedMesh) {
  37335. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  37336. }
  37337. return {
  37338. uniqueId: mesh.uniqueId,
  37339. id: mesh.id,
  37340. name: mesh.name,
  37341. geometryId: geometryId,
  37342. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  37343. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  37344. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  37345. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  37346. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  37347. subMeshes: submeshes,
  37348. checkCollisions: mesh.checkCollisions
  37349. };
  37350. };
  37351. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  37352. return {
  37353. id: geometry.id,
  37354. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  37355. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  37356. indices: new Uint32Array(geometry.getIndices() || []),
  37357. };
  37358. };
  37359. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  37360. var CollisionCoordinatorLegacy = (function () {
  37361. function CollisionCoordinatorLegacy() {
  37362. this._scaledPosition = BABYLON.Vector3.Zero();
  37363. this._scaledVelocity = BABYLON.Vector3.Zero();
  37364. this._finalPosition = BABYLON.Vector3.Zero();
  37365. }
  37366. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  37367. position.divideToRef(collider.radius, this._scaledPosition);
  37368. velocity.divideToRef(collider.radius, this._scaledVelocity);
  37369. collider.collidedMesh = null;
  37370. collider.retry = 0;
  37371. collider.initialVelocity = this._scaledVelocity;
  37372. collider.initialPosition = this._scaledPosition;
  37373. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  37374. this._finalPosition.multiplyInPlace(collider.radius);
  37375. //run the callback
  37376. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  37377. };
  37378. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  37379. this._scene = scene;
  37380. };
  37381. CollisionCoordinatorLegacy.prototype.destroy = function () {
  37382. //Legacy need no destruction method.
  37383. };
  37384. //No update in legacy mode
  37385. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  37386. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  37387. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  37388. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  37389. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  37390. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  37391. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  37392. if (excludedMesh === void 0) { excludedMesh = null; }
  37393. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  37394. if (collider.retry >= maximumRetry) {
  37395. finalPosition.copyFrom(position);
  37396. return;
  37397. }
  37398. // Check if this is a mesh else camera or -1
  37399. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  37400. collider._initialize(position, velocity, closeDistance);
  37401. // Check all meshes
  37402. for (var index = 0; index < this._scene.meshes.length; index++) {
  37403. var mesh = this._scene.meshes[index];
  37404. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  37405. mesh._checkCollision(collider);
  37406. }
  37407. }
  37408. if (!collider.collisionFound) {
  37409. position.addToRef(velocity, finalPosition);
  37410. return;
  37411. }
  37412. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  37413. collider._getResponse(position, velocity);
  37414. }
  37415. if (velocity.length() <= closeDistance) {
  37416. finalPosition.copyFrom(position);
  37417. return;
  37418. }
  37419. collider.retry++;
  37420. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  37421. };
  37422. return CollisionCoordinatorLegacy;
  37423. }());
  37424. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  37425. })(BABYLON || (BABYLON = {}));
  37426. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  37427. var BABYLON;
  37428. (function (BABYLON) {
  37429. var Particle = (function () {
  37430. function Particle() {
  37431. this.position = BABYLON.Vector3.Zero();
  37432. this.direction = BABYLON.Vector3.Zero();
  37433. this.color = new BABYLON.Color4(0, 0, 0, 0);
  37434. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  37435. this.lifeTime = 1.0;
  37436. this.age = 0;
  37437. this.size = 0;
  37438. this.angle = 0;
  37439. this.angularSpeed = 0;
  37440. }
  37441. Particle.prototype.copyTo = function (other) {
  37442. other.position.copyFrom(this.position);
  37443. other.direction.copyFrom(this.direction);
  37444. other.color.copyFrom(this.color);
  37445. other.colorStep.copyFrom(this.colorStep);
  37446. other.lifeTime = this.lifeTime;
  37447. other.age = this.age;
  37448. other.size = this.size;
  37449. other.angle = this.angle;
  37450. other.angularSpeed = this.angularSpeed;
  37451. };
  37452. return Particle;
  37453. }());
  37454. BABYLON.Particle = Particle;
  37455. })(BABYLON || (BABYLON = {}));
  37456. //# sourceMappingURL=babylon.particle.js.map
  37457. var BABYLON;
  37458. (function (BABYLON) {
  37459. var randomNumber = function (min, max) {
  37460. if (min === max) {
  37461. return (min);
  37462. }
  37463. var random = Math.random();
  37464. return ((random * (max - min)) + min);
  37465. };
  37466. var ParticleSystem = (function () {
  37467. function ParticleSystem(name, capacity, scene, customEffect) {
  37468. var _this = this;
  37469. this.name = name;
  37470. // Members
  37471. this.animations = [];
  37472. this.renderingGroupId = 0;
  37473. this.emitter = null;
  37474. this.emitRate = 10;
  37475. this.manualEmitCount = -1;
  37476. this.updateSpeed = 0.01;
  37477. this.targetStopDuration = 0;
  37478. this.disposeOnStop = false;
  37479. this.minEmitPower = 1;
  37480. this.maxEmitPower = 1;
  37481. this.minLifeTime = 1;
  37482. this.maxLifeTime = 1;
  37483. this.minSize = 1;
  37484. this.maxSize = 1;
  37485. this.minAngularSpeed = 0;
  37486. this.maxAngularSpeed = 0;
  37487. this.layerMask = 0x0FFFFFFF;
  37488. this.customShader = null;
  37489. this.preventAutoStart = false;
  37490. /**
  37491. * An event triggered when the system is disposed.
  37492. * @type {BABYLON.Observable}
  37493. */
  37494. this.onDisposeObservable = new BABYLON.Observable();
  37495. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  37496. this.forceDepthWrite = false;
  37497. this.gravity = BABYLON.Vector3.Zero();
  37498. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  37499. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  37500. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  37501. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  37502. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37503. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37504. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  37505. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37506. this.particles = new Array();
  37507. this._stockParticles = new Array();
  37508. this._newPartsExcess = 0;
  37509. this._vertexBuffers = {};
  37510. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  37511. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  37512. this._scaledDirection = BABYLON.Vector3.Zero();
  37513. this._scaledGravity = BABYLON.Vector3.Zero();
  37514. this._currentRenderId = -1;
  37515. this._started = false;
  37516. this._stopped = false;
  37517. this._actualFrame = 0;
  37518. this.id = name;
  37519. this._capacity = capacity;
  37520. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  37521. this._customEffect = customEffect;
  37522. scene.particleSystems.push(this);
  37523. var indices = [];
  37524. var index = 0;
  37525. for (var count = 0; count < capacity; count++) {
  37526. indices.push(index);
  37527. indices.push(index + 1);
  37528. indices.push(index + 2);
  37529. indices.push(index);
  37530. indices.push(index + 2);
  37531. indices.push(index + 3);
  37532. index += 4;
  37533. }
  37534. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  37535. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  37536. this._vertexData = new Float32Array(capacity * 11 * 4);
  37537. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  37538. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  37539. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  37540. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  37541. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  37542. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  37543. this._vertexBuffers["options"] = options;
  37544. // Default behaviors
  37545. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  37546. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  37547. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  37548. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  37549. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  37550. };
  37551. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  37552. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  37553. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  37554. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  37555. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  37556. };
  37557. this.updateFunction = function (particles) {
  37558. for (var index = 0; index < particles.length; index++) {
  37559. var particle = particles[index];
  37560. particle.age += _this._scaledUpdateSpeed;
  37561. if (particle.age >= particle.lifeTime) {
  37562. _this.recycleParticle(particle);
  37563. index--;
  37564. continue;
  37565. }
  37566. else {
  37567. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  37568. particle.color.addInPlace(_this._scaledColorStep);
  37569. if (particle.color.a < 0)
  37570. particle.color.a = 0;
  37571. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  37572. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  37573. particle.position.addInPlace(_this._scaledDirection);
  37574. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  37575. particle.direction.addInPlace(_this._scaledGravity);
  37576. }
  37577. }
  37578. };
  37579. }
  37580. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  37581. set: function (callback) {
  37582. if (this._onDisposeObserver) {
  37583. this.onDisposeObservable.remove(this._onDisposeObserver);
  37584. }
  37585. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  37586. },
  37587. enumerable: true,
  37588. configurable: true
  37589. });
  37590. ParticleSystem.prototype.recycleParticle = function (particle) {
  37591. var lastParticle = this.particles.pop();
  37592. if (lastParticle !== particle) {
  37593. lastParticle.copyTo(particle);
  37594. this._stockParticles.push(lastParticle);
  37595. }
  37596. };
  37597. ParticleSystem.prototype.getCapacity = function () {
  37598. return this._capacity;
  37599. };
  37600. ParticleSystem.prototype.isAlive = function () {
  37601. return this._alive;
  37602. };
  37603. ParticleSystem.prototype.isStarted = function () {
  37604. return this._started;
  37605. };
  37606. ParticleSystem.prototype.start = function () {
  37607. this._started = true;
  37608. this._stopped = false;
  37609. this._actualFrame = 0;
  37610. };
  37611. ParticleSystem.prototype.stop = function () {
  37612. this._stopped = true;
  37613. };
  37614. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  37615. var offset = index * 11;
  37616. this._vertexData[offset] = particle.position.x;
  37617. this._vertexData[offset + 1] = particle.position.y;
  37618. this._vertexData[offset + 2] = particle.position.z;
  37619. this._vertexData[offset + 3] = particle.color.r;
  37620. this._vertexData[offset + 4] = particle.color.g;
  37621. this._vertexData[offset + 5] = particle.color.b;
  37622. this._vertexData[offset + 6] = particle.color.a;
  37623. this._vertexData[offset + 7] = particle.angle;
  37624. this._vertexData[offset + 8] = particle.size;
  37625. this._vertexData[offset + 9] = offsetX;
  37626. this._vertexData[offset + 10] = offsetY;
  37627. };
  37628. ParticleSystem.prototype._update = function (newParticles) {
  37629. // Update current
  37630. this._alive = this.particles.length > 0;
  37631. this.updateFunction(this.particles);
  37632. // Add new ones
  37633. var worldMatrix;
  37634. if (this.emitter.position) {
  37635. worldMatrix = this.emitter.getWorldMatrix();
  37636. }
  37637. else {
  37638. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  37639. }
  37640. var particle;
  37641. for (var index = 0; index < newParticles; index++) {
  37642. if (this.particles.length === this._capacity) {
  37643. break;
  37644. }
  37645. if (this._stockParticles.length !== 0) {
  37646. particle = this._stockParticles.pop();
  37647. particle.age = 0;
  37648. }
  37649. else {
  37650. particle = new BABYLON.Particle();
  37651. }
  37652. this.particles.push(particle);
  37653. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  37654. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  37655. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  37656. particle.size = randomNumber(this.minSize, this.maxSize);
  37657. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  37658. this.startPositionFunction(worldMatrix, particle.position, particle);
  37659. var step = randomNumber(0, 1.0);
  37660. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  37661. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  37662. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  37663. }
  37664. };
  37665. ParticleSystem.prototype._getEffect = function () {
  37666. if (this._customEffect) {
  37667. return this._customEffect;
  37668. }
  37669. ;
  37670. var defines = [];
  37671. if (this._scene.clipPlane) {
  37672. defines.push("#define CLIPPLANE");
  37673. }
  37674. // Effect
  37675. var join = defines.join("\n");
  37676. if (this._cachedDefines !== join) {
  37677. this._cachedDefines = join;
  37678. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  37679. }
  37680. return this._effect;
  37681. };
  37682. ParticleSystem.prototype.animate = function () {
  37683. if (!this._started)
  37684. return;
  37685. var effect = this._getEffect();
  37686. // Check
  37687. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  37688. return;
  37689. if (this._currentRenderId === this._scene.getRenderId()) {
  37690. return;
  37691. }
  37692. this._currentRenderId = this._scene.getRenderId();
  37693. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  37694. // determine the number of particles we need to create
  37695. var newParticles;
  37696. if (this.manualEmitCount > -1) {
  37697. newParticles = this.manualEmitCount;
  37698. this._newPartsExcess = 0;
  37699. this.manualEmitCount = 0;
  37700. }
  37701. else {
  37702. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  37703. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  37704. }
  37705. if (this._newPartsExcess > 1.0) {
  37706. newParticles += this._newPartsExcess >> 0;
  37707. this._newPartsExcess -= this._newPartsExcess >> 0;
  37708. }
  37709. this._alive = false;
  37710. if (!this._stopped) {
  37711. this._actualFrame += this._scaledUpdateSpeed;
  37712. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  37713. this.stop();
  37714. }
  37715. else {
  37716. newParticles = 0;
  37717. }
  37718. this._update(newParticles);
  37719. // Stopped?
  37720. if (this._stopped) {
  37721. if (!this._alive) {
  37722. this._started = false;
  37723. if (this.disposeOnStop) {
  37724. this._scene._toBeDisposed.push(this);
  37725. }
  37726. }
  37727. }
  37728. // Update VBO
  37729. var offset = 0;
  37730. for (var index = 0; index < this.particles.length; index++) {
  37731. var particle = this.particles[index];
  37732. this._appendParticleVertex(offset++, particle, 0, 0);
  37733. this._appendParticleVertex(offset++, particle, 1, 0);
  37734. this._appendParticleVertex(offset++, particle, 1, 1);
  37735. this._appendParticleVertex(offset++, particle, 0, 1);
  37736. }
  37737. this._vertexBuffer.update(this._vertexData);
  37738. };
  37739. ParticleSystem.prototype.render = function () {
  37740. var effect = this._getEffect();
  37741. // Check
  37742. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  37743. return 0;
  37744. var engine = this._scene.getEngine();
  37745. // Render
  37746. engine.enableEffect(effect);
  37747. engine.setState(false);
  37748. var viewMatrix = this._scene.getViewMatrix();
  37749. effect.setTexture("diffuseSampler", this.particleTexture);
  37750. effect.setMatrix("view", viewMatrix);
  37751. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  37752. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  37753. if (this._scene.clipPlane) {
  37754. var clipPlane = this._scene.clipPlane;
  37755. var invView = viewMatrix.clone();
  37756. invView.invert();
  37757. effect.setMatrix("invView", invView);
  37758. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  37759. }
  37760. // VBOs
  37761. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37762. // Draw order
  37763. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  37764. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  37765. }
  37766. else {
  37767. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  37768. }
  37769. if (this.forceDepthWrite) {
  37770. engine.setDepthWrite(true);
  37771. }
  37772. engine.draw(true, 0, this.particles.length * 6);
  37773. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37774. return this.particles.length;
  37775. };
  37776. ParticleSystem.prototype.dispose = function () {
  37777. if (this._vertexBuffer) {
  37778. this._vertexBuffer.dispose();
  37779. this._vertexBuffer = null;
  37780. }
  37781. if (this._indexBuffer) {
  37782. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37783. this._indexBuffer = null;
  37784. }
  37785. if (this.particleTexture) {
  37786. this.particleTexture.dispose();
  37787. this.particleTexture = null;
  37788. }
  37789. // Remove from scene
  37790. var index = this._scene.particleSystems.indexOf(this);
  37791. this._scene.particleSystems.splice(index, 1);
  37792. // Callback
  37793. this.onDisposeObservable.notifyObservers(this);
  37794. this.onDisposeObservable.clear();
  37795. };
  37796. // Clone
  37797. ParticleSystem.prototype.clone = function (name, newEmitter) {
  37798. var custom = null;
  37799. var program = null;
  37800. if (this.customShader != null) {
  37801. program = this.customShader;
  37802. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  37803. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  37804. }
  37805. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  37806. result.customShader = program;
  37807. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  37808. if (newEmitter === undefined) {
  37809. newEmitter = this.emitter;
  37810. }
  37811. result.emitter = newEmitter;
  37812. if (this.particleTexture) {
  37813. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  37814. }
  37815. if (!this.preventAutoStart) {
  37816. result.start();
  37817. }
  37818. return result;
  37819. };
  37820. ParticleSystem.prototype.serialize = function () {
  37821. var serializationObject = {};
  37822. serializationObject.name = this.name;
  37823. serializationObject.id = this.id;
  37824. // Emitter
  37825. if (this.emitter.position) {
  37826. serializationObject.emitterId = this.emitter.id;
  37827. }
  37828. else {
  37829. serializationObject.emitter = this.emitter.asArray();
  37830. }
  37831. serializationObject.capacity = this.getCapacity();
  37832. if (this.particleTexture) {
  37833. serializationObject.textureName = this.particleTexture.name;
  37834. }
  37835. // Animations
  37836. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  37837. // Particle system
  37838. serializationObject.minAngularSpeed = this.minAngularSpeed;
  37839. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  37840. serializationObject.minSize = this.minSize;
  37841. serializationObject.maxSize = this.maxSize;
  37842. serializationObject.minEmitPower = this.minEmitPower;
  37843. serializationObject.maxEmitPower = this.maxEmitPower;
  37844. serializationObject.minLifeTime = this.minLifeTime;
  37845. serializationObject.maxLifeTime = this.maxLifeTime;
  37846. serializationObject.emitRate = this.emitRate;
  37847. serializationObject.minEmitBox = this.minEmitBox.asArray();
  37848. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  37849. serializationObject.gravity = this.gravity.asArray();
  37850. serializationObject.direction1 = this.direction1.asArray();
  37851. serializationObject.direction2 = this.direction2.asArray();
  37852. serializationObject.color1 = this.color1.asArray();
  37853. serializationObject.color2 = this.color2.asArray();
  37854. serializationObject.colorDead = this.colorDead.asArray();
  37855. serializationObject.updateSpeed = this.updateSpeed;
  37856. serializationObject.targetStopDuration = this.targetStopDuration;
  37857. serializationObject.textureMask = this.textureMask.asArray();
  37858. serializationObject.blendMode = this.blendMode;
  37859. serializationObject.customShader = this.customShader;
  37860. serializationObject.preventAutoStart = this.preventAutoStart;
  37861. return serializationObject;
  37862. };
  37863. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  37864. var name = parsedParticleSystem.name;
  37865. var custom = null;
  37866. var program = null;
  37867. if (parsedParticleSystem.customShader) {
  37868. program = parsedParticleSystem.customShader;
  37869. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  37870. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  37871. }
  37872. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  37873. particleSystem.customShader = program;
  37874. if (parsedParticleSystem.id) {
  37875. particleSystem.id = parsedParticleSystem.id;
  37876. }
  37877. // Auto start
  37878. if (parsedParticleSystem.preventAutoStart) {
  37879. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  37880. }
  37881. // Texture
  37882. if (parsedParticleSystem.textureName) {
  37883. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  37884. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  37885. }
  37886. // Emitter
  37887. if (parsedParticleSystem.emitterId) {
  37888. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  37889. }
  37890. else {
  37891. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  37892. }
  37893. // Animations
  37894. if (parsedParticleSystem.animations) {
  37895. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  37896. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  37897. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  37898. }
  37899. }
  37900. if (parsedParticleSystem.autoAnimate) {
  37901. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  37902. }
  37903. // Particle system
  37904. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  37905. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  37906. particleSystem.minSize = parsedParticleSystem.minSize;
  37907. particleSystem.maxSize = parsedParticleSystem.maxSize;
  37908. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  37909. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  37910. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  37911. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  37912. particleSystem.emitRate = parsedParticleSystem.emitRate;
  37913. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  37914. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  37915. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  37916. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  37917. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  37918. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  37919. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  37920. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  37921. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  37922. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  37923. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  37924. particleSystem.blendMode = parsedParticleSystem.blendMode;
  37925. if (!particleSystem.preventAutoStart) {
  37926. particleSystem.start();
  37927. }
  37928. return particleSystem;
  37929. };
  37930. return ParticleSystem;
  37931. }());
  37932. // Statics
  37933. ParticleSystem.BLENDMODE_ONEONE = 0;
  37934. ParticleSystem.BLENDMODE_STANDARD = 1;
  37935. BABYLON.ParticleSystem = ParticleSystem;
  37936. })(BABYLON || (BABYLON = {}));
  37937. //# sourceMappingURL=babylon.particleSystem.js.map
  37938. var BABYLON;
  37939. (function (BABYLON) {
  37940. var SolidParticle = (function () {
  37941. /**
  37942. * Creates a Solid Particle object.
  37943. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  37944. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  37945. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  37946. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  37947. * `shapeId` (integer) is the model shape identifier in the SPS.
  37948. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  37949. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  37950. */
  37951. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  37952. this.idx = 0; // particle global index
  37953. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  37954. this.position = BABYLON.Vector3.Zero(); // position
  37955. this.rotation = BABYLON.Vector3.Zero(); // rotation
  37956. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  37957. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  37958. this.velocity = BABYLON.Vector3.Zero(); // velocity
  37959. this.alive = true; // alive
  37960. this.isVisible = true; // visibility
  37961. this._pos = 0; // index of this particle in the global "positions" array
  37962. this.shapeId = 0; // model shape id
  37963. this.idxInShape = 0; // index of the particle in its shape id
  37964. this.idx = particleIndex;
  37965. this._pos = positionIndex;
  37966. this._model = model;
  37967. this.shapeId = shapeId;
  37968. this.idxInShape = idxInShape;
  37969. this._sps = sps;
  37970. if (modelBoundingInfo) {
  37971. this._modelBoundingInfo = modelBoundingInfo;
  37972. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  37973. }
  37974. }
  37975. Object.defineProperty(SolidParticle.prototype, "scale", {
  37976. /**
  37977. * legacy support, changed scale to scaling
  37978. */
  37979. get: function () {
  37980. return this.scaling;
  37981. },
  37982. set: function (scale) {
  37983. this.scaling = scale;
  37984. },
  37985. enumerable: true,
  37986. configurable: true
  37987. });
  37988. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  37989. /**
  37990. * legacy support, changed quaternion to rotationQuaternion
  37991. */
  37992. get: function () {
  37993. return this.rotationQuaternion;
  37994. },
  37995. set: function (q) {
  37996. this.rotationQuaternion = q;
  37997. },
  37998. enumerable: true,
  37999. configurable: true
  38000. });
  38001. /**
  38002. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  38003. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  38004. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  38005. */
  38006. SolidParticle.prototype.intersectsMesh = function (target) {
  38007. if (!this._boundingInfo || !target._boundingInfo) {
  38008. return false;
  38009. }
  38010. if (this._sps._bSphereOnly) {
  38011. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  38012. }
  38013. return this._boundingInfo.intersects(target._boundingInfo, false);
  38014. };
  38015. return SolidParticle;
  38016. }());
  38017. BABYLON.SolidParticle = SolidParticle;
  38018. var ModelShape = (function () {
  38019. /**
  38020. * 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.
  38021. * SPS internal tool, don't use it manually.
  38022. */
  38023. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  38024. this.shapeID = id;
  38025. this._shape = shape;
  38026. this._shapeUV = shapeUV;
  38027. this._positionFunction = posFunction;
  38028. this._vertexFunction = vtxFunction;
  38029. }
  38030. return ModelShape;
  38031. }());
  38032. BABYLON.ModelShape = ModelShape;
  38033. })(BABYLON || (BABYLON = {}));
  38034. //# sourceMappingURL=babylon.solidParticle.js.map
  38035. var BABYLON;
  38036. (function (BABYLON) {
  38037. /**
  38038. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  38039. */
  38040. var SolidParticleSystem = (function () {
  38041. /**
  38042. * Creates a SPS (Solid Particle System) object.
  38043. * `name` (String) is the SPS name, this will be the underlying mesh name.
  38044. * `scene` (Scene) is the scene in which the SPS is added.
  38045. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  38046. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  38047. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  38048. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  38049. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  38050. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  38051. */
  38052. function SolidParticleSystem(name, scene, options) {
  38053. // public members
  38054. /**
  38055. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  38056. * Example : var p = SPS.particles[i];
  38057. */
  38058. this.particles = new Array();
  38059. /**
  38060. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  38061. */
  38062. this.nbParticles = 0;
  38063. /**
  38064. * If the particles must ever face the camera (default false). Useful for planar particles.
  38065. */
  38066. this.billboard = false;
  38067. /**
  38068. * Recompute normals when adding a shape
  38069. */
  38070. this.recomputeNormals = true;
  38071. /**
  38072. * This a counter ofr your own usage. It's not set by any SPS functions.
  38073. */
  38074. this.counter = 0;
  38075. /**
  38076. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  38077. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  38078. */
  38079. this.vars = {};
  38080. this._positions = new Array();
  38081. this._indices = new Array();
  38082. this._normals = new Array();
  38083. this._colors = new Array();
  38084. this._uvs = new Array();
  38085. this._index = 0; // indices index
  38086. this._updatable = true;
  38087. this._pickable = false;
  38088. this._isVisibilityBoxLocked = false;
  38089. this._alwaysVisible = false;
  38090. this._shapeCounter = 0;
  38091. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  38092. this._color = new BABYLON.Color4(0, 0, 0, 0);
  38093. this._computeParticleColor = true;
  38094. this._computeParticleTexture = true;
  38095. this._computeParticleRotation = true;
  38096. this._computeParticleVertex = false;
  38097. this._computeBoundingBox = false;
  38098. this._cam_axisZ = BABYLON.Vector3.Zero();
  38099. this._cam_axisY = BABYLON.Vector3.Zero();
  38100. this._cam_axisX = BABYLON.Vector3.Zero();
  38101. this._axisX = BABYLON.Axis.X;
  38102. this._axisY = BABYLON.Axis.Y;
  38103. this._axisZ = BABYLON.Axis.Z;
  38104. this._camDir = BABYLON.Vector3.Zero();
  38105. this._rotMatrix = new BABYLON.Matrix();
  38106. this._invertMatrix = new BABYLON.Matrix();
  38107. this._rotated = BABYLON.Vector3.Zero();
  38108. this._quaternion = new BABYLON.Quaternion();
  38109. this._vertex = BABYLON.Vector3.Zero();
  38110. this._normal = BABYLON.Vector3.Zero();
  38111. this._yaw = 0.0;
  38112. this._pitch = 0.0;
  38113. this._roll = 0.0;
  38114. this._halfroll = 0.0;
  38115. this._halfpitch = 0.0;
  38116. this._halfyaw = 0.0;
  38117. this._sinRoll = 0.0;
  38118. this._cosRoll = 0.0;
  38119. this._sinPitch = 0.0;
  38120. this._cosPitch = 0.0;
  38121. this._sinYaw = 0.0;
  38122. this._cosYaw = 0.0;
  38123. this._w = 0.0;
  38124. this._mustUnrotateFixedNormals = false;
  38125. this._minimum = BABYLON.Tmp.Vector3[0];
  38126. this._maximum = BABYLON.Tmp.Vector3[1];
  38127. this._scale = BABYLON.Tmp.Vector3[2];
  38128. this._translation = BABYLON.Tmp.Vector3[3];
  38129. this._minBbox = BABYLON.Tmp.Vector3[4];
  38130. this._maxBbox = BABYLON.Tmp.Vector3[5];
  38131. this._particlesIntersect = false;
  38132. this._bSphereOnly = false;
  38133. this._bSphereRadiusFactor = 1.0;
  38134. this.name = name;
  38135. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38136. this._camera = scene.activeCamera;
  38137. this._pickable = options ? options.isPickable : false;
  38138. this._particlesIntersect = options ? options.particleIntersection : false;
  38139. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  38140. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  38141. if (options && options.updatable) {
  38142. this._updatable = options.updatable;
  38143. }
  38144. else {
  38145. this._updatable = true;
  38146. }
  38147. if (this._pickable) {
  38148. this.pickedParticles = [];
  38149. }
  38150. }
  38151. /**
  38152. * Builds the SPS underlying mesh. Returns a standard Mesh.
  38153. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  38154. */
  38155. SolidParticleSystem.prototype.buildMesh = function () {
  38156. if (this.nbParticles === 0) {
  38157. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  38158. this.addShape(triangle, 1);
  38159. triangle.dispose();
  38160. }
  38161. this._positions32 = new Float32Array(this._positions);
  38162. this._uvs32 = new Float32Array(this._uvs);
  38163. this._colors32 = new Float32Array(this._colors);
  38164. if (this.recomputeNormals) {
  38165. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  38166. }
  38167. this._normals32 = new Float32Array(this._normals);
  38168. this._fixedNormal32 = new Float32Array(this._normals);
  38169. if (this._mustUnrotateFixedNormals) {
  38170. this._unrotateFixedNormals();
  38171. }
  38172. var vertexData = new BABYLON.VertexData();
  38173. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  38174. vertexData.indices = this._indices;
  38175. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  38176. if (this._uvs32) {
  38177. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  38178. ;
  38179. }
  38180. if (this._colors32) {
  38181. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  38182. }
  38183. var mesh = new BABYLON.Mesh(this.name, this._scene);
  38184. vertexData.applyToMesh(mesh, this._updatable);
  38185. this.mesh = mesh;
  38186. this.mesh.isPickable = this._pickable;
  38187. // free memory
  38188. this._positions = null;
  38189. this._normals = null;
  38190. this._uvs = null;
  38191. this._colors = null;
  38192. if (!this._updatable) {
  38193. this.particles.length = 0;
  38194. }
  38195. return mesh;
  38196. };
  38197. /**
  38198. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  38199. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  38200. * Thus the particles generated from `digest()` have their property `position` set yet.
  38201. * `mesh` ( Mesh ) is the mesh to be digested
  38202. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  38203. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  38204. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  38205. */
  38206. SolidParticleSystem.prototype.digest = function (mesh, options) {
  38207. var size = (options && options.facetNb) || 1;
  38208. var number = (options && options.number);
  38209. var delta = (options && options.delta) || 0;
  38210. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38211. var meshInd = mesh.getIndices();
  38212. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38213. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38214. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38215. var f = 0; // facet counter
  38216. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  38217. // compute size from number
  38218. if (number) {
  38219. number = (number > totalFacets) ? totalFacets : number;
  38220. size = Math.round(totalFacets / number);
  38221. delta = 0;
  38222. }
  38223. else {
  38224. size = (size > totalFacets) ? totalFacets : size;
  38225. }
  38226. var facetPos = []; // submesh positions
  38227. var facetInd = []; // submesh indices
  38228. var facetUV = []; // submesh UV
  38229. var facetCol = []; // submesh colors
  38230. var barycenter = BABYLON.Tmp.Vector3[0];
  38231. var rand;
  38232. var sizeO = size;
  38233. while (f < totalFacets) {
  38234. size = sizeO + Math.floor((1 + delta) * Math.random());
  38235. if (f > totalFacets - size) {
  38236. size = totalFacets - f;
  38237. }
  38238. // reset temp arrays
  38239. facetPos.length = 0;
  38240. facetInd.length = 0;
  38241. facetUV.length = 0;
  38242. facetCol.length = 0;
  38243. // iterate over "size" facets
  38244. var fi = 0;
  38245. for (var j = f * 3; j < (f + size) * 3; j++) {
  38246. facetInd.push(fi);
  38247. var i = meshInd[j];
  38248. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  38249. if (meshUV) {
  38250. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  38251. }
  38252. if (meshCol) {
  38253. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  38254. }
  38255. fi++;
  38256. }
  38257. // create a model shape for each single particle
  38258. var idx = this.nbParticles;
  38259. var shape = this._posToShape(facetPos);
  38260. var shapeUV = this._uvsToShapeUV(facetUV);
  38261. // compute the barycenter of the shape
  38262. var v;
  38263. for (v = 0; v < shape.length; v++) {
  38264. barycenter.addInPlace(shape[v]);
  38265. }
  38266. barycenter.scaleInPlace(1 / shape.length);
  38267. // shift the shape from its barycenter to the origin
  38268. for (v = 0; v < shape.length; v++) {
  38269. shape[v].subtractInPlace(barycenter);
  38270. }
  38271. var bInfo;
  38272. if (this._particlesIntersect) {
  38273. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  38274. }
  38275. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  38276. // add the particle in the SPS
  38277. var currentPos = this._positions.length;
  38278. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  38279. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  38280. // initialize the particle position
  38281. this.particles[this.nbParticles].position.addInPlace(barycenter);
  38282. this._index += shape.length;
  38283. idx++;
  38284. this.nbParticles++;
  38285. this._shapeCounter++;
  38286. f += size;
  38287. }
  38288. return this;
  38289. };
  38290. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  38291. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  38292. var index = 0;
  38293. var idx = 0;
  38294. for (var p = 0; p < this.particles.length; p++) {
  38295. this._particle = this.particles[p];
  38296. this._shape = this._particle._model._shape;
  38297. if (this._particle.rotationQuaternion) {
  38298. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  38299. }
  38300. else {
  38301. this._yaw = this._particle.rotation.y;
  38302. this._pitch = this._particle.rotation.x;
  38303. this._roll = this._particle.rotation.z;
  38304. this._quaternionRotationYPR();
  38305. }
  38306. this._quaternionToRotationMatrix();
  38307. this._rotMatrix.invertToRef(this._invertMatrix);
  38308. for (var pt = 0; pt < this._shape.length; pt++) {
  38309. idx = index + pt * 3;
  38310. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  38311. this._fixedNormal32[idx] = this._normal.x;
  38312. this._fixedNormal32[idx + 1] = this._normal.y;
  38313. this._fixedNormal32[idx + 2] = this._normal.z;
  38314. }
  38315. index = idx + 3;
  38316. }
  38317. };
  38318. //reset copy
  38319. SolidParticleSystem.prototype._resetCopy = function () {
  38320. this._copy.position.x = 0;
  38321. this._copy.position.y = 0;
  38322. this._copy.position.z = 0;
  38323. this._copy.rotation.x = 0;
  38324. this._copy.rotation.y = 0;
  38325. this._copy.rotation.z = 0;
  38326. this._copy.rotationQuaternion = null;
  38327. this._copy.scaling.x = 1;
  38328. this._copy.scaling.y = 1;
  38329. this._copy.scaling.z = 1;
  38330. this._copy.uvs.x = 0;
  38331. this._copy.uvs.y = 0;
  38332. this._copy.uvs.z = 1;
  38333. this._copy.uvs.w = 1;
  38334. this._copy.color = null;
  38335. };
  38336. // _meshBuilder : inserts the shape model in the global SPS mesh
  38337. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  38338. var i;
  38339. var u = 0;
  38340. var c = 0;
  38341. var n = 0;
  38342. this._resetCopy();
  38343. if (options && options.positionFunction) {
  38344. options.positionFunction(this._copy, idx, idxInShape);
  38345. this._mustUnrotateFixedNormals = true;
  38346. }
  38347. if (this._copy.rotationQuaternion) {
  38348. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  38349. }
  38350. else {
  38351. this._yaw = this._copy.rotation.y;
  38352. this._pitch = this._copy.rotation.x;
  38353. this._roll = this._copy.rotation.z;
  38354. this._quaternionRotationYPR();
  38355. }
  38356. this._quaternionToRotationMatrix();
  38357. for (i = 0; i < shape.length; i++) {
  38358. this._vertex.x = shape[i].x;
  38359. this._vertex.y = shape[i].y;
  38360. this._vertex.z = shape[i].z;
  38361. if (options && options.vertexFunction) {
  38362. options.vertexFunction(this._copy, this._vertex, i);
  38363. }
  38364. this._vertex.x *= this._copy.scaling.x;
  38365. this._vertex.y *= this._copy.scaling.y;
  38366. this._vertex.z *= this._copy.scaling.z;
  38367. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38368. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  38369. if (meshUV) {
  38370. 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);
  38371. u += 2;
  38372. }
  38373. if (this._copy.color) {
  38374. this._color = this._copy.color;
  38375. }
  38376. else if (meshCol && meshCol[c] !== undefined) {
  38377. this._color.r = meshCol[c];
  38378. this._color.g = meshCol[c + 1];
  38379. this._color.b = meshCol[c + 2];
  38380. this._color.a = meshCol[c + 3];
  38381. }
  38382. else {
  38383. this._color.r = 1;
  38384. this._color.g = 1;
  38385. this._color.b = 1;
  38386. this._color.a = 1;
  38387. }
  38388. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  38389. c += 4;
  38390. if (!this.recomputeNormals && meshNor) {
  38391. this._normal.x = meshNor[n];
  38392. this._normal.y = meshNor[n + 1];
  38393. this._normal.z = meshNor[n + 2];
  38394. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  38395. normals.push(this._normal.x, this._normal.y, this._normal.z);
  38396. n += 3;
  38397. }
  38398. }
  38399. for (i = 0; i < meshInd.length; i++) {
  38400. indices.push(p + meshInd[i]);
  38401. }
  38402. if (this._pickable) {
  38403. var nbfaces = meshInd.length / 3;
  38404. for (i = 0; i < nbfaces; i++) {
  38405. this.pickedParticles.push({ idx: idx, faceId: i });
  38406. }
  38407. }
  38408. return this._copy;
  38409. };
  38410. // returns a shape array from positions array
  38411. SolidParticleSystem.prototype._posToShape = function (positions) {
  38412. var shape = [];
  38413. for (var i = 0; i < positions.length; i += 3) {
  38414. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  38415. }
  38416. return shape;
  38417. };
  38418. // returns a shapeUV array from a Vector4 uvs
  38419. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  38420. var shapeUV = [];
  38421. if (uvs) {
  38422. for (var i = 0; i < uvs.length; i++)
  38423. shapeUV.push(uvs[i]);
  38424. }
  38425. return shapeUV;
  38426. };
  38427. // adds a new particle object in the particles array
  38428. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  38429. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  38430. this.particles.push(sp);
  38431. return sp;
  38432. };
  38433. /**
  38434. * Adds some particles to the SPS from the model shape. Returns the shape id.
  38435. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  38436. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  38437. * `nb` (positive integer) the number of particles to be created from this model
  38438. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  38439. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  38440. */
  38441. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  38442. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38443. var meshInd = mesh.getIndices();
  38444. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38445. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38446. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38447. var bbInfo;
  38448. if (this._particlesIntersect) {
  38449. bbInfo = mesh.getBoundingInfo();
  38450. }
  38451. var shape = this._posToShape(meshPos);
  38452. var shapeUV = this._uvsToShapeUV(meshUV);
  38453. var posfunc = options ? options.positionFunction : null;
  38454. var vtxfunc = options ? options.vertexFunction : null;
  38455. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  38456. // particles
  38457. var sp;
  38458. var currentCopy;
  38459. var idx = this.nbParticles;
  38460. for (var i = 0; i < nb; i++) {
  38461. var currentPos = this._positions.length;
  38462. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  38463. if (this._updatable) {
  38464. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  38465. sp.position.copyFrom(currentCopy.position);
  38466. sp.rotation.copyFrom(currentCopy.rotation);
  38467. if (currentCopy.rotationQuaternion) {
  38468. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  38469. }
  38470. if (currentCopy.color) {
  38471. sp.color.copyFrom(currentCopy.color);
  38472. }
  38473. sp.scaling.copyFrom(currentCopy.scaling);
  38474. sp.uvs.copyFrom(currentCopy.uvs);
  38475. }
  38476. this._index += shape.length;
  38477. idx++;
  38478. }
  38479. this.nbParticles += nb;
  38480. this._shapeCounter++;
  38481. return this._shapeCounter - 1;
  38482. };
  38483. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  38484. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  38485. this._resetCopy();
  38486. if (particle._model._positionFunction) {
  38487. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  38488. }
  38489. if (this._copy.rotationQuaternion) {
  38490. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  38491. }
  38492. else {
  38493. this._yaw = this._copy.rotation.y;
  38494. this._pitch = this._copy.rotation.x;
  38495. this._roll = this._copy.rotation.z;
  38496. this._quaternionRotationYPR();
  38497. }
  38498. this._quaternionToRotationMatrix();
  38499. this._shape = particle._model._shape;
  38500. for (var pt = 0; pt < this._shape.length; pt++) {
  38501. this._vertex.x = this._shape[pt].x;
  38502. this._vertex.y = this._shape[pt].y;
  38503. this._vertex.z = this._shape[pt].z;
  38504. if (particle._model._vertexFunction) {
  38505. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  38506. }
  38507. this._vertex.x *= this._copy.scaling.x;
  38508. this._vertex.y *= this._copy.scaling.y;
  38509. this._vertex.z *= this._copy.scaling.z;
  38510. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38511. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  38512. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  38513. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  38514. }
  38515. particle.position.x = 0.0;
  38516. particle.position.y = 0.0;
  38517. particle.position.z = 0.0;
  38518. particle.rotation.x = 0.0;
  38519. particle.rotation.y = 0.0;
  38520. particle.rotation.z = 0.0;
  38521. particle.rotationQuaternion = null;
  38522. particle.scaling.x = 1.0;
  38523. particle.scaling.y = 1.0;
  38524. particle.scaling.z = 1.0;
  38525. };
  38526. /**
  38527. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  38528. * Returns the SPS.
  38529. */
  38530. SolidParticleSystem.prototype.rebuildMesh = function () {
  38531. for (var p = 0; p < this.particles.length; p++) {
  38532. this._rebuildParticle(this.particles[p]);
  38533. }
  38534. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38535. return this;
  38536. };
  38537. /**
  38538. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  38539. * This method calls `updateParticle()` for each particle of the SPS.
  38540. * For an animated SPS, it is usually called within the render loop.
  38541. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  38542. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  38543. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  38544. * Returns the SPS.
  38545. */
  38546. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  38547. if (start === void 0) { start = 0; }
  38548. if (end === void 0) { end = this.nbParticles - 1; }
  38549. if (update === void 0) { update = true; }
  38550. if (!this._updatable) {
  38551. return;
  38552. }
  38553. // custom beforeUpdate
  38554. this.beforeUpdateParticles(start, end, update);
  38555. this._cam_axisX.x = 1.0;
  38556. this._cam_axisX.y = 0.0;
  38557. this._cam_axisX.z = 0.0;
  38558. this._cam_axisY.x = 0.0;
  38559. this._cam_axisY.y = 1.0;
  38560. this._cam_axisY.z = 0.0;
  38561. this._cam_axisZ.x = 0.0;
  38562. this._cam_axisZ.y = 0.0;
  38563. this._cam_axisZ.z = 1.0;
  38564. // if the particles will always face the camera
  38565. if (this.billboard) {
  38566. this.mesh.computeWorldMatrix(true);
  38567. // compute the camera position and un-rotate it by the current mesh rotation
  38568. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  38569. this._quaternionToRotationMatrix();
  38570. this._rotMatrix.invertToRef(this._invertMatrix);
  38571. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  38572. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  38573. this._cam_axisZ.normalize();
  38574. // same for camera up vector extracted from the cam view matrix
  38575. var view = this._camera.getViewMatrix(true);
  38576. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  38577. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  38578. this._cam_axisY.normalize();
  38579. this._cam_axisX.normalize();
  38580. }
  38581. }
  38582. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  38583. var idx = 0; // current position index in the global array positions32
  38584. var index = 0; // position start index in the global array positions32 of the current particle
  38585. var colidx = 0; // current color index in the global array colors32
  38586. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  38587. var uvidx = 0; // current uv index in the global array uvs32
  38588. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  38589. var pt = 0; // current index in the particle model shape
  38590. if (this.mesh.isFacetDataEnabled) {
  38591. this._computeBoundingBox = true;
  38592. }
  38593. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  38594. if (this._computeBoundingBox) {
  38595. if (start == 0 && end == this.nbParticles - 1) {
  38596. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  38597. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  38598. }
  38599. else {
  38600. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  38601. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  38602. }
  38603. }
  38604. // particle loop
  38605. index = this.particles[start]._pos;
  38606. var vpos = (index / 3) | 0;
  38607. colorIndex = vpos * 4;
  38608. uvIndex = vpos * 2;
  38609. for (var p = start; p <= end; p++) {
  38610. this._particle = this.particles[p];
  38611. this._shape = this._particle._model._shape;
  38612. this._shapeUV = this._particle._model._shapeUV;
  38613. // call to custom user function to update the particle properties
  38614. this.updateParticle(this._particle);
  38615. if (this._particle.isVisible) {
  38616. // particle rotation matrix
  38617. if (this.billboard) {
  38618. this._particle.rotation.x = 0.0;
  38619. this._particle.rotation.y = 0.0;
  38620. }
  38621. if (this._computeParticleRotation || this.billboard) {
  38622. if (this._particle.rotationQuaternion) {
  38623. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  38624. }
  38625. else {
  38626. this._yaw = this._particle.rotation.y;
  38627. this._pitch = this._particle.rotation.x;
  38628. this._roll = this._particle.rotation.z;
  38629. this._quaternionRotationYPR();
  38630. }
  38631. this._quaternionToRotationMatrix();
  38632. }
  38633. // particle vertex loop
  38634. for (pt = 0; pt < this._shape.length; pt++) {
  38635. idx = index + pt * 3;
  38636. colidx = colorIndex + pt * 4;
  38637. uvidx = uvIndex + pt * 2;
  38638. this._vertex.x = this._shape[pt].x;
  38639. this._vertex.y = this._shape[pt].y;
  38640. this._vertex.z = this._shape[pt].z;
  38641. if (this._computeParticleVertex) {
  38642. this.updateParticleVertex(this._particle, this._vertex, pt);
  38643. }
  38644. // positions
  38645. this._vertex.x *= this._particle.scaling.x;
  38646. this._vertex.y *= this._particle.scaling.y;
  38647. this._vertex.z *= this._particle.scaling.z;
  38648. 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];
  38649. 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;
  38650. 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;
  38651. 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;
  38652. 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;
  38653. 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;
  38654. 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;
  38655. if (this._computeBoundingBox) {
  38656. if (this._positions32[idx] < this._minimum.x) {
  38657. this._minimum.x = this._positions32[idx];
  38658. }
  38659. if (this._positions32[idx] > this._maximum.x) {
  38660. this._maximum.x = this._positions32[idx];
  38661. }
  38662. if (this._positions32[idx + 1] < this._minimum.y) {
  38663. this._minimum.y = this._positions32[idx + 1];
  38664. }
  38665. if (this._positions32[idx + 1] > this._maximum.y) {
  38666. this._maximum.y = this._positions32[idx + 1];
  38667. }
  38668. if (this._positions32[idx + 2] < this._minimum.z) {
  38669. this._minimum.z = this._positions32[idx + 2];
  38670. }
  38671. if (this._positions32[idx + 2] > this._maximum.z) {
  38672. this._maximum.z = this._positions32[idx + 2];
  38673. }
  38674. }
  38675. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  38676. if (!this._computeParticleVertex) {
  38677. this._normal.x = this._fixedNormal32[idx];
  38678. this._normal.y = this._fixedNormal32[idx + 1];
  38679. this._normal.z = this._fixedNormal32[idx + 2];
  38680. 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]);
  38681. 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]);
  38682. 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]);
  38683. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  38684. 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;
  38685. 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;
  38686. }
  38687. if (this._computeParticleColor) {
  38688. this._colors32[colidx] = this._particle.color.r;
  38689. this._colors32[colidx + 1] = this._particle.color.g;
  38690. this._colors32[colidx + 2] = this._particle.color.b;
  38691. this._colors32[colidx + 3] = this._particle.color.a;
  38692. }
  38693. if (this._computeParticleTexture) {
  38694. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38695. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38696. }
  38697. }
  38698. }
  38699. else {
  38700. for (pt = 0; pt < this._shape.length; pt++) {
  38701. idx = index + pt * 3;
  38702. colidx = colorIndex + pt * 4;
  38703. uvidx = uvIndex + pt * 2;
  38704. this._positions32[idx] = this._camera.position.x;
  38705. this._positions32[idx + 1] = this._camera.position.y;
  38706. this._positions32[idx + 2] = this._camera.position.z;
  38707. this._normals32[idx] = 0.0;
  38708. this._normals32[idx + 1] = 0.0;
  38709. this._normals32[idx + 2] = 0.0;
  38710. if (this._computeParticleColor) {
  38711. this._colors32[colidx] = this._particle.color.r;
  38712. this._colors32[colidx + 1] = this._particle.color.g;
  38713. this._colors32[colidx + 2] = this._particle.color.b;
  38714. this._colors32[colidx + 3] = this._particle.color.a;
  38715. }
  38716. if (this._computeParticleTexture) {
  38717. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38718. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38719. }
  38720. }
  38721. }
  38722. // if the particle intersections must be computed : update the bbInfo
  38723. if (this._particlesIntersect) {
  38724. var bInfo = this._particle._boundingInfo;
  38725. var bBox = bInfo.boundingBox;
  38726. var bSphere = bInfo.boundingSphere;
  38727. if (!this._bSphereOnly) {
  38728. // place, scale and rotate the particle bbox within the SPS local system, then update it
  38729. for (var b = 0; b < bBox.vectors.length; b++) {
  38730. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  38731. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  38732. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  38733. 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];
  38734. 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;
  38735. 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;
  38736. 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;
  38737. 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;
  38738. 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;
  38739. 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;
  38740. }
  38741. bBox._update(this.mesh._worldMatrix);
  38742. }
  38743. // place and scale the particle bouding sphere in the SPS local system, then update it
  38744. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  38745. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  38746. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  38747. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  38748. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  38749. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  38750. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  38751. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  38752. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  38753. 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));
  38754. bSphere._update(this.mesh._worldMatrix);
  38755. }
  38756. // increment indexes for the next particle
  38757. index = idx + 3;
  38758. colorIndex = colidx + 4;
  38759. uvIndex = uvidx + 2;
  38760. }
  38761. // if the VBO must be updated
  38762. if (update) {
  38763. if (this._computeParticleColor) {
  38764. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  38765. }
  38766. if (this._computeParticleTexture) {
  38767. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  38768. }
  38769. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38770. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  38771. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  38772. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  38773. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  38774. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  38775. for (var i = 0; i < this._normals32.length; i++) {
  38776. this._fixedNormal32[i] = this._normals32[i];
  38777. }
  38778. }
  38779. if (!this.mesh.areNormalsFrozen) {
  38780. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  38781. }
  38782. }
  38783. }
  38784. if (this._computeBoundingBox) {
  38785. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  38786. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  38787. }
  38788. this.afterUpdateParticles(start, end, update);
  38789. return this;
  38790. };
  38791. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  38792. this._halfroll = this._roll * 0.5;
  38793. this._halfpitch = this._pitch * 0.5;
  38794. this._halfyaw = this._yaw * 0.5;
  38795. this._sinRoll = Math.sin(this._halfroll);
  38796. this._cosRoll = Math.cos(this._halfroll);
  38797. this._sinPitch = Math.sin(this._halfpitch);
  38798. this._cosPitch = Math.cos(this._halfpitch);
  38799. this._sinYaw = Math.sin(this._halfyaw);
  38800. this._cosYaw = Math.cos(this._halfyaw);
  38801. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  38802. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  38803. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  38804. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  38805. };
  38806. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  38807. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  38808. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  38809. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  38810. this._rotMatrix.m[3] = 0;
  38811. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  38812. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  38813. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  38814. this._rotMatrix.m[7] = 0;
  38815. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  38816. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  38817. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  38818. this._rotMatrix.m[11] = 0;
  38819. this._rotMatrix.m[12] = 0;
  38820. this._rotMatrix.m[13] = 0;
  38821. this._rotMatrix.m[14] = 0;
  38822. this._rotMatrix.m[15] = 1.0;
  38823. };
  38824. /**
  38825. * Disposes the SPS.
  38826. * Returns nothing.
  38827. */
  38828. SolidParticleSystem.prototype.dispose = function () {
  38829. this.mesh.dispose();
  38830. this.vars = null;
  38831. // drop references to internal big arrays for the GC
  38832. this._positions = null;
  38833. this._indices = null;
  38834. this._normals = null;
  38835. this._uvs = null;
  38836. this._colors = null;
  38837. this._positions32 = null;
  38838. this._normals32 = null;
  38839. this._fixedNormal32 = null;
  38840. this._uvs32 = null;
  38841. this._colors32 = null;
  38842. this.pickedParticles = null;
  38843. };
  38844. /**
  38845. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  38846. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  38847. * Returns the SPS.
  38848. */
  38849. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  38850. if (!this._isVisibilityBoxLocked) {
  38851. this.mesh.refreshBoundingInfo();
  38852. }
  38853. return this;
  38854. };
  38855. /**
  38856. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  38857. * @param size the size (float) of the visibility box
  38858. * note : this doesn't lock the SPS mesh bounding box.
  38859. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  38860. */
  38861. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  38862. var vis = size / 2;
  38863. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  38864. };
  38865. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  38866. // getter and setter
  38867. get: function () {
  38868. return this._alwaysVisible;
  38869. },
  38870. /**
  38871. * Sets the SPS as always visible or not
  38872. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  38873. */
  38874. set: function (val) {
  38875. this._alwaysVisible = val;
  38876. this.mesh.alwaysSelectAsActiveMesh = val;
  38877. },
  38878. enumerable: true,
  38879. configurable: true
  38880. });
  38881. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  38882. get: function () {
  38883. return this._isVisibilityBoxLocked;
  38884. },
  38885. /**
  38886. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  38887. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  38888. */
  38889. set: function (val) {
  38890. this._isVisibilityBoxLocked = val;
  38891. this.mesh.getBoundingInfo().isLocked = val;
  38892. },
  38893. enumerable: true,
  38894. configurable: true
  38895. });
  38896. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  38897. // getters
  38898. get: function () {
  38899. return this._computeParticleRotation;
  38900. },
  38901. // Optimizer setters
  38902. /**
  38903. * Tells to `setParticles()` to compute the particle rotations or not.
  38904. * Default value : true. The SPS is faster when it's set to false.
  38905. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  38906. */
  38907. set: function (val) {
  38908. this._computeParticleRotation = val;
  38909. },
  38910. enumerable: true,
  38911. configurable: true
  38912. });
  38913. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  38914. get: function () {
  38915. return this._computeParticleColor;
  38916. },
  38917. /**
  38918. * Tells to `setParticles()` to compute the particle colors or not.
  38919. * Default value : true. The SPS is faster when it's set to false.
  38920. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  38921. */
  38922. set: function (val) {
  38923. this._computeParticleColor = val;
  38924. },
  38925. enumerable: true,
  38926. configurable: true
  38927. });
  38928. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  38929. get: function () {
  38930. return this._computeParticleTexture;
  38931. },
  38932. /**
  38933. * Tells to `setParticles()` to compute the particle textures or not.
  38934. * Default value : true. The SPS is faster when it's set to false.
  38935. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  38936. */
  38937. set: function (val) {
  38938. this._computeParticleTexture = val;
  38939. },
  38940. enumerable: true,
  38941. configurable: true
  38942. });
  38943. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  38944. get: function () {
  38945. return this._computeParticleVertex;
  38946. },
  38947. /**
  38948. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  38949. * Default value : false. The SPS is faster when it's set to false.
  38950. * Note : the particle custom vertex positions aren't stored values.
  38951. */
  38952. set: function (val) {
  38953. this._computeParticleVertex = val;
  38954. },
  38955. enumerable: true,
  38956. configurable: true
  38957. });
  38958. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  38959. get: function () {
  38960. return this._computeBoundingBox;
  38961. },
  38962. /**
  38963. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  38964. */
  38965. set: function (val) {
  38966. this._computeBoundingBox = val;
  38967. },
  38968. enumerable: true,
  38969. configurable: true
  38970. });
  38971. // =======================================================================
  38972. // Particle behavior logic
  38973. // these following methods may be overwritten by the user to fit his needs
  38974. /**
  38975. * This function does nothing. It may be overwritten to set all the particle first values.
  38976. * The SPS doesn't call this function, you may have to call it by your own.
  38977. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  38978. */
  38979. SolidParticleSystem.prototype.initParticles = function () {
  38980. };
  38981. /**
  38982. * This function does nothing. It may be overwritten to recycle a particle.
  38983. * The SPS doesn't call this function, you may have to call it by your own.
  38984. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  38985. */
  38986. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  38987. return particle;
  38988. };
  38989. /**
  38990. * Updates a particle : this function should be overwritten by the user.
  38991. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  38992. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  38993. * ex : just set a particle position or velocity and recycle conditions
  38994. */
  38995. SolidParticleSystem.prototype.updateParticle = function (particle) {
  38996. return particle;
  38997. };
  38998. /**
  38999. * Updates a vertex of a particle : it can be overwritten by the user.
  39000. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  39001. * @param particle the current particle
  39002. * @param vertex the current index of the current particle
  39003. * @param pt the index of the current vertex in the particle shape
  39004. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  39005. * ex : just set a vertex particle position
  39006. */
  39007. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  39008. return vertex;
  39009. };
  39010. /**
  39011. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  39012. * This does nothing and may be overwritten by the user.
  39013. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39014. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39015. * @param update the boolean update value actually passed to setParticles()
  39016. */
  39017. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  39018. };
  39019. /**
  39020. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  39021. * This will be passed three parameters.
  39022. * This does nothing and may be overwritten by the user.
  39023. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39024. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39025. * @param update the boolean update value actually passed to setParticles()
  39026. */
  39027. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  39028. };
  39029. return SolidParticleSystem;
  39030. }());
  39031. BABYLON.SolidParticleSystem = SolidParticleSystem;
  39032. })(BABYLON || (BABYLON = {}));
  39033. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  39034. /// <reference path="babylon.mesh.ts" />
  39035. var BABYLON;
  39036. (function (BABYLON) {
  39037. var GroundMesh = (function (_super) {
  39038. __extends(GroundMesh, _super);
  39039. function GroundMesh(name, scene) {
  39040. var _this = _super.call(this, name, scene) || this;
  39041. _this.generateOctree = false;
  39042. _this._worldInverse = new BABYLON.Matrix();
  39043. return _this;
  39044. }
  39045. GroundMesh.prototype.getClassName = function () {
  39046. return "GroundMesh";
  39047. };
  39048. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  39049. get: function () {
  39050. return Math.min(this._subdivisionsX, this._subdivisionsY);
  39051. },
  39052. enumerable: true,
  39053. configurable: true
  39054. });
  39055. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  39056. get: function () {
  39057. return this._subdivisionsX;
  39058. },
  39059. enumerable: true,
  39060. configurable: true
  39061. });
  39062. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  39063. get: function () {
  39064. return this._subdivisionsY;
  39065. },
  39066. enumerable: true,
  39067. configurable: true
  39068. });
  39069. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  39070. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  39071. this._subdivisionsX = chunksCount;
  39072. this._subdivisionsY = chunksCount;
  39073. this.subdivide(chunksCount);
  39074. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  39075. };
  39076. /**
  39077. * Returns a height (y) value in the Worl system :
  39078. * the ground altitude at the coordinates (x, z) expressed in the World system.
  39079. * Returns the ground y position if (x, z) are outside the ground surface.
  39080. */
  39081. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  39082. var world = this.getWorldMatrix();
  39083. var invMat = BABYLON.Tmp.Matrix[5];
  39084. world.invertToRef(invMat);
  39085. var tmpVect = BABYLON.Tmp.Vector3[8];
  39086. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  39087. x = tmpVect.x;
  39088. z = tmpVect.z;
  39089. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39090. return this.position.y;
  39091. }
  39092. if (!this._heightQuads || this._heightQuads.length == 0) {
  39093. this._initHeightQuads();
  39094. this._computeHeightQuads();
  39095. }
  39096. var facet = this._getFacetAt(x, z);
  39097. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  39098. // return y in the World system
  39099. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  39100. return tmpVect.y;
  39101. };
  39102. /**
  39103. * Returns a normalized vector (Vector3) orthogonal to the ground
  39104. * at the ground coordinates (x, z) expressed in the World system.
  39105. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  39106. */
  39107. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  39108. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  39109. this.getNormalAtCoordinatesToRef(x, z, normal);
  39110. return normal;
  39111. };
  39112. /**
  39113. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  39114. * at the ground coordinates (x, z) expressed in the World system.
  39115. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  39116. * Returns the GroundMesh.
  39117. */
  39118. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  39119. var world = this.getWorldMatrix();
  39120. var tmpMat = BABYLON.Tmp.Matrix[5];
  39121. world.invertToRef(tmpMat);
  39122. var tmpVect = BABYLON.Tmp.Vector3[8];
  39123. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  39124. x = tmpVect.x;
  39125. z = tmpVect.z;
  39126. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39127. return this;
  39128. }
  39129. if (!this._heightQuads || this._heightQuads.length == 0) {
  39130. this._initHeightQuads();
  39131. this._computeHeightQuads();
  39132. }
  39133. var facet = this._getFacetAt(x, z);
  39134. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  39135. return this;
  39136. };
  39137. /**
  39138. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  39139. * if the ground has been updated.
  39140. * This can be used in the render loop.
  39141. * Returns the GroundMesh.
  39142. */
  39143. GroundMesh.prototype.updateCoordinateHeights = function () {
  39144. if (!this._heightQuads || this._heightQuads.length == 0) {
  39145. this._initHeightQuads();
  39146. }
  39147. this._computeHeightQuads();
  39148. return this;
  39149. };
  39150. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  39151. GroundMesh.prototype._getFacetAt = function (x, z) {
  39152. // retrieve col and row from x, z coordinates in the ground local system
  39153. var subdivisionsX = this._subdivisionsX;
  39154. var subdivisionsY = this._subdivisionsY;
  39155. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  39156. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  39157. var quad = this._heightQuads[row * this._subdivisionsX + col];
  39158. var facet;
  39159. if (z < quad.slope.x * x + quad.slope.y) {
  39160. facet = quad.facet1;
  39161. }
  39162. else {
  39163. facet = quad.facet2;
  39164. }
  39165. return facet;
  39166. };
  39167. // Creates and populates the heightMap array with "facet" elements :
  39168. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  39169. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39170. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39171. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39172. // Returns the GroundMesh.
  39173. GroundMesh.prototype._initHeightQuads = function () {
  39174. var subdivisionsX = this._subdivisionsX;
  39175. var subdivisionsY = this._subdivisionsY;
  39176. this._heightQuads = new Array();
  39177. for (var row = 0; row < subdivisionsY; row++) {
  39178. for (var col = 0; col < subdivisionsX; col++) {
  39179. 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) };
  39180. this._heightQuads[row * subdivisionsX + col] = quad;
  39181. }
  39182. }
  39183. return this;
  39184. };
  39185. // Compute each quad element values and update the the heightMap array :
  39186. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39187. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39188. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39189. // Returns the GroundMesh.
  39190. GroundMesh.prototype._computeHeightQuads = function () {
  39191. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39192. var v1 = BABYLON.Tmp.Vector3[3];
  39193. var v2 = BABYLON.Tmp.Vector3[2];
  39194. var v3 = BABYLON.Tmp.Vector3[1];
  39195. var v4 = BABYLON.Tmp.Vector3[0];
  39196. var v1v2 = BABYLON.Tmp.Vector3[4];
  39197. var v1v3 = BABYLON.Tmp.Vector3[5];
  39198. var v1v4 = BABYLON.Tmp.Vector3[6];
  39199. var norm1 = BABYLON.Tmp.Vector3[7];
  39200. var norm2 = BABYLON.Tmp.Vector3[8];
  39201. var i = 0;
  39202. var j = 0;
  39203. var k = 0;
  39204. var cd = 0; // 2D slope coefficient : z = cd * x + h
  39205. var h = 0;
  39206. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  39207. var d2 = 0;
  39208. var subdivisionsX = this._subdivisionsX;
  39209. var subdivisionsY = this._subdivisionsY;
  39210. for (var row = 0; row < subdivisionsY; row++) {
  39211. for (var col = 0; col < subdivisionsX; col++) {
  39212. i = col * 3;
  39213. j = row * (subdivisionsX + 1) * 3;
  39214. k = (row + 1) * (subdivisionsX + 1) * 3;
  39215. v1.x = positions[j + i];
  39216. v1.y = positions[j + i + 1];
  39217. v1.z = positions[j + i + 2];
  39218. v2.x = positions[j + i + 3];
  39219. v2.y = positions[j + i + 4];
  39220. v2.z = positions[j + i + 5];
  39221. v3.x = positions[k + i];
  39222. v3.y = positions[k + i + 1];
  39223. v3.z = positions[k + i + 2];
  39224. v4.x = positions[k + i + 3];
  39225. v4.y = positions[k + i + 4];
  39226. v4.z = positions[k + i + 5];
  39227. // 2D slope V1V4
  39228. cd = (v4.z - v1.z) / (v4.x - v1.x);
  39229. h = v1.z - cd * v1.x; // v1 belongs to the slope
  39230. // facet equations :
  39231. // we compute each facet normal vector
  39232. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  39233. // we compute the value d by applying the equation to v1 which belongs to the plane
  39234. // then we store the facet equation in a Vector4
  39235. v2.subtractToRef(v1, v1v2);
  39236. v3.subtractToRef(v1, v1v3);
  39237. v4.subtractToRef(v1, v1v4);
  39238. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  39239. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  39240. norm1.normalize();
  39241. norm2.normalize();
  39242. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  39243. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  39244. var quad = this._heightQuads[row * subdivisionsX + col];
  39245. quad.slope.copyFromFloats(cd, h);
  39246. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  39247. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  39248. }
  39249. }
  39250. return this;
  39251. };
  39252. GroundMesh.prototype.serialize = function (serializationObject) {
  39253. _super.prototype.serialize.call(this, serializationObject);
  39254. serializationObject.subdivisionsX = this._subdivisionsX;
  39255. serializationObject.subdivisionsY = this._subdivisionsY;
  39256. serializationObject.minX = this._minX;
  39257. serializationObject.maxX = this._maxX;
  39258. serializationObject.minZ = this._minZ;
  39259. serializationObject.maxZ = this._maxZ;
  39260. serializationObject.width = this._width;
  39261. serializationObject.height = this._height;
  39262. };
  39263. GroundMesh.Parse = function (parsedMesh, scene) {
  39264. var result = new GroundMesh(parsedMesh.name, scene);
  39265. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  39266. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  39267. result._minX = parsedMesh.minX;
  39268. result._maxX = parsedMesh.maxX;
  39269. result._minZ = parsedMesh.minZ;
  39270. result._maxZ = parsedMesh.maxZ;
  39271. result._width = parsedMesh.width;
  39272. result._height = parsedMesh.height;
  39273. return result;
  39274. };
  39275. return GroundMesh;
  39276. }(BABYLON.Mesh));
  39277. BABYLON.GroundMesh = GroundMesh;
  39278. })(BABYLON || (BABYLON = {}));
  39279. //# sourceMappingURL=babylon.groundMesh.js.map
  39280. var BABYLON;
  39281. (function (BABYLON) {
  39282. /**
  39283. * Creates an instance based on a source mesh.
  39284. */
  39285. var InstancedMesh = (function (_super) {
  39286. __extends(InstancedMesh, _super);
  39287. function InstancedMesh(name, source) {
  39288. var _this = _super.call(this, name, source.getScene()) || this;
  39289. source.instances.push(_this);
  39290. _this._sourceMesh = source;
  39291. _this.position.copyFrom(source.position);
  39292. _this.rotation.copyFrom(source.rotation);
  39293. _this.scaling.copyFrom(source.scaling);
  39294. if (source.rotationQuaternion) {
  39295. _this.rotationQuaternion = source.rotationQuaternion.clone();
  39296. }
  39297. _this.infiniteDistance = source.infiniteDistance;
  39298. _this.setPivotMatrix(source.getPivotMatrix());
  39299. _this.refreshBoundingInfo();
  39300. _this._syncSubMeshes();
  39301. return _this;
  39302. }
  39303. /**
  39304. * Returns the string "InstancedMesh".
  39305. */
  39306. InstancedMesh.prototype.getClassName = function () {
  39307. return "InstancedMesh";
  39308. };
  39309. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  39310. // Methods
  39311. get: function () {
  39312. return this._sourceMesh.receiveShadows;
  39313. },
  39314. enumerable: true,
  39315. configurable: true
  39316. });
  39317. Object.defineProperty(InstancedMesh.prototype, "material", {
  39318. get: function () {
  39319. return this._sourceMesh.material;
  39320. },
  39321. enumerable: true,
  39322. configurable: true
  39323. });
  39324. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  39325. get: function () {
  39326. return this._sourceMesh.visibility;
  39327. },
  39328. enumerable: true,
  39329. configurable: true
  39330. });
  39331. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  39332. get: function () {
  39333. return this._sourceMesh.skeleton;
  39334. },
  39335. enumerable: true,
  39336. configurable: true
  39337. });
  39338. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  39339. get: function () {
  39340. return this._sourceMesh.renderingGroupId;
  39341. },
  39342. enumerable: true,
  39343. configurable: true
  39344. });
  39345. /**
  39346. * Returns the total number of vertices (integer).
  39347. */
  39348. InstancedMesh.prototype.getTotalVertices = function () {
  39349. return this._sourceMesh.getTotalVertices();
  39350. };
  39351. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  39352. get: function () {
  39353. return this._sourceMesh;
  39354. },
  39355. enumerable: true,
  39356. configurable: true
  39357. });
  39358. /**
  39359. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  39360. */
  39361. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  39362. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  39363. };
  39364. /**
  39365. * Sets the vertex data of the mesh geometry for the requested `kind`.
  39366. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  39367. * The `data` are either a numeric array either a Float32Array.
  39368. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  39369. * 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).
  39370. * Note that a new underlying VertexBuffer object is created each call.
  39371. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  39372. *
  39373. * Possible `kind` values :
  39374. * - BABYLON.VertexBuffer.PositionKind
  39375. * - BABYLON.VertexBuffer.UVKind
  39376. * - BABYLON.VertexBuffer.UV2Kind
  39377. * - BABYLON.VertexBuffer.UV3Kind
  39378. * - BABYLON.VertexBuffer.UV4Kind
  39379. * - BABYLON.VertexBuffer.UV5Kind
  39380. * - BABYLON.VertexBuffer.UV6Kind
  39381. * - BABYLON.VertexBuffer.ColorKind
  39382. * - BABYLON.VertexBuffer.MatricesIndicesKind
  39383. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  39384. * - BABYLON.VertexBuffer.MatricesWeightsKind
  39385. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  39386. *
  39387. * Returns the Mesh.
  39388. */
  39389. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39390. if (this.sourceMesh) {
  39391. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  39392. }
  39393. return this.sourceMesh;
  39394. };
  39395. /**
  39396. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  39397. * If the mesh has no geometry, it is simply returned as it is.
  39398. * The `data` are either a numeric array either a Float32Array.
  39399. * No new underlying VertexBuffer object is created.
  39400. * 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.
  39401. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  39402. *
  39403. * Possible `kind` values :
  39404. * - BABYLON.VertexBuffer.PositionKind
  39405. * - BABYLON.VertexBuffer.UVKind
  39406. * - BABYLON.VertexBuffer.UV2Kind
  39407. * - BABYLON.VertexBuffer.UV3Kind
  39408. * - BABYLON.VertexBuffer.UV4Kind
  39409. * - BABYLON.VertexBuffer.UV5Kind
  39410. * - BABYLON.VertexBuffer.UV6Kind
  39411. * - BABYLON.VertexBuffer.ColorKind
  39412. * - BABYLON.VertexBuffer.MatricesIndicesKind
  39413. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  39414. * - BABYLON.VertexBuffer.MatricesWeightsKind
  39415. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  39416. *
  39417. * Returns the Mesh.
  39418. */
  39419. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  39420. if (this.sourceMesh) {
  39421. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  39422. }
  39423. return this.sourceMesh;
  39424. };
  39425. /**
  39426. * Sets the mesh indices.
  39427. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  39428. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  39429. * This method creates a new index buffer each call.
  39430. * Returns the Mesh.
  39431. */
  39432. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  39433. if (this.sourceMesh) {
  39434. this.sourceMesh.setIndices(indices, totalVertices);
  39435. }
  39436. return this.sourceMesh;
  39437. };
  39438. /**
  39439. * Boolean : True if the mesh owns the requested kind of data.
  39440. */
  39441. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  39442. return this._sourceMesh.isVerticesDataPresent(kind);
  39443. };
  39444. /**
  39445. * Returns an array of indices (IndicesArray).
  39446. */
  39447. InstancedMesh.prototype.getIndices = function () {
  39448. return this._sourceMesh.getIndices();
  39449. };
  39450. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  39451. get: function () {
  39452. return this._sourceMesh._positions;
  39453. },
  39454. enumerable: true,
  39455. configurable: true
  39456. });
  39457. /**
  39458. * Sets a new updated BoundingInfo to the mesh.
  39459. * Returns the mesh.
  39460. */
  39461. InstancedMesh.prototype.refreshBoundingInfo = function () {
  39462. var meshBB = this._sourceMesh.getBoundingInfo();
  39463. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  39464. this._updateBoundingInfo();
  39465. return this;
  39466. };
  39467. InstancedMesh.prototype._preActivate = function () {
  39468. if (this._currentLOD) {
  39469. this._currentLOD._preActivate();
  39470. }
  39471. return this;
  39472. };
  39473. InstancedMesh.prototype._activate = function (renderId) {
  39474. if (this._currentLOD) {
  39475. this._currentLOD._registerInstanceForRenderId(this, renderId);
  39476. }
  39477. return this;
  39478. };
  39479. /**
  39480. * Returns the current associated LOD AbstractMesh.
  39481. */
  39482. InstancedMesh.prototype.getLOD = function (camera) {
  39483. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  39484. if (this._currentLOD === this.sourceMesh) {
  39485. return this;
  39486. }
  39487. return this._currentLOD;
  39488. };
  39489. InstancedMesh.prototype._syncSubMeshes = function () {
  39490. this.releaseSubMeshes();
  39491. if (this._sourceMesh.subMeshes) {
  39492. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  39493. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  39494. }
  39495. }
  39496. return this;
  39497. };
  39498. InstancedMesh.prototype._generatePointsArray = function () {
  39499. return this._sourceMesh._generatePointsArray();
  39500. };
  39501. /**
  39502. * Creates a new InstancedMesh from the current mesh.
  39503. * - name (string) : the cloned mesh name
  39504. * - newParent (optional Node) : the optional Node to parent the clone to.
  39505. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  39506. *
  39507. * Returns the clone.
  39508. */
  39509. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  39510. var result = this._sourceMesh.createInstance(name);
  39511. // Deep copy
  39512. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  39513. // Bounding info
  39514. this.refreshBoundingInfo();
  39515. // Parent
  39516. if (newParent) {
  39517. result.parent = newParent;
  39518. }
  39519. if (!doNotCloneChildren) {
  39520. // Children
  39521. for (var index = 0; index < this.getScene().meshes.length; index++) {
  39522. var mesh = this.getScene().meshes[index];
  39523. if (mesh.parent === this) {
  39524. mesh.clone(mesh.name, result);
  39525. }
  39526. }
  39527. }
  39528. result.computeWorldMatrix(true);
  39529. return result;
  39530. };
  39531. /**
  39532. * Disposes the InstancedMesh.
  39533. * Returns nothing.
  39534. */
  39535. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  39536. // Remove from mesh
  39537. var index = this._sourceMesh.instances.indexOf(this);
  39538. this._sourceMesh.instances.splice(index, 1);
  39539. _super.prototype.dispose.call(this, doNotRecurse);
  39540. };
  39541. return InstancedMesh;
  39542. }(BABYLON.AbstractMesh));
  39543. BABYLON.InstancedMesh = InstancedMesh;
  39544. })(BABYLON || (BABYLON = {}));
  39545. //# sourceMappingURL=babylon.instancedMesh.js.map
  39546. /// <reference path="babylon.mesh.ts" />
  39547. var BABYLON;
  39548. (function (BABYLON) {
  39549. var LinesMesh = (function (_super) {
  39550. __extends(LinesMesh, _super);
  39551. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  39552. if (parent === void 0) { parent = null; }
  39553. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  39554. _this.useVertexColor = useVertexColor;
  39555. _this.color = new BABYLON.Color3(1, 1, 1);
  39556. _this.alpha = 1;
  39557. if (source) {
  39558. _this.color = source.color.clone();
  39559. _this.alpha = source.alpha;
  39560. _this.useVertexColor = source.useVertexColor;
  39561. }
  39562. _this._intersectionThreshold = 0.1;
  39563. var options = {
  39564. attributes: [BABYLON.VertexBuffer.PositionKind],
  39565. uniforms: ["world", "viewProjection"],
  39566. needAlphaBlending: false,
  39567. };
  39568. if (!useVertexColor) {
  39569. options.uniforms.push("color");
  39570. options.needAlphaBlending = true;
  39571. }
  39572. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  39573. return _this;
  39574. }
  39575. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  39576. /**
  39577. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  39578. * This margin is expressed in world space coordinates, so its value may vary.
  39579. * Default value is 0.1
  39580. * @returns the intersection Threshold value.
  39581. */
  39582. get: function () {
  39583. return this._intersectionThreshold;
  39584. },
  39585. /**
  39586. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  39587. * This margin is expressed in world space coordinates, so its value may vary.
  39588. * @param value the new threshold to apply
  39589. */
  39590. set: function (value) {
  39591. if (this._intersectionThreshold === value) {
  39592. return;
  39593. }
  39594. this._intersectionThreshold = value;
  39595. if (this.geometry) {
  39596. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  39597. }
  39598. },
  39599. enumerable: true,
  39600. configurable: true
  39601. });
  39602. /**
  39603. * Returns the string "LineMesh"
  39604. */
  39605. LinesMesh.prototype.getClassName = function () {
  39606. return "LinesMesh";
  39607. };
  39608. Object.defineProperty(LinesMesh.prototype, "material", {
  39609. get: function () {
  39610. return this._colorShader;
  39611. },
  39612. enumerable: true,
  39613. configurable: true
  39614. });
  39615. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  39616. get: function () {
  39617. return false;
  39618. },
  39619. enumerable: true,
  39620. configurable: true
  39621. });
  39622. LinesMesh.prototype.createInstance = function (name) {
  39623. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  39624. return null;
  39625. };
  39626. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  39627. // VBOs
  39628. this._geometry._bind(this._colorShader.getEffect());
  39629. // Color
  39630. if (!this.useVertexColor) {
  39631. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  39632. }
  39633. return this;
  39634. };
  39635. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  39636. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  39637. return this;
  39638. }
  39639. var engine = this.getScene().getEngine();
  39640. // Draw order
  39641. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  39642. return this;
  39643. };
  39644. LinesMesh.prototype.dispose = function (doNotRecurse) {
  39645. this._colorShader.dispose();
  39646. _super.prototype.dispose.call(this, doNotRecurse);
  39647. };
  39648. /**
  39649. * Returns a new LineMesh object cloned from the current one.
  39650. */
  39651. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  39652. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  39653. };
  39654. return LinesMesh;
  39655. }(BABYLON.Mesh));
  39656. BABYLON.LinesMesh = LinesMesh;
  39657. })(BABYLON || (BABYLON = {}));
  39658. //# sourceMappingURL=babylon.linesMesh.js.map
  39659. var BABYLON;
  39660. (function (BABYLON) {
  39661. var ShaderMaterial = (function (_super) {
  39662. __extends(ShaderMaterial, _super);
  39663. function ShaderMaterial(name, scene, shaderPath, options) {
  39664. var _this = _super.call(this, name, scene) || this;
  39665. _this._textures = {};
  39666. _this._textureArrays = {};
  39667. _this._floats = {};
  39668. _this._floatsArrays = {};
  39669. _this._colors3 = {};
  39670. _this._colors4 = {};
  39671. _this._vectors2 = {};
  39672. _this._vectors3 = {};
  39673. _this._vectors4 = {};
  39674. _this._matrices = {};
  39675. _this._matrices3x3 = {};
  39676. _this._matrices2x2 = {};
  39677. _this._vectors3Arrays = {};
  39678. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39679. _this._shaderPath = shaderPath;
  39680. options.needAlphaBlending = options.needAlphaBlending || false;
  39681. options.needAlphaTesting = options.needAlphaTesting || false;
  39682. options.attributes = options.attributes || ["position", "normal", "uv"];
  39683. options.uniforms = options.uniforms || ["worldViewProjection"];
  39684. options.uniformBuffers = options.uniformBuffers || [];
  39685. options.samplers = options.samplers || [];
  39686. options.defines = options.defines || [];
  39687. _this._options = options;
  39688. return _this;
  39689. }
  39690. ShaderMaterial.prototype.getClassName = function () {
  39691. return "ShaderMaterial";
  39692. };
  39693. ShaderMaterial.prototype.needAlphaBlending = function () {
  39694. return this._options.needAlphaBlending;
  39695. };
  39696. ShaderMaterial.prototype.needAlphaTesting = function () {
  39697. return this._options.needAlphaTesting;
  39698. };
  39699. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39700. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39701. this._options.uniforms.push(uniformName);
  39702. }
  39703. };
  39704. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39705. if (this._options.samplers.indexOf(name) === -1) {
  39706. this._options.samplers.push(name);
  39707. }
  39708. this._textures[name] = texture;
  39709. return this;
  39710. };
  39711. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  39712. if (this._options.samplers.indexOf(name) === -1) {
  39713. this._options.samplers.push(name);
  39714. }
  39715. this._checkUniform(name);
  39716. this._textureArrays[name] = textures;
  39717. return this;
  39718. };
  39719. ShaderMaterial.prototype.setFloat = function (name, value) {
  39720. this._checkUniform(name);
  39721. this._floats[name] = value;
  39722. return this;
  39723. };
  39724. ShaderMaterial.prototype.setFloats = function (name, value) {
  39725. this._checkUniform(name);
  39726. this._floatsArrays[name] = value;
  39727. return this;
  39728. };
  39729. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39730. this._checkUniform(name);
  39731. this._colors3[name] = value;
  39732. return this;
  39733. };
  39734. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39735. this._checkUniform(name);
  39736. this._colors4[name] = value;
  39737. return this;
  39738. };
  39739. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39740. this._checkUniform(name);
  39741. this._vectors2[name] = value;
  39742. return this;
  39743. };
  39744. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39745. this._checkUniform(name);
  39746. this._vectors3[name] = value;
  39747. return this;
  39748. };
  39749. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39750. this._checkUniform(name);
  39751. this._vectors4[name] = value;
  39752. return this;
  39753. };
  39754. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39755. this._checkUniform(name);
  39756. this._matrices[name] = value;
  39757. return this;
  39758. };
  39759. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39760. this._checkUniform(name);
  39761. this._matrices3x3[name] = value;
  39762. return this;
  39763. };
  39764. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39765. this._checkUniform(name);
  39766. this._matrices2x2[name] = value;
  39767. return this;
  39768. };
  39769. ShaderMaterial.prototype.setArray3 = function (name, value) {
  39770. this._checkUniform(name);
  39771. this._vectors3Arrays[name] = value;
  39772. return this;
  39773. };
  39774. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  39775. if (!mesh) {
  39776. return true;
  39777. }
  39778. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  39779. return false;
  39780. }
  39781. return false;
  39782. };
  39783. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39784. var scene = this.getScene();
  39785. var engine = scene.getEngine();
  39786. if (!this.checkReadyOnEveryCall) {
  39787. if (this._renderId === scene.getRenderId()) {
  39788. if (this._checkCache(scene, mesh, useInstances)) {
  39789. return true;
  39790. }
  39791. }
  39792. }
  39793. // Instances
  39794. var defines = [];
  39795. var attribs = [];
  39796. var fallbacks = new BABYLON.EffectFallbacks();
  39797. if (useInstances) {
  39798. defines.push("#define INSTANCES");
  39799. }
  39800. for (var index = 0; index < this._options.defines.length; index++) {
  39801. defines.push(this._options.defines[index]);
  39802. }
  39803. for (var index = 0; index < this._options.attributes.length; index++) {
  39804. attribs.push(this._options.attributes[index]);
  39805. }
  39806. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39807. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39808. defines.push("#define VERTEXCOLOR");
  39809. }
  39810. // Bones
  39811. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39812. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39813. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39814. if (mesh.numBoneInfluencers > 4) {
  39815. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39816. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39817. }
  39818. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39819. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39820. fallbacks.addCPUSkinningFallback(0, mesh);
  39821. }
  39822. else {
  39823. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39824. }
  39825. // Textures
  39826. for (var name in this._textures) {
  39827. if (!this._textures[name].isReady()) {
  39828. return false;
  39829. }
  39830. }
  39831. // Alpha test
  39832. if (engine.getAlphaTesting()) {
  39833. defines.push("#define ALPHATEST");
  39834. }
  39835. var previousEffect = this._effect;
  39836. var join = defines.join("\n");
  39837. this._effect = engine.createEffect(this._shaderPath, {
  39838. attributes: attribs,
  39839. uniformsNames: this._options.uniforms,
  39840. uniformBuffersNames: this._options.uniformBuffers,
  39841. samplers: this._options.samplers,
  39842. defines: join,
  39843. fallbacks: fallbacks,
  39844. onCompiled: this.onCompiled,
  39845. onError: this.onError
  39846. }, engine);
  39847. if (!this._effect.isReady()) {
  39848. return false;
  39849. }
  39850. if (previousEffect !== this._effect) {
  39851. scene.resetCachedMaterial();
  39852. }
  39853. this._renderId = scene.getRenderId();
  39854. return true;
  39855. };
  39856. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39857. var scene = this.getScene();
  39858. if (this._options.uniforms.indexOf("world") !== -1) {
  39859. this._effect.setMatrix("world", world);
  39860. }
  39861. if (this._options.uniforms.indexOf("worldView") !== -1) {
  39862. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  39863. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  39864. }
  39865. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  39866. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  39867. }
  39868. };
  39869. ShaderMaterial.prototype.bind = function (world, mesh) {
  39870. // Std values
  39871. this.bindOnlyWorldMatrix(world);
  39872. if (this.getScene().getCachedMaterial() !== this) {
  39873. if (this._options.uniforms.indexOf("view") !== -1) {
  39874. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39875. }
  39876. if (this._options.uniforms.indexOf("projection") !== -1) {
  39877. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39878. }
  39879. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39880. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39881. }
  39882. // Bones
  39883. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39884. var name;
  39885. // Texture
  39886. for (name in this._textures) {
  39887. this._effect.setTexture(name, this._textures[name]);
  39888. }
  39889. // Texture arrays
  39890. for (name in this._textureArrays) {
  39891. this._effect.setTextureArray(name, this._textureArrays[name]);
  39892. }
  39893. // Float
  39894. for (name in this._floats) {
  39895. this._effect.setFloat(name, this._floats[name]);
  39896. }
  39897. // Float s
  39898. for (name in this._floatsArrays) {
  39899. this._effect.setArray(name, this._floatsArrays[name]);
  39900. }
  39901. // Color3
  39902. for (name in this._colors3) {
  39903. this._effect.setColor3(name, this._colors3[name]);
  39904. }
  39905. // Color4
  39906. for (name in this._colors4) {
  39907. var color = this._colors4[name];
  39908. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  39909. }
  39910. // Vector2
  39911. for (name in this._vectors2) {
  39912. this._effect.setVector2(name, this._vectors2[name]);
  39913. }
  39914. // Vector3
  39915. for (name in this._vectors3) {
  39916. this._effect.setVector3(name, this._vectors3[name]);
  39917. }
  39918. // Vector4
  39919. for (name in this._vectors4) {
  39920. this._effect.setVector4(name, this._vectors4[name]);
  39921. }
  39922. // Matrix
  39923. for (name in this._matrices) {
  39924. this._effect.setMatrix(name, this._matrices[name]);
  39925. }
  39926. // Matrix 3x3
  39927. for (name in this._matrices3x3) {
  39928. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  39929. }
  39930. // Matrix 2x2
  39931. for (name in this._matrices2x2) {
  39932. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  39933. }
  39934. // Vector3Array
  39935. for (name in this._vectors3Arrays) {
  39936. this._effect.setArray3(name, this._vectors3Arrays[name]);
  39937. }
  39938. }
  39939. this._afterBind(mesh);
  39940. };
  39941. ShaderMaterial.prototype.clone = function (name) {
  39942. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  39943. return newShaderMaterial;
  39944. };
  39945. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39946. if (forceDisposeTextures) {
  39947. var name;
  39948. for (name in this._textures) {
  39949. this._textures[name].dispose();
  39950. }
  39951. for (name in this._textureArrays) {
  39952. var array = this._textureArrays[name];
  39953. for (var index = 0; index < array.length; index++) {
  39954. array[index].dispose();
  39955. }
  39956. }
  39957. }
  39958. this._textures = {};
  39959. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39960. };
  39961. ShaderMaterial.prototype.serialize = function () {
  39962. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39963. serializationObject.customType = "BABYLON.ShaderMaterial";
  39964. serializationObject.options = this._options;
  39965. serializationObject.shaderPath = this._shaderPath;
  39966. var name;
  39967. // Texture
  39968. serializationObject.textures = {};
  39969. for (name in this._textures) {
  39970. serializationObject.textures[name] = this._textures[name].serialize();
  39971. }
  39972. // Texture arrays
  39973. serializationObject.textureArrays = {};
  39974. for (name in this._textureArrays) {
  39975. serializationObject.textureArrays[name] = [];
  39976. var array = this._textureArrays[name];
  39977. for (var index = 0; index < array.length; index++) {
  39978. serializationObject.textureArrays[name].push(array[index].serialize());
  39979. }
  39980. }
  39981. // Float
  39982. serializationObject.floats = {};
  39983. for (name in this._floats) {
  39984. serializationObject.floats[name] = this._floats[name];
  39985. }
  39986. // Float s
  39987. serializationObject.floatArrays = {};
  39988. for (name in this._floatsArrays) {
  39989. serializationObject.floatArrays[name] = this._floatsArrays[name];
  39990. }
  39991. // Color3
  39992. serializationObject.colors3 = {};
  39993. for (name in this._colors3) {
  39994. serializationObject.colors3[name] = this._colors3[name].asArray();
  39995. }
  39996. // Color4
  39997. serializationObject.colors4 = {};
  39998. for (name in this._colors4) {
  39999. serializationObject.colors4[name] = this._colors4[name].asArray();
  40000. }
  40001. // Vector2
  40002. serializationObject.vectors2 = {};
  40003. for (name in this._vectors2) {
  40004. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40005. }
  40006. // Vector3
  40007. serializationObject.vectors3 = {};
  40008. for (name in this._vectors3) {
  40009. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40010. }
  40011. // Vector4
  40012. serializationObject.vectors4 = {};
  40013. for (name in this._vectors4) {
  40014. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40015. }
  40016. // Matrix
  40017. serializationObject.matrices = {};
  40018. for (name in this._matrices) {
  40019. serializationObject.matrices[name] = this._matrices[name].asArray();
  40020. }
  40021. // Matrix 3x3
  40022. serializationObject.matrices3x3 = {};
  40023. for (name in this._matrices3x3) {
  40024. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40025. }
  40026. // Matrix 2x2
  40027. serializationObject.matrices2x2 = {};
  40028. for (name in this._matrices2x2) {
  40029. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40030. }
  40031. // Vector3Array
  40032. serializationObject.vectors3Arrays = {};
  40033. for (name in this._vectors3Arrays) {
  40034. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40035. }
  40036. return serializationObject;
  40037. };
  40038. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40039. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40040. var name;
  40041. // Texture
  40042. for (name in source.textures) {
  40043. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40044. }
  40045. // Texture arrays
  40046. for (name in source.textureArrays) {
  40047. var array = source.textureArrays[name];
  40048. var textureArray = new Array();
  40049. for (var index = 0; index < array.length; index++) {
  40050. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40051. }
  40052. material.setTextureArray(name, textureArray);
  40053. }
  40054. // Float
  40055. for (name in source.floats) {
  40056. material.setFloat(name, source.floats[name]);
  40057. }
  40058. // Float s
  40059. for (name in source.floatsArrays) {
  40060. material.setFloats(name, source.floatsArrays[name]);
  40061. }
  40062. // Color3
  40063. for (name in source.colors3) {
  40064. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40065. }
  40066. // Color4
  40067. for (name in source.colors4) {
  40068. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40069. }
  40070. // Vector2
  40071. for (name in source.vectors2) {
  40072. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40073. }
  40074. // Vector3
  40075. for (name in source.vectors3) {
  40076. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40077. }
  40078. // Vector4
  40079. for (name in source.vectors4) {
  40080. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40081. }
  40082. // Matrix
  40083. for (name in source.matrices) {
  40084. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40085. }
  40086. // Matrix 3x3
  40087. for (name in source.matrices3x3) {
  40088. material.setMatrix3x3(name, source.matrices3x3[name]);
  40089. }
  40090. // Matrix 2x2
  40091. for (name in source.matrices2x2) {
  40092. material.setMatrix2x2(name, source.matrices2x2[name]);
  40093. }
  40094. // Vector3Array
  40095. for (name in source.vectors3Arrays) {
  40096. material.setArray3(name, source.vectors3Arrays[name]);
  40097. }
  40098. return material;
  40099. };
  40100. return ShaderMaterial;
  40101. }(BABYLON.Material));
  40102. BABYLON.ShaderMaterial = ShaderMaterial;
  40103. })(BABYLON || (BABYLON = {}));
  40104. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40105. var BABYLON;
  40106. (function (BABYLON) {
  40107. var MeshBuilder = (function () {
  40108. function MeshBuilder() {
  40109. }
  40110. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  40111. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  40112. return BABYLON.Mesh.DOUBLESIDE;
  40113. }
  40114. if (orientation === undefined || orientation === null) {
  40115. return BABYLON.Mesh.FRONTSIDE;
  40116. }
  40117. return orientation;
  40118. };
  40119. /**
  40120. * Creates a box mesh.
  40121. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  40122. * The parameter `size` sets the size (float) of each box side (default 1).
  40123. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  40124. * 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).
  40125. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40126. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40127. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40128. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40129. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40130. */
  40131. MeshBuilder.CreateBox = function (name, options, scene) {
  40132. var box = new BABYLON.Mesh(name, scene);
  40133. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40134. box.sideOrientation = options.sideOrientation;
  40135. var vertexData = BABYLON.VertexData.CreateBox(options);
  40136. vertexData.applyToMesh(box, options.updatable);
  40137. return box;
  40138. };
  40139. /**
  40140. * Creates a sphere mesh.
  40141. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  40142. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  40143. * 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`).
  40144. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  40145. * 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
  40146. * 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).
  40147. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40148. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40149. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40150. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40151. */
  40152. MeshBuilder.CreateSphere = function (name, options, scene) {
  40153. var sphere = new BABYLON.Mesh(name, scene);
  40154. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40155. sphere.sideOrientation = options.sideOrientation;
  40156. var vertexData = BABYLON.VertexData.CreateSphere(options);
  40157. vertexData.applyToMesh(sphere, options.updatable);
  40158. return sphere;
  40159. };
  40160. /**
  40161. * Creates a plane polygonal mesh. By default, this is a disc.
  40162. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  40163. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  40164. * 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.
  40165. * 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
  40166. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40167. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40168. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40169. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40170. */
  40171. MeshBuilder.CreateDisc = function (name, options, scene) {
  40172. var disc = new BABYLON.Mesh(name, scene);
  40173. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40174. disc.sideOrientation = options.sideOrientation;
  40175. var vertexData = BABYLON.VertexData.CreateDisc(options);
  40176. vertexData.applyToMesh(disc, options.updatable);
  40177. return disc;
  40178. };
  40179. /**
  40180. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  40181. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  40182. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  40183. * 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`).
  40184. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  40185. * 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.
  40186. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40187. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40188. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40189. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40190. */
  40191. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  40192. var sphere = new BABYLON.Mesh(name, scene);
  40193. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40194. sphere.sideOrientation = options.sideOrientation;
  40195. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  40196. vertexData.applyToMesh(sphere, options.updatable);
  40197. return sphere;
  40198. };
  40199. ;
  40200. /**
  40201. * Creates a ribbon mesh.
  40202. * 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.
  40203. *
  40204. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  40205. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  40206. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  40207. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  40208. * 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.
  40209. * 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.
  40210. * 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
  40211. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40212. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40213. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40214. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40215. * 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.
  40216. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  40217. * 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
  40218. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  40219. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  40220. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40221. */
  40222. MeshBuilder.CreateRibbon = function (name, options, scene) {
  40223. var pathArray = options.pathArray;
  40224. var closeArray = options.closeArray;
  40225. var closePath = options.closePath;
  40226. var offset = options.offset;
  40227. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40228. var instance = options.instance;
  40229. var updatable = options.updatable;
  40230. if (instance) {
  40231. // positionFunction : ribbon case
  40232. // only pathArray and sideOrientation parameters are taken into account for positions update
  40233. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  40234. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  40235. var positionFunction = function (positions) {
  40236. var minlg = pathArray[0].length;
  40237. var i = 0;
  40238. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  40239. for (var si = 1; si <= ns; si++) {
  40240. for (var p = 0; p < pathArray.length; p++) {
  40241. var path = pathArray[p];
  40242. var l = path.length;
  40243. minlg = (minlg < l) ? minlg : l;
  40244. var j = 0;
  40245. while (j < minlg) {
  40246. positions[i] = path[j].x;
  40247. positions[i + 1] = path[j].y;
  40248. positions[i + 2] = path[j].z;
  40249. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  40250. BABYLON.Tmp.Vector3[0].x = path[j].x;
  40251. }
  40252. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  40253. BABYLON.Tmp.Vector3[1].x = path[j].x;
  40254. }
  40255. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  40256. BABYLON.Tmp.Vector3[0].y = path[j].y;
  40257. }
  40258. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  40259. BABYLON.Tmp.Vector3[1].y = path[j].y;
  40260. }
  40261. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  40262. BABYLON.Tmp.Vector3[0].z = path[j].z;
  40263. }
  40264. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  40265. BABYLON.Tmp.Vector3[1].z = path[j].z;
  40266. }
  40267. j++;
  40268. i += 3;
  40269. }
  40270. if (instance._closePath) {
  40271. positions[i] = path[0].x;
  40272. positions[i + 1] = path[0].y;
  40273. positions[i + 2] = path[0].z;
  40274. i += 3;
  40275. }
  40276. }
  40277. }
  40278. };
  40279. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40280. positionFunction(positions);
  40281. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  40282. instance._boundingInfo.update(instance._worldMatrix);
  40283. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  40284. if (options.colors) {
  40285. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40286. for (var c = 0; c < options.colors.length; c++) {
  40287. colors[c * 4] = options.colors[c].r;
  40288. colors[c * 4 + 1] = options.colors[c].g;
  40289. colors[c * 4 + 2] = options.colors[c].b;
  40290. colors[c * 4 + 3] = options.colors[c].a;
  40291. }
  40292. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  40293. }
  40294. if (options.uvs) {
  40295. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40296. for (var i = 0; i < options.uvs.length; i++) {
  40297. uvs[i * 2] = options.uvs[i].x;
  40298. uvs[i * 2 + 1] = options.uvs[i].y;
  40299. }
  40300. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  40301. }
  40302. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  40303. var indices = instance.getIndices();
  40304. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40305. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  40306. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  40307. if (instance._closePath) {
  40308. var indexFirst = 0;
  40309. var indexLast = 0;
  40310. for (var p = 0; p < pathArray.length; p++) {
  40311. indexFirst = instance._idx[p] * 3;
  40312. if (p + 1 < pathArray.length) {
  40313. indexLast = (instance._idx[p + 1] - 1) * 3;
  40314. }
  40315. else {
  40316. indexLast = normals.length - 3;
  40317. }
  40318. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  40319. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  40320. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  40321. normals[indexLast] = normals[indexFirst];
  40322. normals[indexLast + 1] = normals[indexFirst + 1];
  40323. normals[indexLast + 2] = normals[indexFirst + 2];
  40324. }
  40325. }
  40326. if (!(instance.areNormalsFrozen)) {
  40327. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  40328. }
  40329. }
  40330. return instance;
  40331. }
  40332. else {
  40333. var ribbon = new BABYLON.Mesh(name, scene);
  40334. ribbon.sideOrientation = sideOrientation;
  40335. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  40336. if (closePath) {
  40337. ribbon._idx = vertexData._idx;
  40338. }
  40339. ribbon._closePath = closePath;
  40340. ribbon._closeArray = closeArray;
  40341. vertexData.applyToMesh(ribbon, updatable);
  40342. return ribbon;
  40343. }
  40344. };
  40345. /**
  40346. * Creates a cylinder or a cone mesh.
  40347. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  40348. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  40349. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  40350. * 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.
  40351. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  40352. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  40353. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  40354. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  40355. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  40356. * 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).
  40357. * 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
  40358. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  40359. * 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
  40360. * 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.
  40361. * If `enclose` is false, a ring surface is one element.
  40362. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  40363. * 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
  40364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40365. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40366. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40368. */
  40369. MeshBuilder.CreateCylinder = function (name, options, scene) {
  40370. var cylinder = new BABYLON.Mesh(name, scene);
  40371. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40372. cylinder.sideOrientation = options.sideOrientation;
  40373. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  40374. vertexData.applyToMesh(cylinder, options.updatable);
  40375. return cylinder;
  40376. };
  40377. /**
  40378. * Creates a torus mesh.
  40379. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  40380. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  40381. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  40382. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  40383. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40384. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40385. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40386. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40387. */
  40388. MeshBuilder.CreateTorus = function (name, options, scene) {
  40389. var torus = new BABYLON.Mesh(name, scene);
  40390. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40391. torus.sideOrientation = options.sideOrientation;
  40392. var vertexData = BABYLON.VertexData.CreateTorus(options);
  40393. vertexData.applyToMesh(torus, options.updatable);
  40394. return torus;
  40395. };
  40396. /**
  40397. * Creates a torus knot mesh.
  40398. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  40399. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  40400. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  40401. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  40402. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  40403. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40404. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40405. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40406. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40407. */
  40408. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  40409. var torusKnot = new BABYLON.Mesh(name, scene);
  40410. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40411. torusKnot.sideOrientation = options.sideOrientation;
  40412. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  40413. vertexData.applyToMesh(torusKnot, options.updatable);
  40414. return torusKnot;
  40415. };
  40416. /**
  40417. * Creates a line system mesh.
  40418. * A line system is a pool of many lines gathered in a single mesh.
  40419. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  40420. * 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.
  40421. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  40422. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  40423. * 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
  40424. * 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
  40425. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  40426. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40427. */
  40428. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  40429. var instance = options.instance;
  40430. var lines = options.lines;
  40431. if (instance) {
  40432. var positionFunction = function (positions) {
  40433. var i = 0;
  40434. for (var l = 0; l < lines.length; l++) {
  40435. var points = lines[l];
  40436. for (var p = 0; p < points.length; p++) {
  40437. positions[i] = points[p].x;
  40438. positions[i + 1] = points[p].y;
  40439. positions[i + 2] = points[p].z;
  40440. i += 3;
  40441. }
  40442. }
  40443. };
  40444. instance.updateMeshPositions(positionFunction, false);
  40445. return instance;
  40446. }
  40447. // line system creation
  40448. var lineSystem = new BABYLON.LinesMesh(name, scene);
  40449. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  40450. vertexData.applyToMesh(lineSystem, options.updatable);
  40451. return lineSystem;
  40452. };
  40453. /**
  40454. * Creates a line mesh.
  40455. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  40456. * 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.
  40457. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40458. * The parameter `points` is an array successive Vector3.
  40459. * 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
  40460. * When updating an instance, remember that only point positions can change, not the number of points.
  40461. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40462. */
  40463. MeshBuilder.CreateLines = function (name, options, scene) {
  40464. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  40465. return lines;
  40466. };
  40467. /**
  40468. * Creates a dashed line mesh.
  40469. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  40470. * 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.
  40471. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40472. * The parameter `points` is an array successive Vector3.
  40473. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  40474. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  40475. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  40476. * 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
  40477. * When updating an instance, remember that only point positions can change, not the number of points.
  40478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40479. */
  40480. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  40481. var points = options.points;
  40482. var instance = options.instance;
  40483. var gapSize = options.gapSize;
  40484. var dashNb = options.dashNb;
  40485. var dashSize = options.dashSize;
  40486. if (instance) {
  40487. var positionFunction = function (positions) {
  40488. var curvect = BABYLON.Vector3.Zero();
  40489. var nbSeg = positions.length / 6;
  40490. var lg = 0;
  40491. var nb = 0;
  40492. var shft = 0;
  40493. var dashshft = 0;
  40494. var curshft = 0;
  40495. var p = 0;
  40496. var i = 0;
  40497. var j = 0;
  40498. for (i = 0; i < points.length - 1; i++) {
  40499. points[i + 1].subtractToRef(points[i], curvect);
  40500. lg += curvect.length();
  40501. }
  40502. shft = lg / nbSeg;
  40503. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  40504. for (i = 0; i < points.length - 1; i++) {
  40505. points[i + 1].subtractToRef(points[i], curvect);
  40506. nb = Math.floor(curvect.length() / shft);
  40507. curvect.normalize();
  40508. j = 0;
  40509. while (j < nb && p < positions.length) {
  40510. curshft = shft * j;
  40511. positions[p] = points[i].x + curshft * curvect.x;
  40512. positions[p + 1] = points[i].y + curshft * curvect.y;
  40513. positions[p + 2] = points[i].z + curshft * curvect.z;
  40514. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  40515. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  40516. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  40517. p += 6;
  40518. j++;
  40519. }
  40520. }
  40521. while (p < positions.length) {
  40522. positions[p] = points[i].x;
  40523. positions[p + 1] = points[i].y;
  40524. positions[p + 2] = points[i].z;
  40525. p += 3;
  40526. }
  40527. };
  40528. instance.updateMeshPositions(positionFunction, false);
  40529. return instance;
  40530. }
  40531. // dashed lines creation
  40532. var dashedLines = new BABYLON.LinesMesh(name, scene);
  40533. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  40534. vertexData.applyToMesh(dashedLines, options.updatable);
  40535. dashedLines.dashSize = dashSize;
  40536. dashedLines.gapSize = gapSize;
  40537. return dashedLines;
  40538. };
  40539. /**
  40540. * Creates an extruded shape mesh.
  40541. * 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.
  40542. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  40543. *
  40544. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40545. * 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
  40546. * extruded along the Z axis.
  40547. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40548. * 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.
  40549. * The parameter `scale` (float, default 1) is the value to scale the shape.
  40550. * 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
  40551. * 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
  40552. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40553. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40554. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40555. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40556. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40557. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40558. */
  40559. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  40560. var path = options.path;
  40561. var shape = options.shape;
  40562. var scale = options.scale || 1;
  40563. var rotation = options.rotation || 0;
  40564. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40565. var updatable = options.updatable;
  40566. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40567. var instance = options.instance;
  40568. var invertUV = options.invertUV || false;
  40569. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40570. };
  40571. /**
  40572. * Creates an custom extruded shape mesh.
  40573. * 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.
  40574. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  40575. *
  40576. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40577. * 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
  40578. * extruded along the Z axis.
  40579. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40580. * 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
  40581. * and the distance of this point from the begining of the path :
  40582. * ```javascript
  40583. * var rotationFunction = function(i, distance) {
  40584. * // do things
  40585. * return rotationValue; }
  40586. * ```
  40587. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  40588. * 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
  40589. * and the distance of this point from the begining of the path :
  40590. * ```javascript
  40591. * var scaleFunction = function(i, distance) {
  40592. * // do things
  40593. * return scaleValue;}
  40594. * ```
  40595. * It must returns a float value that will be the scale value applied to the shape on each path point.
  40596. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  40597. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  40598. * 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
  40599. * 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
  40600. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40601. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40602. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40603. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40604. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40606. */
  40607. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  40608. var path = options.path;
  40609. var shape = options.shape;
  40610. var scaleFunction = options.scaleFunction || (function () { return 1; });
  40611. var rotationFunction = options.rotationFunction || (function () { return 0; });
  40612. var ribbonCloseArray = options.ribbonCloseArray || false;
  40613. var ribbonClosePath = options.ribbonClosePath || false;
  40614. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40615. var updatable = options.updatable;
  40616. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40617. var instance = options.instance;
  40618. var invertUV = options.invertUV || false;
  40619. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40620. };
  40621. /**
  40622. * Creates lathe mesh.
  40623. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  40624. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  40625. *
  40626. * 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
  40627. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  40628. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  40629. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  40630. * 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.
  40631. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  40632. * 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
  40633. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40634. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40635. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40636. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40637. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40638. */
  40639. MeshBuilder.CreateLathe = function (name, options, scene) {
  40640. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  40641. var closed = (options.closed === undefined) ? true : options.closed;
  40642. var shape = options.shape;
  40643. var radius = options.radius || 1;
  40644. var tessellation = options.tessellation || 64;
  40645. var updatable = options.updatable;
  40646. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40647. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40648. var pi2 = Math.PI * 2;
  40649. var paths = new Array();
  40650. var invertUV = options.invertUV || false;
  40651. var i = 0;
  40652. var p = 0;
  40653. var step = pi2 / tessellation * arc;
  40654. var rotated;
  40655. var path = new Array();
  40656. ;
  40657. for (i = 0; i <= tessellation; i++) {
  40658. var path = [];
  40659. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  40660. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  40661. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  40662. }
  40663. for (p = 0; p < shape.length; p++) {
  40664. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  40665. path.push(rotated);
  40666. }
  40667. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  40668. 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));
  40669. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  40670. }
  40671. paths.push(path);
  40672. }
  40673. // lathe ribbon
  40674. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40675. return lathe;
  40676. };
  40677. /**
  40678. * Creates a plane mesh.
  40679. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40680. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  40681. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  40682. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  40683. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40684. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40685. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40687. */
  40688. MeshBuilder.CreatePlane = function (name, options, scene) {
  40689. var plane = new BABYLON.Mesh(name, scene);
  40690. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40691. plane.sideOrientation = options.sideOrientation;
  40692. var vertexData = BABYLON.VertexData.CreatePlane(options);
  40693. vertexData.applyToMesh(plane, options.updatable);
  40694. if (options.sourcePlane) {
  40695. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  40696. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  40697. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  40698. plane.rotate(vectorProduct, product);
  40699. }
  40700. return plane;
  40701. };
  40702. /**
  40703. * Creates a ground mesh.
  40704. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40705. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  40706. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  40707. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40708. */
  40709. MeshBuilder.CreateGround = function (name, options, scene) {
  40710. var ground = new BABYLON.GroundMesh(name, scene);
  40711. ground._setReady(false);
  40712. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  40713. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  40714. ground._width = options.width || 1;
  40715. ground._height = options.height || 1;
  40716. ground._maxX = ground._width / 2;
  40717. ground._maxZ = ground._height / 2;
  40718. ground._minX = -ground._maxX;
  40719. ground._minZ = -ground._maxZ;
  40720. var vertexData = BABYLON.VertexData.CreateGround(options);
  40721. vertexData.applyToMesh(ground, options.updatable);
  40722. ground._setReady(true);
  40723. return ground;
  40724. };
  40725. /**
  40726. * Creates a tiled ground mesh.
  40727. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  40728. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  40729. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  40730. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  40731. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  40732. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  40733. * numbers of subdivisions on the ground width and height of each tile.
  40734. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40735. */
  40736. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  40737. var tiledGround = new BABYLON.Mesh(name, scene);
  40738. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  40739. vertexData.applyToMesh(tiledGround, options.updatable);
  40740. return tiledGround;
  40741. };
  40742. /**
  40743. * Creates a ground mesh from a height map.
  40744. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  40745. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  40746. * The parameter `url` sets the URL of the height map image resource.
  40747. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  40748. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  40749. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  40750. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  40751. * 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.
  40752. * 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).
  40753. * This function is passed the newly built mesh :
  40754. * ```javascript
  40755. * function(mesh) { // do things
  40756. * return; }
  40757. * ```
  40758. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40759. */
  40760. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  40761. var width = options.width || 10.0;
  40762. var height = options.height || 10.0;
  40763. var subdivisions = options.subdivisions || 1 | 0;
  40764. var minHeight = options.minHeight || 0.0;
  40765. var maxHeight = options.maxHeight || 10.0;
  40766. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  40767. var updatable = options.updatable;
  40768. var onReady = options.onReady;
  40769. var ground = new BABYLON.GroundMesh(name, scene);
  40770. ground._subdivisionsX = subdivisions;
  40771. ground._subdivisionsY = subdivisions;
  40772. ground._width = width;
  40773. ground._height = height;
  40774. ground._maxX = ground._width / 2.0;
  40775. ground._maxZ = ground._height / 2.0;
  40776. ground._minX = -ground._maxX;
  40777. ground._minZ = -ground._maxZ;
  40778. ground._setReady(false);
  40779. var onload = function (img) {
  40780. // Getting height map data
  40781. var canvas = document.createElement("canvas");
  40782. var context = canvas.getContext("2d");
  40783. var bufferWidth = img.width;
  40784. var bufferHeight = img.height;
  40785. canvas.width = bufferWidth;
  40786. canvas.height = bufferHeight;
  40787. context.drawImage(img, 0, 0);
  40788. // Create VertexData from map data
  40789. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  40790. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  40791. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  40792. width: width, height: height,
  40793. subdivisions: subdivisions,
  40794. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  40795. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  40796. });
  40797. vertexData.applyToMesh(ground, updatable);
  40798. ground._setReady(true);
  40799. //execute ready callback, if set
  40800. if (onReady) {
  40801. onReady(ground);
  40802. }
  40803. };
  40804. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  40805. return ground;
  40806. };
  40807. /**
  40808. * Creates a polygon mesh.
  40809. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  40810. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  40811. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40812. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40813. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40814. * Remember you can only change the shape positions, not their number when updating a polygon.
  40815. */
  40816. MeshBuilder.CreatePolygon = function (name, options, scene) {
  40817. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40818. var shape = options.shape;
  40819. var holes = options.holes || [];
  40820. var depth = options.depth || 0;
  40821. var contours = [];
  40822. var hole = [];
  40823. for (var i = 0; i < shape.length; i++) {
  40824. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  40825. }
  40826. var epsilon = 0.00000001;
  40827. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  40828. contours.pop();
  40829. }
  40830. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  40831. for (var hNb = 0; hNb < holes.length; hNb++) {
  40832. hole = [];
  40833. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  40834. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  40835. }
  40836. polygonTriangulation.addHole(hole);
  40837. }
  40838. var polygon = polygonTriangulation.build(options.updatable, depth);
  40839. polygon.sideOrientation = options.sideOrientation;
  40840. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  40841. vertexData.applyToMesh(polygon, options.updatable);
  40842. return polygon;
  40843. };
  40844. ;
  40845. /**
  40846. * Creates an extruded polygon mesh, with depth in the Y direction.
  40847. * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements).
  40848. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40849. */
  40850. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  40851. return MeshBuilder.CreatePolygon(name, options, scene);
  40852. };
  40853. ;
  40854. /**
  40855. * Creates a tube mesh.
  40856. * 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.
  40857. *
  40858. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  40859. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  40860. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  40861. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  40862. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  40863. * 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.
  40864. * It must return a radius value (positive float) :
  40865. * ```javascript
  40866. * var radiusFunction = function(i, distance) {
  40867. * // do things
  40868. * return radius; }
  40869. * ```
  40870. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  40871. * 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
  40872. * 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
  40873. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40874. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40875. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40876. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40877. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40878. */
  40879. MeshBuilder.CreateTube = function (name, options, scene) {
  40880. var path = options.path;
  40881. var radius = options.radius || 1.0;
  40882. var tessellation = options.tessellation || 64 | 0;
  40883. var radiusFunction = options.radiusFunction;
  40884. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40885. var invertUV = options.invertUV || false;
  40886. var updatable = options.updatable;
  40887. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40888. var instance = options.instance;
  40889. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  40890. // tube geometry
  40891. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  40892. var tangents = path3D.getTangents();
  40893. var normals = path3D.getNormals();
  40894. var distances = path3D.getDistances();
  40895. var pi2 = Math.PI * 2;
  40896. var step = pi2 / tessellation * arc;
  40897. var returnRadius = function () { return radius; };
  40898. var radiusFunctionFinal = radiusFunction || returnRadius;
  40899. var circlePath;
  40900. var rad;
  40901. var normal;
  40902. var rotated;
  40903. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  40904. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  40905. for (var i = 0; i < path.length; i++) {
  40906. rad = radiusFunctionFinal(i, distances[i]); // current radius
  40907. circlePath = Array(); // current circle array
  40908. normal = normals[i]; // current normal
  40909. for (var t = 0; t < tessellation; t++) {
  40910. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  40911. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  40912. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  40913. rotated.scaleInPlace(rad).addInPlace(path[i]);
  40914. circlePath[t] = rotated;
  40915. }
  40916. circlePaths[index] = circlePath;
  40917. index++;
  40918. }
  40919. // cap
  40920. var capPath = function (nbPoints, pathIndex) {
  40921. var pointCap = Array();
  40922. for (var i = 0; i < nbPoints; i++) {
  40923. pointCap.push(path[pathIndex]);
  40924. }
  40925. return pointCap;
  40926. };
  40927. switch (cap) {
  40928. case BABYLON.Mesh.NO_CAP:
  40929. break;
  40930. case BABYLON.Mesh.CAP_START:
  40931. circlePaths[0] = capPath(tessellation, 0);
  40932. circlePaths[1] = circlePaths[2].slice(0);
  40933. break;
  40934. case BABYLON.Mesh.CAP_END:
  40935. circlePaths[index] = circlePaths[index - 1].slice(0);
  40936. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40937. break;
  40938. case BABYLON.Mesh.CAP_ALL:
  40939. circlePaths[0] = capPath(tessellation, 0);
  40940. circlePaths[1] = circlePaths[2].slice(0);
  40941. circlePaths[index] = circlePaths[index - 1].slice(0);
  40942. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  40943. break;
  40944. default:
  40945. break;
  40946. }
  40947. return circlePaths;
  40948. };
  40949. var path3D;
  40950. var pathArray;
  40951. if (instance) {
  40952. var arc = options.arc || instance.arc;
  40953. path3D = (instance.path3D).update(path);
  40954. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  40955. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  40956. instance.path3D = path3D;
  40957. instance.pathArray = pathArray;
  40958. instance.arc = arc;
  40959. return instance;
  40960. }
  40961. // tube creation
  40962. path3D = new BABYLON.Path3D(path);
  40963. var newPathArray = new Array();
  40964. cap = (cap < 0 || cap > 3) ? 0 : cap;
  40965. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  40966. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40967. tube.pathArray = pathArray;
  40968. tube.path3D = path3D;
  40969. tube.tessellation = tessellation;
  40970. tube.cap = cap;
  40971. tube.arc = options.arc;
  40972. return tube;
  40973. };
  40974. /**
  40975. * Creates a polyhedron mesh.
  40976. *
  40977. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  40978. * 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
  40979. * to choose the wanted type.
  40980. * The parameter `size` (positive float, default 1) sets the polygon size.
  40981. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  40982. * 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`.
  40983. * 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
  40984. * 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)`).
  40985. * 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
  40986. * 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.
  40987. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40988. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40989. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40991. */
  40992. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  40993. var polyhedron = new BABYLON.Mesh(name, scene);
  40994. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40995. polyhedron.sideOrientation = options.sideOrientation;
  40996. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  40997. vertexData.applyToMesh(polyhedron, options.updatable);
  40998. return polyhedron;
  40999. };
  41000. /**
  41001. * Creates a decal mesh.
  41002. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  41003. * 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.
  41004. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  41005. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  41006. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  41007. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  41008. */
  41009. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  41010. var indices = sourceMesh.getIndices();
  41011. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41012. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41013. var position = options.position || BABYLON.Vector3.Zero();
  41014. var normal = options.normal || BABYLON.Vector3.Up();
  41015. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  41016. var angle = options.angle || 0;
  41017. // Getting correct rotation
  41018. if (!normal) {
  41019. var target = new BABYLON.Vector3(0, 0, 1);
  41020. var camera = sourceMesh.getScene().activeCamera;
  41021. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  41022. normal = camera.globalPosition.subtract(cameraWorldTarget);
  41023. }
  41024. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  41025. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  41026. var pitch = Math.atan2(normal.y, len);
  41027. // Matrix
  41028. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  41029. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  41030. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  41031. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  41032. var vertexData = new BABYLON.VertexData();
  41033. vertexData.indices = [];
  41034. vertexData.positions = [];
  41035. vertexData.normals = [];
  41036. vertexData.uvs = [];
  41037. var currentVertexDataIndex = 0;
  41038. var extractDecalVector3 = function (indexId) {
  41039. var vertexId = indices[indexId];
  41040. var result = new BABYLON.PositionNormalVertex();
  41041. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  41042. // Send vector to decal local world
  41043. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  41044. // Get normal
  41045. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  41046. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  41047. return result;
  41048. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  41049. var clip = function (vertices, axis) {
  41050. if (vertices.length === 0) {
  41051. return vertices;
  41052. }
  41053. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  41054. var clipVertices = function (v0, v1) {
  41055. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  41056. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  41057. };
  41058. var result = new Array();
  41059. for (var index = 0; index < vertices.length; index += 3) {
  41060. var v1Out;
  41061. var v2Out;
  41062. var v3Out;
  41063. var total = 0;
  41064. var nV1, nV2, nV3, nV4;
  41065. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  41066. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  41067. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  41068. v1Out = d1 > 0;
  41069. v2Out = d2 > 0;
  41070. v3Out = d3 > 0;
  41071. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  41072. switch (total) {
  41073. case 0:
  41074. result.push(vertices[index]);
  41075. result.push(vertices[index + 1]);
  41076. result.push(vertices[index + 2]);
  41077. break;
  41078. case 1:
  41079. if (v1Out) {
  41080. nV1 = vertices[index + 1];
  41081. nV2 = vertices[index + 2];
  41082. nV3 = clipVertices(vertices[index], nV1);
  41083. nV4 = clipVertices(vertices[index], nV2);
  41084. }
  41085. if (v2Out) {
  41086. nV1 = vertices[index];
  41087. nV2 = vertices[index + 2];
  41088. nV3 = clipVertices(vertices[index + 1], nV1);
  41089. nV4 = clipVertices(vertices[index + 1], nV2);
  41090. result.push(nV3);
  41091. result.push(nV2.clone());
  41092. result.push(nV1.clone());
  41093. result.push(nV2.clone());
  41094. result.push(nV3.clone());
  41095. result.push(nV4);
  41096. break;
  41097. }
  41098. if (v3Out) {
  41099. nV1 = vertices[index];
  41100. nV2 = vertices[index + 1];
  41101. nV3 = clipVertices(vertices[index + 2], nV1);
  41102. nV4 = clipVertices(vertices[index + 2], nV2);
  41103. }
  41104. result.push(nV1.clone());
  41105. result.push(nV2.clone());
  41106. result.push(nV3);
  41107. result.push(nV4);
  41108. result.push(nV3.clone());
  41109. result.push(nV2.clone());
  41110. break;
  41111. case 2:
  41112. if (!v1Out) {
  41113. nV1 = vertices[index].clone();
  41114. nV2 = clipVertices(nV1, vertices[index + 1]);
  41115. nV3 = clipVertices(nV1, vertices[index + 2]);
  41116. result.push(nV1);
  41117. result.push(nV2);
  41118. result.push(nV3);
  41119. }
  41120. if (!v2Out) {
  41121. nV1 = vertices[index + 1].clone();
  41122. nV2 = clipVertices(nV1, vertices[index + 2]);
  41123. nV3 = clipVertices(nV1, vertices[index]);
  41124. result.push(nV1);
  41125. result.push(nV2);
  41126. result.push(nV3);
  41127. }
  41128. if (!v3Out) {
  41129. nV1 = vertices[index + 2].clone();
  41130. nV2 = clipVertices(nV1, vertices[index]);
  41131. nV3 = clipVertices(nV1, vertices[index + 1]);
  41132. result.push(nV1);
  41133. result.push(nV2);
  41134. result.push(nV3);
  41135. }
  41136. break;
  41137. case 3:
  41138. break;
  41139. }
  41140. }
  41141. return result;
  41142. };
  41143. for (var index = 0; index < indices.length; index += 3) {
  41144. var faceVertices = new Array();
  41145. faceVertices.push(extractDecalVector3(index));
  41146. faceVertices.push(extractDecalVector3(index + 1));
  41147. faceVertices.push(extractDecalVector3(index + 2));
  41148. // Clip
  41149. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  41150. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  41151. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  41152. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  41153. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  41154. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  41155. if (faceVertices.length === 0) {
  41156. continue;
  41157. }
  41158. // Add UVs and get back to world
  41159. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  41160. var vertex = faceVertices[vIndex];
  41161. //TODO check for Int32Array | Uint32Array | Uint16Array
  41162. vertexData.indices.push(currentVertexDataIndex);
  41163. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  41164. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  41165. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  41166. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  41167. currentVertexDataIndex++;
  41168. }
  41169. }
  41170. // Return mesh
  41171. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  41172. vertexData.applyToMesh(decal);
  41173. decal.position = position.clone();
  41174. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  41175. return decal;
  41176. };
  41177. // Privates
  41178. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  41179. // extrusion geometry
  41180. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  41181. var tangents = path3D.getTangents();
  41182. var normals = path3D.getNormals();
  41183. var binormals = path3D.getBinormals();
  41184. var distances = path3D.getDistances();
  41185. var angle = 0;
  41186. var returnScale = function () { return scale; };
  41187. var returnRotation = function () { return rotation; };
  41188. var rotate = custom ? rotateFunction : returnRotation;
  41189. var scl = custom ? scaleFunction : returnScale;
  41190. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  41191. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  41192. for (var i = 0; i < curve.length; i++) {
  41193. var shapePath = new Array();
  41194. var angleStep = rotate(i, distances[i]);
  41195. var scaleRatio = scl(i, distances[i]);
  41196. for (var p = 0; p < shape.length; p++) {
  41197. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  41198. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  41199. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  41200. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  41201. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  41202. shapePath[p] = rotated;
  41203. }
  41204. shapePaths[index] = shapePath;
  41205. angle += angleStep;
  41206. index++;
  41207. }
  41208. // cap
  41209. var capPath = function (shapePath) {
  41210. var pointCap = Array();
  41211. var barycenter = BABYLON.Vector3.Zero();
  41212. var i;
  41213. for (i = 0; i < shapePath.length; i++) {
  41214. barycenter.addInPlace(shapePath[i]);
  41215. }
  41216. barycenter.scaleInPlace(1.0 / shapePath.length);
  41217. for (i = 0; i < shapePath.length; i++) {
  41218. pointCap.push(barycenter);
  41219. }
  41220. return pointCap;
  41221. };
  41222. switch (cap) {
  41223. case BABYLON.Mesh.NO_CAP:
  41224. break;
  41225. case BABYLON.Mesh.CAP_START:
  41226. shapePaths[0] = capPath(shapePaths[2]);
  41227. shapePaths[1] = shapePaths[2];
  41228. break;
  41229. case BABYLON.Mesh.CAP_END:
  41230. shapePaths[index] = shapePaths[index - 1];
  41231. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41232. break;
  41233. case BABYLON.Mesh.CAP_ALL:
  41234. shapePaths[0] = capPath(shapePaths[2]);
  41235. shapePaths[1] = shapePaths[2];
  41236. shapePaths[index] = shapePaths[index - 1];
  41237. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41238. break;
  41239. default:
  41240. break;
  41241. }
  41242. return shapePaths;
  41243. };
  41244. var path3D;
  41245. var pathArray;
  41246. if (instance) {
  41247. path3D = (instance.path3D).update(curve);
  41248. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  41249. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  41250. return instance;
  41251. }
  41252. // extruded shape creation
  41253. path3D = new BABYLON.Path3D(curve);
  41254. var newShapePaths = new Array();
  41255. cap = (cap < 0 || cap > 3) ? 0 : cap;
  41256. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  41257. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  41258. extrudedGeneric.pathArray = pathArray;
  41259. extrudedGeneric.path3D = path3D;
  41260. extrudedGeneric.cap = cap;
  41261. return extrudedGeneric;
  41262. };
  41263. return MeshBuilder;
  41264. }());
  41265. BABYLON.MeshBuilder = MeshBuilder;
  41266. })(BABYLON || (BABYLON = {}));
  41267. //# sourceMappingURL=babylon.meshBuilder.js.map
  41268. var BABYLON;
  41269. (function (BABYLON) {
  41270. var AudioEngine = (function () {
  41271. function AudioEngine() {
  41272. this._audioContext = null;
  41273. this._audioContextInitialized = false;
  41274. this.canUseWebAudio = false;
  41275. this.WarnedWebAudioUnsupported = false;
  41276. this.unlocked = false;
  41277. this.isMP3supported = false;
  41278. this.isOGGsupported = false;
  41279. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  41280. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  41281. this.canUseWebAudio = true;
  41282. }
  41283. var audioElem = document.createElement('audio');
  41284. try {
  41285. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  41286. this.isMP3supported = true;
  41287. }
  41288. }
  41289. catch (e) {
  41290. // protect error during capability check.
  41291. }
  41292. try {
  41293. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  41294. this.isOGGsupported = true;
  41295. }
  41296. }
  41297. catch (e) {
  41298. // protect error during capability check.
  41299. }
  41300. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  41301. this._unlockiOSaudio();
  41302. }
  41303. else {
  41304. this.unlocked = true;
  41305. }
  41306. }
  41307. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  41308. get: function () {
  41309. if (!this._audioContextInitialized) {
  41310. this._initializeAudioContext();
  41311. }
  41312. return this._audioContext;
  41313. },
  41314. enumerable: true,
  41315. configurable: true
  41316. });
  41317. AudioEngine.prototype._unlockiOSaudio = function () {
  41318. var _this = this;
  41319. var unlockaudio = function () {
  41320. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  41321. var source = _this.audioContext.createBufferSource();
  41322. source.buffer = buffer;
  41323. source.connect(_this.audioContext.destination);
  41324. source.start(0);
  41325. setTimeout(function () {
  41326. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  41327. _this.unlocked = true;
  41328. window.removeEventListener('touchend', unlockaudio, false);
  41329. if (_this.onAudioUnlocked) {
  41330. _this.onAudioUnlocked();
  41331. }
  41332. }
  41333. }, 0);
  41334. };
  41335. window.addEventListener('touchend', unlockaudio, false);
  41336. };
  41337. AudioEngine.prototype._initializeAudioContext = function () {
  41338. try {
  41339. if (this.canUseWebAudio) {
  41340. this._audioContext = new AudioContext();
  41341. // create a global volume gain node
  41342. this.masterGain = this._audioContext.createGain();
  41343. this.masterGain.gain.value = 1;
  41344. this.masterGain.connect(this._audioContext.destination);
  41345. this._audioContextInitialized = true;
  41346. }
  41347. }
  41348. catch (e) {
  41349. this.canUseWebAudio = false;
  41350. BABYLON.Tools.Error("Web Audio: " + e.message);
  41351. }
  41352. };
  41353. AudioEngine.prototype.dispose = function () {
  41354. if (this.canUseWebAudio && this._audioContextInitialized) {
  41355. if (this._connectedAnalyser) {
  41356. this._connectedAnalyser.stopDebugCanvas();
  41357. this._connectedAnalyser.dispose();
  41358. this.masterGain.disconnect();
  41359. this.masterGain.connect(this._audioContext.destination);
  41360. this._connectedAnalyser = null;
  41361. }
  41362. this.masterGain.gain.value = 1;
  41363. }
  41364. this.WarnedWebAudioUnsupported = false;
  41365. };
  41366. AudioEngine.prototype.getGlobalVolume = function () {
  41367. if (this.canUseWebAudio && this._audioContextInitialized) {
  41368. return this.masterGain.gain.value;
  41369. }
  41370. else {
  41371. return -1;
  41372. }
  41373. };
  41374. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  41375. if (this.canUseWebAudio && this._audioContextInitialized) {
  41376. this.masterGain.gain.value = newVolume;
  41377. }
  41378. };
  41379. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  41380. if (this._connectedAnalyser) {
  41381. this._connectedAnalyser.stopDebugCanvas();
  41382. }
  41383. if (this.canUseWebAudio && this._audioContextInitialized) {
  41384. this._connectedAnalyser = analyser;
  41385. this.masterGain.disconnect();
  41386. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  41387. }
  41388. };
  41389. return AudioEngine;
  41390. }());
  41391. BABYLON.AudioEngine = AudioEngine;
  41392. })(BABYLON || (BABYLON = {}));
  41393. //# sourceMappingURL=babylon.audioEngine.js.map
  41394. var BABYLON;
  41395. (function (BABYLON) {
  41396. var Sound = (function () {
  41397. /**
  41398. * Create a sound and attach it to a scene
  41399. * @param name Name of your sound
  41400. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  41401. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  41402. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  41403. */
  41404. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  41405. var _this = this;
  41406. this.autoplay = false;
  41407. this.loop = false;
  41408. this.useCustomAttenuation = false;
  41409. this.spatialSound = false;
  41410. this.refDistance = 1;
  41411. this.rolloffFactor = 1;
  41412. this.maxDistance = 100;
  41413. this.distanceModel = "linear";
  41414. this._panningModel = "equalpower";
  41415. this._playbackRate = 1;
  41416. this._streaming = false;
  41417. this._startTime = 0;
  41418. this._startOffset = 0;
  41419. this._position = BABYLON.Vector3.Zero();
  41420. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  41421. this._volume = 1;
  41422. this._isLoaded = false;
  41423. this._isReadyToPlay = false;
  41424. this.isPlaying = false;
  41425. this.isPaused = false;
  41426. this._isDirectional = false;
  41427. // Used if you'd like to create a directional sound.
  41428. // If not set, the sound will be omnidirectional
  41429. this._coneInnerAngle = 360;
  41430. this._coneOuterAngle = 360;
  41431. this._coneOuterGain = 0;
  41432. this._isOutputConnected = false;
  41433. this._urlType = "Unknown";
  41434. this.name = name;
  41435. this._scene = scene;
  41436. this._readyToPlayCallback = readyToPlayCallback;
  41437. // Default custom attenuation function is a linear attenuation
  41438. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  41439. if (currentDistance < maxDistance) {
  41440. return currentVolume * (1 - currentDistance / maxDistance);
  41441. }
  41442. else {
  41443. return 0;
  41444. }
  41445. };
  41446. if (options) {
  41447. this.autoplay = options.autoplay || false;
  41448. this.loop = options.loop || false;
  41449. // if volume === 0, we need another way to check this option
  41450. if (options.volume !== undefined) {
  41451. this._volume = options.volume;
  41452. }
  41453. this.spatialSound = options.spatialSound || false;
  41454. this.maxDistance = options.maxDistance || 100;
  41455. this.useCustomAttenuation = options.useCustomAttenuation || false;
  41456. this.rolloffFactor = options.rolloffFactor || 1;
  41457. this.refDistance = options.refDistance || 1;
  41458. this.distanceModel = options.distanceModel || "linear";
  41459. this._playbackRate = options.playbackRate || 1;
  41460. this._streaming = options.streaming || false;
  41461. }
  41462. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41463. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  41464. this._soundGain.gain.value = this._volume;
  41465. this._inputAudioNode = this._soundGain;
  41466. this._ouputAudioNode = this._soundGain;
  41467. if (this.spatialSound) {
  41468. this._createSpatialParameters();
  41469. }
  41470. this._scene.mainSoundTrack.AddSound(this);
  41471. var validParameter = true;
  41472. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  41473. if (urlOrArrayBuffer) {
  41474. if (typeof (urlOrArrayBuffer) === "string")
  41475. this._urlType = "String";
  41476. if (Array.isArray(urlOrArrayBuffer))
  41477. this._urlType = "Array";
  41478. if (urlOrArrayBuffer instanceof ArrayBuffer)
  41479. this._urlType = "ArrayBuffer";
  41480. var urls = [];
  41481. var codecSupportedFound = false;
  41482. switch (this._urlType) {
  41483. case "ArrayBuffer":
  41484. if (urlOrArrayBuffer.byteLength > 0) {
  41485. codecSupportedFound = true;
  41486. this._soundLoaded(urlOrArrayBuffer);
  41487. }
  41488. break;
  41489. case "String":
  41490. urls.push(urlOrArrayBuffer);
  41491. case "Array":
  41492. if (urls.length === 0)
  41493. urls = urlOrArrayBuffer;
  41494. // If we found a supported format, we load it immediately and stop the loop
  41495. for (var i = 0; i < urls.length; i++) {
  41496. var url = urls[i];
  41497. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  41498. codecSupportedFound = true;
  41499. }
  41500. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  41501. codecSupportedFound = true;
  41502. }
  41503. if (url.indexOf(".wav", url.length - 4) !== -1) {
  41504. codecSupportedFound = true;
  41505. }
  41506. if (codecSupportedFound) {
  41507. // Loading sound using XHR2
  41508. if (!this._streaming) {
  41509. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  41510. }
  41511. else {
  41512. this._htmlAudioElement = new Audio(url);
  41513. this._htmlAudioElement.controls = false;
  41514. this._htmlAudioElement.loop = this.loop;
  41515. this._htmlAudioElement.crossOrigin = "anonymous";
  41516. this._htmlAudioElement.preload = "auto";
  41517. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  41518. _this._isReadyToPlay = true;
  41519. if (_this.autoplay) {
  41520. _this.play();
  41521. }
  41522. if (_this._readyToPlayCallback) {
  41523. _this._readyToPlayCallback();
  41524. }
  41525. });
  41526. document.body.appendChild(this._htmlAudioElement);
  41527. }
  41528. break;
  41529. }
  41530. }
  41531. break;
  41532. default:
  41533. validParameter = false;
  41534. break;
  41535. }
  41536. if (!validParameter) {
  41537. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  41538. }
  41539. else {
  41540. if (!codecSupportedFound) {
  41541. this._isReadyToPlay = true;
  41542. // Simulating a ready to play event to avoid breaking code path
  41543. if (this._readyToPlayCallback) {
  41544. window.setTimeout(function () {
  41545. _this._readyToPlayCallback();
  41546. }, 1000);
  41547. }
  41548. }
  41549. }
  41550. }
  41551. }
  41552. else {
  41553. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  41554. this._scene.mainSoundTrack.AddSound(this);
  41555. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  41556. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  41557. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  41558. }
  41559. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  41560. if (this._readyToPlayCallback) {
  41561. window.setTimeout(function () {
  41562. _this._readyToPlayCallback();
  41563. }, 1000);
  41564. }
  41565. }
  41566. }
  41567. Sound.prototype.dispose = function () {
  41568. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  41569. if (this.isPlaying) {
  41570. this.stop();
  41571. }
  41572. this._isReadyToPlay = false;
  41573. if (this.soundTrackId === -1) {
  41574. this._scene.mainSoundTrack.RemoveSound(this);
  41575. }
  41576. else {
  41577. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  41578. }
  41579. if (this._soundGain) {
  41580. this._soundGain.disconnect();
  41581. this._soundGain = null;
  41582. }
  41583. if (this._soundPanner) {
  41584. this._soundPanner.disconnect();
  41585. this._soundPanner = null;
  41586. }
  41587. if (this._soundSource) {
  41588. this._soundSource.disconnect();
  41589. this._soundSource = null;
  41590. }
  41591. this._audioBuffer = null;
  41592. if (this._htmlAudioElement) {
  41593. this._htmlAudioElement.pause();
  41594. this._htmlAudioElement.src = "";
  41595. document.body.removeChild(this._htmlAudioElement);
  41596. }
  41597. if (this._connectedMesh) {
  41598. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41599. this._connectedMesh = null;
  41600. }
  41601. }
  41602. };
  41603. Sound.prototype.isReady = function () {
  41604. return this._isReadyToPlay;
  41605. };
  41606. Sound.prototype._soundLoaded = function (audioData) {
  41607. var _this = this;
  41608. this._isLoaded = true;
  41609. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  41610. _this._audioBuffer = buffer;
  41611. _this._isReadyToPlay = true;
  41612. if (_this.autoplay) {
  41613. _this.play();
  41614. }
  41615. if (_this._readyToPlayCallback) {
  41616. _this._readyToPlayCallback();
  41617. }
  41618. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  41619. };
  41620. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  41621. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41622. this._audioBuffer = audioBuffer;
  41623. this._isReadyToPlay = true;
  41624. }
  41625. };
  41626. Sound.prototype.updateOptions = function (options) {
  41627. if (options) {
  41628. this.loop = options.loop || this.loop;
  41629. this.maxDistance = options.maxDistance || this.maxDistance;
  41630. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  41631. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  41632. this.refDistance = options.refDistance || this.refDistance;
  41633. this.distanceModel = options.distanceModel || this.distanceModel;
  41634. this._playbackRate = options.playbackRate || this._playbackRate;
  41635. this._updateSpatialParameters();
  41636. if (this.isPlaying) {
  41637. if (this._streaming) {
  41638. this._htmlAudioElement.playbackRate = this._playbackRate;
  41639. }
  41640. else {
  41641. this._soundSource.playbackRate.value = this._playbackRate;
  41642. }
  41643. }
  41644. }
  41645. };
  41646. Sound.prototype._createSpatialParameters = function () {
  41647. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41648. if (this._scene.headphone) {
  41649. this._panningModel = "HRTF";
  41650. }
  41651. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  41652. this._updateSpatialParameters();
  41653. this._soundPanner.connect(this._ouputAudioNode);
  41654. this._inputAudioNode = this._soundPanner;
  41655. }
  41656. };
  41657. Sound.prototype._updateSpatialParameters = function () {
  41658. if (this.spatialSound) {
  41659. if (this.useCustomAttenuation) {
  41660. // Tricks to disable in a way embedded Web Audio attenuation
  41661. this._soundPanner.distanceModel = "linear";
  41662. this._soundPanner.maxDistance = Number.MAX_VALUE;
  41663. this._soundPanner.refDistance = 1;
  41664. this._soundPanner.rolloffFactor = 1;
  41665. this._soundPanner.panningModel = this._panningModel;
  41666. }
  41667. else {
  41668. this._soundPanner.distanceModel = this.distanceModel;
  41669. this._soundPanner.maxDistance = this.maxDistance;
  41670. this._soundPanner.refDistance = this.refDistance;
  41671. this._soundPanner.rolloffFactor = this.rolloffFactor;
  41672. this._soundPanner.panningModel = this._panningModel;
  41673. }
  41674. }
  41675. };
  41676. Sound.prototype.switchPanningModelToHRTF = function () {
  41677. this._panningModel = "HRTF";
  41678. this._switchPanningModel();
  41679. };
  41680. Sound.prototype.switchPanningModelToEqualPower = function () {
  41681. this._panningModel = "equalpower";
  41682. this._switchPanningModel();
  41683. };
  41684. Sound.prototype._switchPanningModel = function () {
  41685. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41686. this._soundPanner.panningModel = this._panningModel;
  41687. }
  41688. };
  41689. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  41690. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41691. if (this._isOutputConnected) {
  41692. this._ouputAudioNode.disconnect();
  41693. }
  41694. this._ouputAudioNode.connect(soundTrackAudioNode);
  41695. this._isOutputConnected = true;
  41696. }
  41697. };
  41698. /**
  41699. * Transform this sound into a directional source
  41700. * @param coneInnerAngle Size of the inner cone in degree
  41701. * @param coneOuterAngle Size of the outer cone in degree
  41702. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  41703. */
  41704. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  41705. if (coneOuterAngle < coneInnerAngle) {
  41706. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  41707. return;
  41708. }
  41709. this._coneInnerAngle = coneInnerAngle;
  41710. this._coneOuterAngle = coneOuterAngle;
  41711. this._coneOuterGain = coneOuterGain;
  41712. this._isDirectional = true;
  41713. if (this.isPlaying && this.loop) {
  41714. this.stop();
  41715. this.play();
  41716. }
  41717. };
  41718. Sound.prototype.setPosition = function (newPosition) {
  41719. this._position = newPosition;
  41720. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41721. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  41722. }
  41723. };
  41724. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  41725. this._localDirection = newLocalDirection;
  41726. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  41727. this._updateDirection();
  41728. }
  41729. };
  41730. Sound.prototype._updateDirection = function () {
  41731. var mat = this._connectedMesh.getWorldMatrix();
  41732. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  41733. direction.normalize();
  41734. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  41735. };
  41736. Sound.prototype.updateDistanceFromListener = function () {
  41737. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  41738. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  41739. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  41740. }
  41741. };
  41742. Sound.prototype.setAttenuationFunction = function (callback) {
  41743. this._customAttenuationFunction = callback;
  41744. };
  41745. /**
  41746. * Play the sound
  41747. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  41748. * @param offset (optional) Start the sound setting it at a specific time
  41749. */
  41750. Sound.prototype.play = function (time, offset) {
  41751. var _this = this;
  41752. if (this._isReadyToPlay && this._scene.audioEnabled) {
  41753. try {
  41754. if (this._startOffset < 0) {
  41755. time = -this._startOffset;
  41756. this._startOffset = 0;
  41757. }
  41758. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  41759. if (!this._soundSource || !this._streamingSource) {
  41760. if (this.spatialSound) {
  41761. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  41762. if (this._isDirectional) {
  41763. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  41764. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  41765. this._soundPanner.coneOuterGain = this._coneOuterGain;
  41766. if (this._connectedMesh) {
  41767. this._updateDirection();
  41768. }
  41769. else {
  41770. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  41771. }
  41772. }
  41773. }
  41774. }
  41775. if (this._streaming) {
  41776. if (!this._streamingSource) {
  41777. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  41778. this._htmlAudioElement.onended = function () { _this._onended(); };
  41779. this._htmlAudioElement.playbackRate = this._playbackRate;
  41780. }
  41781. this._streamingSource.disconnect();
  41782. this._streamingSource.connect(this._inputAudioNode);
  41783. this._htmlAudioElement.play();
  41784. }
  41785. else {
  41786. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  41787. this._soundSource.buffer = this._audioBuffer;
  41788. this._soundSource.connect(this._inputAudioNode);
  41789. this._soundSource.loop = this.loop;
  41790. this._soundSource.playbackRate.value = this._playbackRate;
  41791. this._soundSource.onended = function () { _this._onended(); };
  41792. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  41793. }
  41794. this._startTime = startTime;
  41795. this.isPlaying = true;
  41796. this.isPaused = false;
  41797. }
  41798. catch (ex) {
  41799. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  41800. }
  41801. }
  41802. };
  41803. Sound.prototype._onended = function () {
  41804. this.isPlaying = false;
  41805. if (this.onended) {
  41806. this.onended();
  41807. }
  41808. };
  41809. /**
  41810. * Stop the sound
  41811. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  41812. */
  41813. Sound.prototype.stop = function (time) {
  41814. if (this.isPlaying) {
  41815. if (this._streaming) {
  41816. this._htmlAudioElement.pause();
  41817. // Test needed for Firefox or it will generate an Invalid State Error
  41818. if (this._htmlAudioElement.currentTime > 0) {
  41819. this._htmlAudioElement.currentTime = 0;
  41820. }
  41821. }
  41822. else {
  41823. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  41824. this._soundSource.stop(stopTime);
  41825. this._soundSource.onended = null;
  41826. if (!this.isPaused) {
  41827. this._startOffset = 0;
  41828. }
  41829. }
  41830. this.isPlaying = false;
  41831. }
  41832. };
  41833. Sound.prototype.pause = function () {
  41834. if (this.isPlaying) {
  41835. this.isPaused = true;
  41836. if (this._streaming) {
  41837. this._htmlAudioElement.pause();
  41838. }
  41839. else {
  41840. this.stop(0);
  41841. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  41842. }
  41843. }
  41844. };
  41845. Sound.prototype.setVolume = function (newVolume, time) {
  41846. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41847. if (time) {
  41848. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  41849. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  41850. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  41851. }
  41852. else {
  41853. this._soundGain.gain.value = newVolume;
  41854. }
  41855. }
  41856. this._volume = newVolume;
  41857. };
  41858. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  41859. this._playbackRate = newPlaybackRate;
  41860. if (this.isPlaying) {
  41861. if (this._streaming) {
  41862. this._htmlAudioElement.playbackRate = this._playbackRate;
  41863. }
  41864. else {
  41865. this._soundSource.playbackRate.value = this._playbackRate;
  41866. }
  41867. }
  41868. };
  41869. Sound.prototype.getVolume = function () {
  41870. return this._volume;
  41871. };
  41872. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  41873. var _this = this;
  41874. if (this._connectedMesh) {
  41875. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41876. this._registerFunc = null;
  41877. }
  41878. this._connectedMesh = meshToConnectTo;
  41879. if (!this.spatialSound) {
  41880. this.spatialSound = true;
  41881. this._createSpatialParameters();
  41882. if (this.isPlaying && this.loop) {
  41883. this.stop();
  41884. this.play();
  41885. }
  41886. }
  41887. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  41888. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  41889. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  41890. };
  41891. Sound.prototype.detachFromMesh = function () {
  41892. if (this._connectedMesh) {
  41893. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41894. this._registerFunc = null;
  41895. this._connectedMesh = null;
  41896. }
  41897. };
  41898. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  41899. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  41900. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  41901. this._updateDirection();
  41902. }
  41903. };
  41904. Sound.prototype.clone = function () {
  41905. var _this = this;
  41906. if (!this._streaming) {
  41907. var setBufferAndRun = function () {
  41908. if (_this._isReadyToPlay) {
  41909. clonedSound._audioBuffer = _this.getAudioBuffer();
  41910. clonedSound._isReadyToPlay = true;
  41911. if (clonedSound.autoplay) {
  41912. clonedSound.play();
  41913. }
  41914. }
  41915. else {
  41916. window.setTimeout(setBufferAndRun, 300);
  41917. }
  41918. };
  41919. var currentOptions = {
  41920. autoplay: this.autoplay, loop: this.loop,
  41921. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  41922. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  41923. refDistance: this.refDistance, distanceModel: this.distanceModel
  41924. };
  41925. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  41926. if (this.useCustomAttenuation) {
  41927. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  41928. }
  41929. clonedSound.setPosition(this._position);
  41930. clonedSound.setPlaybackRate(this._playbackRate);
  41931. setBufferAndRun();
  41932. return clonedSound;
  41933. }
  41934. else {
  41935. return null;
  41936. }
  41937. };
  41938. Sound.prototype.getAudioBuffer = function () {
  41939. return this._audioBuffer;
  41940. };
  41941. Sound.prototype.serialize = function () {
  41942. var serializationObject = {
  41943. name: this.name,
  41944. url: this.name,
  41945. autoplay: this.autoplay,
  41946. loop: this.loop,
  41947. volume: this._volume,
  41948. spatialSound: this.spatialSound,
  41949. maxDistance: this.maxDistance,
  41950. rolloffFactor: this.rolloffFactor,
  41951. refDistance: this.refDistance,
  41952. distanceModel: this.distanceModel,
  41953. playbackRate: this._playbackRate,
  41954. panningModel: this._panningModel,
  41955. soundTrackId: this.soundTrackId
  41956. };
  41957. if (this.spatialSound) {
  41958. if (this._connectedMesh)
  41959. serializationObject.connectedMeshId = this._connectedMesh.id;
  41960. serializationObject.position = this._position.asArray();
  41961. serializationObject.refDistance = this.refDistance;
  41962. serializationObject.distanceModel = this.distanceModel;
  41963. serializationObject.isDirectional = this._isDirectional;
  41964. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  41965. serializationObject.coneInnerAngle = this._coneInnerAngle;
  41966. serializationObject.coneOuterAngle = this._coneOuterAngle;
  41967. serializationObject.coneOuterGain = this._coneOuterGain;
  41968. }
  41969. return serializationObject;
  41970. };
  41971. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  41972. var soundName = parsedSound.name;
  41973. var soundUrl;
  41974. if (parsedSound.url) {
  41975. soundUrl = rootUrl + parsedSound.url;
  41976. }
  41977. else {
  41978. soundUrl = rootUrl + soundName;
  41979. }
  41980. var options = {
  41981. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  41982. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  41983. rolloffFactor: parsedSound.rolloffFactor,
  41984. refDistance: parsedSound.refDistance,
  41985. distanceModel: parsedSound.distanceModel,
  41986. playbackRate: parsedSound.playbackRate
  41987. };
  41988. var newSound;
  41989. if (!sourceSound) {
  41990. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  41991. scene._addPendingData(newSound);
  41992. }
  41993. else {
  41994. var setBufferAndRun = function () {
  41995. if (sourceSound._isReadyToPlay) {
  41996. newSound._audioBuffer = sourceSound.getAudioBuffer();
  41997. newSound._isReadyToPlay = true;
  41998. if (newSound.autoplay) {
  41999. newSound.play();
  42000. }
  42001. }
  42002. else {
  42003. window.setTimeout(setBufferAndRun, 300);
  42004. }
  42005. };
  42006. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  42007. setBufferAndRun();
  42008. }
  42009. if (parsedSound.position) {
  42010. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  42011. newSound.setPosition(soundPosition);
  42012. }
  42013. if (parsedSound.isDirectional) {
  42014. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  42015. if (parsedSound.localDirectionToMesh) {
  42016. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  42017. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  42018. }
  42019. }
  42020. if (parsedSound.connectedMeshId) {
  42021. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  42022. if (connectedMesh) {
  42023. newSound.attachToMesh(connectedMesh);
  42024. }
  42025. }
  42026. return newSound;
  42027. };
  42028. return Sound;
  42029. }());
  42030. BABYLON.Sound = Sound;
  42031. })(BABYLON || (BABYLON = {}));
  42032. //# sourceMappingURL=babylon.sound.js.map
  42033. var BABYLON;
  42034. (function (BABYLON) {
  42035. var SoundTrack = (function () {
  42036. function SoundTrack(scene, options) {
  42037. this.id = -1;
  42038. this._isMainTrack = false;
  42039. this._isInitialized = false;
  42040. this._scene = scene;
  42041. this.soundCollection = new Array();
  42042. this._options = options;
  42043. if (!this._isMainTrack) {
  42044. this._scene.soundTracks.push(this);
  42045. this.id = this._scene.soundTracks.length - 1;
  42046. }
  42047. }
  42048. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  42049. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42050. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  42051. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  42052. if (this._options) {
  42053. if (this._options.volume) {
  42054. this._outputAudioNode.gain.value = this._options.volume;
  42055. }
  42056. if (this._options.mainTrack) {
  42057. this._isMainTrack = this._options.mainTrack;
  42058. }
  42059. }
  42060. this._isInitialized = true;
  42061. }
  42062. };
  42063. SoundTrack.prototype.dispose = function () {
  42064. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42065. if (this._connectedAnalyser) {
  42066. this._connectedAnalyser.stopDebugCanvas();
  42067. }
  42068. while (this.soundCollection.length) {
  42069. this.soundCollection[0].dispose();
  42070. }
  42071. if (this._outputAudioNode) {
  42072. this._outputAudioNode.disconnect();
  42073. }
  42074. this._outputAudioNode = null;
  42075. }
  42076. };
  42077. SoundTrack.prototype.AddSound = function (sound) {
  42078. if (!this._isInitialized) {
  42079. this._initializeSoundTrackAudioGraph();
  42080. }
  42081. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42082. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  42083. }
  42084. if (sound.soundTrackId) {
  42085. if (sound.soundTrackId === -1) {
  42086. this._scene.mainSoundTrack.RemoveSound(sound);
  42087. }
  42088. else {
  42089. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  42090. }
  42091. }
  42092. this.soundCollection.push(sound);
  42093. sound.soundTrackId = this.id;
  42094. };
  42095. SoundTrack.prototype.RemoveSound = function (sound) {
  42096. var index = this.soundCollection.indexOf(sound);
  42097. if (index !== -1) {
  42098. this.soundCollection.splice(index, 1);
  42099. }
  42100. };
  42101. SoundTrack.prototype.setVolume = function (newVolume) {
  42102. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42103. this._outputAudioNode.gain.value = newVolume;
  42104. }
  42105. };
  42106. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  42107. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42108. for (var i = 0; i < this.soundCollection.length; i++) {
  42109. this.soundCollection[i].switchPanningModelToHRTF();
  42110. }
  42111. }
  42112. };
  42113. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  42114. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42115. for (var i = 0; i < this.soundCollection.length; i++) {
  42116. this.soundCollection[i].switchPanningModelToEqualPower();
  42117. }
  42118. }
  42119. };
  42120. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  42121. if (this._connectedAnalyser) {
  42122. this._connectedAnalyser.stopDebugCanvas();
  42123. }
  42124. this._connectedAnalyser = analyser;
  42125. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42126. this._outputAudioNode.disconnect();
  42127. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  42128. }
  42129. };
  42130. return SoundTrack;
  42131. }());
  42132. BABYLON.SoundTrack = SoundTrack;
  42133. })(BABYLON || (BABYLON = {}));
  42134. //# sourceMappingURL=babylon.soundtrack.js.map
  42135. var BABYLON;
  42136. (function (BABYLON) {
  42137. var Analyser = (function () {
  42138. function Analyser(scene) {
  42139. this.SMOOTHING = 0.75;
  42140. this.FFT_SIZE = 512;
  42141. this.BARGRAPHAMPLITUDE = 256;
  42142. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  42143. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  42144. this._scene = scene;
  42145. this._audioEngine = BABYLON.Engine.audioEngine;
  42146. if (this._audioEngine.canUseWebAudio) {
  42147. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  42148. this._webAudioAnalyser.minDecibels = -140;
  42149. this._webAudioAnalyser.maxDecibels = 0;
  42150. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42151. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42152. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  42153. }
  42154. }
  42155. Analyser.prototype.getFrequencyBinCount = function () {
  42156. if (this._audioEngine.canUseWebAudio) {
  42157. return this._webAudioAnalyser.frequencyBinCount;
  42158. }
  42159. else {
  42160. return 0;
  42161. }
  42162. };
  42163. Analyser.prototype.getByteFrequencyData = function () {
  42164. if (this._audioEngine.canUseWebAudio) {
  42165. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42166. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42167. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  42168. }
  42169. return this._byteFreqs;
  42170. };
  42171. Analyser.prototype.getByteTimeDomainData = function () {
  42172. if (this._audioEngine.canUseWebAudio) {
  42173. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42174. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42175. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  42176. }
  42177. return this._byteTime;
  42178. };
  42179. Analyser.prototype.getFloatFrequencyData = function () {
  42180. if (this._audioEngine.canUseWebAudio) {
  42181. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42182. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42183. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  42184. }
  42185. return this._floatFreqs;
  42186. };
  42187. Analyser.prototype.drawDebugCanvas = function () {
  42188. var _this = this;
  42189. if (this._audioEngine.canUseWebAudio) {
  42190. if (!this._debugCanvas) {
  42191. this._debugCanvas = document.createElement("canvas");
  42192. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  42193. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  42194. this._debugCanvas.style.position = "absolute";
  42195. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  42196. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  42197. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  42198. document.body.appendChild(this._debugCanvas);
  42199. this._registerFunc = function () {
  42200. _this.drawDebugCanvas();
  42201. };
  42202. this._scene.registerBeforeRender(this._registerFunc);
  42203. }
  42204. if (this._registerFunc) {
  42205. var workingArray = this.getByteFrequencyData();
  42206. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  42207. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  42208. // Draw the frequency domain chart.
  42209. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  42210. var value = workingArray[i];
  42211. var percent = value / this.BARGRAPHAMPLITUDE;
  42212. var height = this.DEBUGCANVASSIZE.height * percent;
  42213. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  42214. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  42215. var hue = i / this.getFrequencyBinCount() * 360;
  42216. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  42217. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  42218. }
  42219. }
  42220. }
  42221. };
  42222. Analyser.prototype.stopDebugCanvas = function () {
  42223. if (this._debugCanvas) {
  42224. this._scene.unregisterBeforeRender(this._registerFunc);
  42225. this._registerFunc = null;
  42226. document.body.removeChild(this._debugCanvas);
  42227. this._debugCanvas = null;
  42228. this._debugCanvasContext = null;
  42229. }
  42230. };
  42231. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  42232. if (this._audioEngine.canUseWebAudio) {
  42233. inputAudioNode.connect(this._webAudioAnalyser);
  42234. this._webAudioAnalyser.connect(outputAudioNode);
  42235. }
  42236. };
  42237. Analyser.prototype.dispose = function () {
  42238. if (this._audioEngine.canUseWebAudio) {
  42239. this._webAudioAnalyser.disconnect();
  42240. }
  42241. };
  42242. return Analyser;
  42243. }());
  42244. BABYLON.Analyser = Analyser;
  42245. })(BABYLON || (BABYLON = {}));
  42246. //# sourceMappingURL=babylon.analyser.js.map
  42247. var BABYLON;
  42248. (function (BABYLON) {
  42249. var CubeTexture = (function (_super) {
  42250. __extends(CubeTexture, _super);
  42251. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  42252. if (onLoad === void 0) { onLoad = null; }
  42253. if (onError === void 0) { onError = null; }
  42254. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  42255. var _this = _super.call(this, scene) || this;
  42256. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  42257. _this.name = rootUrl;
  42258. _this.url = rootUrl;
  42259. _this._noMipmap = noMipmap;
  42260. _this.hasAlpha = false;
  42261. _this._format = format;
  42262. if (!rootUrl && !files) {
  42263. return _this;
  42264. }
  42265. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  42266. if (!files) {
  42267. if (!extensions) {
  42268. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  42269. }
  42270. files = [];
  42271. for (var index = 0; index < extensions.length; index++) {
  42272. files.push(rootUrl + extensions[index]);
  42273. }
  42274. _this._extensions = extensions;
  42275. }
  42276. _this._files = files;
  42277. if (!_this._texture) {
  42278. if (!scene.useDelayedTextureLoading) {
  42279. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  42280. }
  42281. else {
  42282. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  42283. }
  42284. }
  42285. else if (onLoad) {
  42286. if (_this._texture.isReady) {
  42287. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  42288. }
  42289. else {
  42290. _this._texture.onLoadedCallbacks.push(onLoad);
  42291. }
  42292. }
  42293. _this.isCube = true;
  42294. _this._textureMatrix = BABYLON.Matrix.Identity();
  42295. return _this;
  42296. }
  42297. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  42298. return new CubeTexture("", scene, null, noMipmap, files);
  42299. };
  42300. // Methods
  42301. CubeTexture.prototype.delayLoad = function () {
  42302. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  42303. return;
  42304. }
  42305. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  42306. this._texture = this._getFromCache(this.url, this._noMipmap);
  42307. if (!this._texture) {
  42308. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  42309. }
  42310. };
  42311. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  42312. return this._textureMatrix;
  42313. };
  42314. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  42315. var texture = BABYLON.SerializationHelper.Parse(function () {
  42316. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  42317. }, parsedTexture, scene);
  42318. // Animations
  42319. if (parsedTexture.animations) {
  42320. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  42321. var parsedAnimation = parsedTexture.animations[animationIndex];
  42322. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  42323. }
  42324. }
  42325. return texture;
  42326. };
  42327. CubeTexture.prototype.clone = function () {
  42328. var _this = this;
  42329. return BABYLON.SerializationHelper.Clone(function () {
  42330. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  42331. }, this);
  42332. };
  42333. return CubeTexture;
  42334. }(BABYLON.BaseTexture));
  42335. BABYLON.CubeTexture = CubeTexture;
  42336. })(BABYLON || (BABYLON = {}));
  42337. //# sourceMappingURL=babylon.cubeTexture.js.map
  42338. var BABYLON;
  42339. (function (BABYLON) {
  42340. var RenderTargetTexture = (function (_super) {
  42341. __extends(RenderTargetTexture, _super);
  42342. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  42343. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  42344. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  42345. if (isCube === void 0) { isCube = false; }
  42346. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42347. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  42348. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  42349. if (isMulti === void 0) { isMulti = false; }
  42350. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  42351. _this.isCube = isCube;
  42352. /**
  42353. * Use this list to define the list of mesh you want to render.
  42354. */
  42355. _this.renderList = new Array();
  42356. _this.renderParticles = true;
  42357. _this.renderSprites = false;
  42358. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  42359. // Events
  42360. /**
  42361. * An event triggered when the texture is unbind.
  42362. * @type {BABYLON.Observable}
  42363. */
  42364. _this.onAfterUnbindObservable = new BABYLON.Observable();
  42365. /**
  42366. * An event triggered before rendering the texture
  42367. * @type {BABYLON.Observable}
  42368. */
  42369. _this.onBeforeRenderObservable = new BABYLON.Observable();
  42370. /**
  42371. * An event triggered after rendering the texture
  42372. * @type {BABYLON.Observable}
  42373. */
  42374. _this.onAfterRenderObservable = new BABYLON.Observable();
  42375. /**
  42376. * An event triggered after the texture clear
  42377. * @type {BABYLON.Observable}
  42378. */
  42379. _this.onClearObservable = new BABYLON.Observable();
  42380. _this._currentRefreshId = -1;
  42381. _this._refreshRate = 1;
  42382. _this._samples = 1;
  42383. _this.name = name;
  42384. _this.isRenderTarget = true;
  42385. _this._size = size;
  42386. _this._generateMipMaps = generateMipMaps;
  42387. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  42388. // Rendering groups
  42389. _this._renderingManager = new BABYLON.RenderingManager(scene);
  42390. if (isMulti) {
  42391. return _this;
  42392. }
  42393. _this._renderTargetOptions = {
  42394. generateMipMaps: generateMipMaps,
  42395. type: type,
  42396. samplingMode: samplingMode,
  42397. generateDepthBuffer: generateDepthBuffer,
  42398. generateStencilBuffer: generateStencilBuffer
  42399. };
  42400. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  42401. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42402. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42403. }
  42404. if (isCube) {
  42405. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  42406. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  42407. _this._textureMatrix = BABYLON.Matrix.Identity();
  42408. }
  42409. else {
  42410. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  42411. }
  42412. return _this;
  42413. }
  42414. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  42415. get: function () {
  42416. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  42417. },
  42418. enumerable: true,
  42419. configurable: true
  42420. });
  42421. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  42422. get: function () {
  42423. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  42424. },
  42425. enumerable: true,
  42426. configurable: true
  42427. });
  42428. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  42429. get: function () {
  42430. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  42431. },
  42432. enumerable: true,
  42433. configurable: true
  42434. });
  42435. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  42436. set: function (callback) {
  42437. if (this._onAfterUnbindObserver) {
  42438. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  42439. }
  42440. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  42441. },
  42442. enumerable: true,
  42443. configurable: true
  42444. });
  42445. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  42446. set: function (callback) {
  42447. if (this._onBeforeRenderObserver) {
  42448. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  42449. }
  42450. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  42451. },
  42452. enumerable: true,
  42453. configurable: true
  42454. });
  42455. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  42456. set: function (callback) {
  42457. if (this._onAfterRenderObserver) {
  42458. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  42459. }
  42460. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  42461. },
  42462. enumerable: true,
  42463. configurable: true
  42464. });
  42465. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  42466. set: function (callback) {
  42467. if (this._onClearObserver) {
  42468. this.onClearObservable.remove(this._onClearObserver);
  42469. }
  42470. this._onClearObserver = this.onClearObservable.add(callback);
  42471. },
  42472. enumerable: true,
  42473. configurable: true
  42474. });
  42475. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  42476. get: function () {
  42477. return this._renderTargetOptions;
  42478. },
  42479. enumerable: true,
  42480. configurable: true
  42481. });
  42482. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  42483. get: function () {
  42484. return this._samples;
  42485. },
  42486. set: function (value) {
  42487. if (this._samples === value) {
  42488. return;
  42489. }
  42490. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  42491. },
  42492. enumerable: true,
  42493. configurable: true
  42494. });
  42495. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  42496. this._currentRefreshId = -1;
  42497. };
  42498. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  42499. get: function () {
  42500. return this._refreshRate;
  42501. },
  42502. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  42503. set: function (value) {
  42504. this._refreshRate = value;
  42505. this.resetRefreshCounter();
  42506. },
  42507. enumerable: true,
  42508. configurable: true
  42509. });
  42510. RenderTargetTexture.prototype._shouldRender = function () {
  42511. if (this._currentRefreshId === -1) {
  42512. this._currentRefreshId = 1;
  42513. return true;
  42514. }
  42515. if (this.refreshRate === this._currentRefreshId) {
  42516. this._currentRefreshId = 1;
  42517. return true;
  42518. }
  42519. this._currentRefreshId++;
  42520. return false;
  42521. };
  42522. RenderTargetTexture.prototype.isReady = function () {
  42523. if (!this.getScene().renderTargetsEnabled) {
  42524. return false;
  42525. }
  42526. return _super.prototype.isReady.call(this);
  42527. };
  42528. RenderTargetTexture.prototype.getRenderSize = function () {
  42529. return this._size;
  42530. };
  42531. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  42532. get: function () {
  42533. return true;
  42534. },
  42535. enumerable: true,
  42536. configurable: true
  42537. });
  42538. RenderTargetTexture.prototype.scale = function (ratio) {
  42539. var newSize = this._size * ratio;
  42540. this.resize(newSize);
  42541. };
  42542. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  42543. if (this.isCube) {
  42544. return this._textureMatrix;
  42545. }
  42546. return _super.prototype.getReflectionTextureMatrix.call(this);
  42547. };
  42548. RenderTargetTexture.prototype.resize = function (size) {
  42549. this.releaseInternalTexture();
  42550. if (this.isCube) {
  42551. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  42552. }
  42553. else {
  42554. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  42555. }
  42556. };
  42557. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  42558. var scene = this.getScene();
  42559. var engine = scene.getEngine();
  42560. if (this.useCameraPostProcesses !== undefined) {
  42561. useCameraPostProcess = this.useCameraPostProcesses;
  42562. }
  42563. if (this._waitingRenderList) {
  42564. this.renderList = [];
  42565. for (var index = 0; index < this._waitingRenderList.length; index++) {
  42566. var id = this._waitingRenderList[index];
  42567. this.renderList.push(scene.getMeshByID(id));
  42568. }
  42569. delete this._waitingRenderList;
  42570. }
  42571. // Is predicate defined?
  42572. if (this.renderListPredicate) {
  42573. this.renderList.splice(0); // Clear previous renderList
  42574. var sceneMeshes = this.getScene().meshes;
  42575. for (var index = 0; index < sceneMeshes.length; index++) {
  42576. var mesh = sceneMeshes[index];
  42577. if (this.renderListPredicate(mesh)) {
  42578. this.renderList.push(mesh);
  42579. }
  42580. }
  42581. }
  42582. if (this.renderList && this.renderList.length === 0) {
  42583. return;
  42584. }
  42585. // Set custom projection.
  42586. // Needs to be before binding to prevent changing the aspect ratio.
  42587. if (this.activeCamera) {
  42588. engine.setViewport(this.activeCamera.viewport);
  42589. if (this.activeCamera !== scene.activeCamera) {
  42590. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  42591. }
  42592. }
  42593. else {
  42594. engine.setViewport(scene.activeCamera.viewport);
  42595. }
  42596. // Prepare renderingManager
  42597. this._renderingManager.reset();
  42598. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  42599. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  42600. var sceneRenderId = scene.getRenderId();
  42601. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  42602. var mesh = currentRenderList[meshIndex];
  42603. if (mesh) {
  42604. if (!mesh.isReady()) {
  42605. // Reset _currentRefreshId
  42606. this.resetRefreshCounter();
  42607. continue;
  42608. }
  42609. mesh._preActivateForIntermediateRendering(sceneRenderId);
  42610. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  42611. mesh._activate(sceneRenderId);
  42612. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42613. var subMesh = mesh.subMeshes[subIndex];
  42614. scene._activeIndices.addCount(subMesh.indexCount, false);
  42615. this._renderingManager.dispatch(subMesh);
  42616. }
  42617. }
  42618. }
  42619. }
  42620. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  42621. var particleSystem = scene.particleSystems[particleIndex];
  42622. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  42623. continue;
  42624. }
  42625. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  42626. this._renderingManager.dispatchParticles(particleSystem);
  42627. }
  42628. }
  42629. if (this.isCube) {
  42630. for (var face = 0; face < 6; face++) {
  42631. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  42632. scene.incrementRenderId();
  42633. scene.resetCachedMaterial();
  42634. }
  42635. }
  42636. else {
  42637. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  42638. }
  42639. this.onAfterUnbindObservable.notifyObservers(this);
  42640. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  42641. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  42642. }
  42643. engine.setViewport(scene.activeCamera.viewport);
  42644. scene.resetCachedMaterial();
  42645. };
  42646. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  42647. var _this = this;
  42648. var scene = this.getScene();
  42649. var engine = scene.getEngine();
  42650. // Bind
  42651. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  42652. if (this.isCube) {
  42653. engine.bindFramebuffer(this._texture, faceIndex);
  42654. }
  42655. else {
  42656. engine.bindFramebuffer(this._texture);
  42657. }
  42658. }
  42659. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  42660. // Clear
  42661. if (this.onClearObservable.hasObservers()) {
  42662. this.onClearObservable.notifyObservers(engine);
  42663. }
  42664. else {
  42665. engine.clear(scene.clearColor, true, true, true);
  42666. }
  42667. if (!this._doNotChangeAspectRatio) {
  42668. scene.updateTransformMatrix(true);
  42669. }
  42670. // Render
  42671. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  42672. if (useCameraPostProcess) {
  42673. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  42674. }
  42675. if (!this._doNotChangeAspectRatio) {
  42676. scene.updateTransformMatrix(true);
  42677. }
  42678. // Dump ?
  42679. if (dumpForDebug) {
  42680. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  42681. }
  42682. // Unbind
  42683. if (!this.isCube || faceIndex === 5) {
  42684. if (this.isCube) {
  42685. if (faceIndex === 5) {
  42686. engine.generateMipMapsForCubemap(this._texture);
  42687. }
  42688. }
  42689. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  42690. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  42691. });
  42692. }
  42693. else {
  42694. this.onAfterRenderObservable.notifyObservers(faceIndex);
  42695. }
  42696. };
  42697. /**
  42698. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  42699. * This allowed control for front to back rendering or reversly depending of the special needs.
  42700. *
  42701. * @param renderingGroupId The rendering group id corresponding to its index
  42702. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  42703. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  42704. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  42705. */
  42706. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  42707. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  42708. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  42709. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  42710. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  42711. };
  42712. /**
  42713. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  42714. *
  42715. * @param renderingGroupId The rendering group id corresponding to its index
  42716. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  42717. */
  42718. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  42719. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  42720. };
  42721. RenderTargetTexture.prototype.clone = function () {
  42722. var textureSize = this.getSize();
  42723. 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);
  42724. // Base texture
  42725. newTexture.hasAlpha = this.hasAlpha;
  42726. newTexture.level = this.level;
  42727. // RenderTarget Texture
  42728. newTexture.coordinatesMode = this.coordinatesMode;
  42729. newTexture.renderList = this.renderList.slice(0);
  42730. return newTexture;
  42731. };
  42732. RenderTargetTexture.prototype.serialize = function () {
  42733. if (!this.name) {
  42734. return null;
  42735. }
  42736. var serializationObject = _super.prototype.serialize.call(this);
  42737. serializationObject.renderTargetSize = this.getRenderSize();
  42738. serializationObject.renderList = [];
  42739. for (var index = 0; index < this.renderList.length; index++) {
  42740. serializationObject.renderList.push(this.renderList[index].id);
  42741. }
  42742. return serializationObject;
  42743. };
  42744. RenderTargetTexture.prototype.dispose = function () {
  42745. _super.prototype.dispose.call(this);
  42746. };
  42747. return RenderTargetTexture;
  42748. }(BABYLON.Texture));
  42749. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  42750. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  42751. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  42752. BABYLON.RenderTargetTexture = RenderTargetTexture;
  42753. })(BABYLON || (BABYLON = {}));
  42754. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  42755. var BABYLON;
  42756. (function (BABYLON) {
  42757. ;
  42758. var MultiRenderTarget = (function (_super) {
  42759. __extends(MultiRenderTarget, _super);
  42760. function MultiRenderTarget(name, size, count, scene, options) {
  42761. var _this = this;
  42762. options = options || {};
  42763. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  42764. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  42765. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  42766. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  42767. if (!_this.isSupported) {
  42768. _this.dispose();
  42769. return;
  42770. }
  42771. var types = [];
  42772. var samplingModes = [];
  42773. for (var i = 0; i < count; i++) {
  42774. if (options.types && options.types[i]) {
  42775. types.push(options.types[i]);
  42776. }
  42777. else {
  42778. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  42779. }
  42780. if (options.samplingModes && options.samplingModes[i]) {
  42781. samplingModes.push(options.samplingModes[i]);
  42782. }
  42783. else {
  42784. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42785. }
  42786. }
  42787. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  42788. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  42789. _this._count = count;
  42790. _this._size = size;
  42791. _this._multiRenderTargetOptions = {
  42792. samplingModes: samplingModes,
  42793. generateMipMaps: generateMipMaps,
  42794. generateDepthBuffer: generateDepthBuffer,
  42795. generateStencilBuffer: generateStencilBuffer,
  42796. generateDepthTexture: generateDepthTexture,
  42797. types: types,
  42798. textureCount: count
  42799. };
  42800. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  42801. _this._createInternalTextures();
  42802. return _this;
  42803. }
  42804. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  42805. get: function () {
  42806. var engine = this.getScene().getEngine();
  42807. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  42808. },
  42809. enumerable: true,
  42810. configurable: true
  42811. });
  42812. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  42813. get: function () {
  42814. return this._textures;
  42815. },
  42816. enumerable: true,
  42817. configurable: true
  42818. });
  42819. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  42820. get: function () {
  42821. return this._textures[this._textures.length - 1];
  42822. },
  42823. enumerable: true,
  42824. configurable: true
  42825. });
  42826. MultiRenderTarget.prototype._createInternalTextures = function () {
  42827. this._textures = [];
  42828. for (var i = 0; i < this._webGLTextures.length; i++) {
  42829. var texture = new BABYLON.Texture(null, this.getScene());
  42830. texture._texture = this._webGLTextures[i];
  42831. this._textures.push(texture);
  42832. }
  42833. // Keeps references to frame buffer and stencil/depth buffer
  42834. this._texture = this._webGLTextures[0];
  42835. };
  42836. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  42837. get: function () {
  42838. return this._samples;
  42839. },
  42840. set: function (value) {
  42841. if (this._samples === value) {
  42842. return;
  42843. }
  42844. for (var i = 0; i < this._webGLTextures.length; i++) {
  42845. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  42846. }
  42847. },
  42848. enumerable: true,
  42849. configurable: true
  42850. });
  42851. MultiRenderTarget.prototype.resize = function (size) {
  42852. this.releaseInternalTextures();
  42853. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  42854. this._createInternalTextures();
  42855. };
  42856. MultiRenderTarget.prototype.dispose = function () {
  42857. this.releaseInternalTextures();
  42858. _super.prototype.dispose.call(this);
  42859. };
  42860. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  42861. if (!this._webGLTextures) {
  42862. return;
  42863. }
  42864. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  42865. if (this._webGLTextures[i] !== undefined) {
  42866. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  42867. this._webGLTextures.splice(i, 1);
  42868. }
  42869. }
  42870. };
  42871. return MultiRenderTarget;
  42872. }(BABYLON.RenderTargetTexture));
  42873. BABYLON.MultiRenderTarget = MultiRenderTarget;
  42874. })(BABYLON || (BABYLON = {}));
  42875. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  42876. /// <reference path="babylon.renderTargetTexture.ts" />
  42877. var BABYLON;
  42878. (function (BABYLON) {
  42879. var MirrorTexture = (function (_super) {
  42880. __extends(MirrorTexture, _super);
  42881. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  42882. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  42883. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  42884. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  42885. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  42886. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  42887. _this._transformMatrix = BABYLON.Matrix.Zero();
  42888. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  42889. _this.onBeforeRenderObservable.add(function () {
  42890. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  42891. _this._savedViewMatrix = scene.getViewMatrix();
  42892. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  42893. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  42894. scene.clipPlane = _this.mirrorPlane;
  42895. scene.getEngine().cullBackFaces = false;
  42896. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  42897. });
  42898. _this.onAfterRenderObservable.add(function () {
  42899. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  42900. scene.getEngine().cullBackFaces = true;
  42901. scene._mirroredCameraPosition = null;
  42902. delete scene.clipPlane;
  42903. });
  42904. return _this;
  42905. }
  42906. MirrorTexture.prototype.clone = function () {
  42907. var textureSize = this.getSize();
  42908. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  42909. // Base texture
  42910. newTexture.hasAlpha = this.hasAlpha;
  42911. newTexture.level = this.level;
  42912. // Mirror Texture
  42913. newTexture.mirrorPlane = this.mirrorPlane.clone();
  42914. newTexture.renderList = this.renderList.slice(0);
  42915. return newTexture;
  42916. };
  42917. MirrorTexture.prototype.serialize = function () {
  42918. if (!this.name) {
  42919. return null;
  42920. }
  42921. var serializationObject = _super.prototype.serialize.call(this);
  42922. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  42923. return serializationObject;
  42924. };
  42925. return MirrorTexture;
  42926. }(BABYLON.RenderTargetTexture));
  42927. BABYLON.MirrorTexture = MirrorTexture;
  42928. })(BABYLON || (BABYLON = {}));
  42929. //# sourceMappingURL=babylon.mirrorTexture.js.map
  42930. /// <reference path="babylon.renderTargetTexture.ts" />
  42931. var BABYLON;
  42932. (function (BABYLON) {
  42933. /**
  42934. * Creates a refraction texture used by refraction channel of the standard material.
  42935. * @param name the texture name
  42936. * @param size size of the underlying texture
  42937. * @param scene root scene
  42938. */
  42939. var RefractionTexture = (function (_super) {
  42940. __extends(RefractionTexture, _super);
  42941. function RefractionTexture(name, size, scene, generateMipMaps) {
  42942. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  42943. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  42944. _this.depth = 2.0;
  42945. _this.onBeforeRenderObservable.add(function () {
  42946. scene.clipPlane = _this.refractionPlane;
  42947. });
  42948. _this.onAfterRenderObservable.add(function () {
  42949. delete scene.clipPlane;
  42950. });
  42951. return _this;
  42952. }
  42953. RefractionTexture.prototype.clone = function () {
  42954. var textureSize = this.getSize();
  42955. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  42956. // Base texture
  42957. newTexture.hasAlpha = this.hasAlpha;
  42958. newTexture.level = this.level;
  42959. // Refraction Texture
  42960. newTexture.refractionPlane = this.refractionPlane.clone();
  42961. newTexture.renderList = this.renderList.slice(0);
  42962. newTexture.depth = this.depth;
  42963. return newTexture;
  42964. };
  42965. RefractionTexture.prototype.serialize = function () {
  42966. if (!this.name) {
  42967. return null;
  42968. }
  42969. var serializationObject = _super.prototype.serialize.call(this);
  42970. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  42971. serializationObject.depth = this.depth;
  42972. return serializationObject;
  42973. };
  42974. return RefractionTexture;
  42975. }(BABYLON.RenderTargetTexture));
  42976. BABYLON.RefractionTexture = RefractionTexture;
  42977. })(BABYLON || (BABYLON = {}));
  42978. //# sourceMappingURL=babylon.refractionTexture.js.map
  42979. /// <reference path="babylon.texture.ts" />
  42980. var BABYLON;
  42981. (function (BABYLON) {
  42982. var DynamicTexture = (function (_super) {
  42983. __extends(DynamicTexture, _super);
  42984. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  42985. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42986. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  42987. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  42988. _this.name = name;
  42989. var engine = _this.getScene().getEngine();
  42990. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42991. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42992. _this._generateMipMaps = generateMipMaps;
  42993. if (options.getContext) {
  42994. _this._canvas = options;
  42995. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  42996. }
  42997. else {
  42998. _this._canvas = document.createElement("canvas");
  42999. if (options.width) {
  43000. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  43001. }
  43002. else {
  43003. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  43004. }
  43005. }
  43006. var textureSize = _this.getSize();
  43007. _this._canvas.width = textureSize.width;
  43008. _this._canvas.height = textureSize.height;
  43009. _this._context = _this._canvas.getContext("2d");
  43010. return _this;
  43011. }
  43012. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  43013. get: function () {
  43014. return true;
  43015. },
  43016. enumerable: true,
  43017. configurable: true
  43018. });
  43019. DynamicTexture.prototype._recreate = function (textureSize) {
  43020. this._canvas.width = textureSize.width;
  43021. this._canvas.height = textureSize.height;
  43022. this.releaseInternalTexture();
  43023. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  43024. };
  43025. DynamicTexture.prototype.scale = function (ratio) {
  43026. var textureSize = this.getSize();
  43027. textureSize.width *= ratio;
  43028. textureSize.height *= ratio;
  43029. this._recreate(textureSize);
  43030. };
  43031. DynamicTexture.prototype.scaleTo = function (width, height) {
  43032. var textureSize = this.getSize();
  43033. textureSize.width = width;
  43034. textureSize.height = height;
  43035. this._recreate(textureSize);
  43036. };
  43037. DynamicTexture.prototype.getContext = function () {
  43038. return this._context;
  43039. };
  43040. DynamicTexture.prototype.clear = function () {
  43041. var size = this.getSize();
  43042. this._context.fillRect(0, 0, size.width, size.height);
  43043. };
  43044. DynamicTexture.prototype.update = function (invertY) {
  43045. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  43046. };
  43047. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  43048. if (update === void 0) { update = true; }
  43049. var size = this.getSize();
  43050. if (clearColor) {
  43051. this._context.fillStyle = clearColor;
  43052. this._context.fillRect(0, 0, size.width, size.height);
  43053. }
  43054. this._context.font = font;
  43055. if (x === null || x === undefined) {
  43056. var textSize = this._context.measureText(text);
  43057. x = (size.width - textSize.width) / 2;
  43058. }
  43059. if (y === null || y === undefined) {
  43060. var fontSize = parseInt((font.replace(/\D/g, '')));
  43061. ;
  43062. y = (size.height / 2) + (fontSize / 3.65);
  43063. }
  43064. this._context.fillStyle = color;
  43065. this._context.fillText(text, x, y);
  43066. if (update) {
  43067. this.update(invertY);
  43068. }
  43069. };
  43070. DynamicTexture.prototype.clone = function () {
  43071. var textureSize = this.getSize();
  43072. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  43073. // Base texture
  43074. newTexture.hasAlpha = this.hasAlpha;
  43075. newTexture.level = this.level;
  43076. // Dynamic Texture
  43077. newTexture.wrapU = this.wrapU;
  43078. newTexture.wrapV = this.wrapV;
  43079. return newTexture;
  43080. };
  43081. return DynamicTexture;
  43082. }(BABYLON.Texture));
  43083. BABYLON.DynamicTexture = DynamicTexture;
  43084. })(BABYLON || (BABYLON = {}));
  43085. //# sourceMappingURL=babylon.dynamicTexture.js.map
  43086. var BABYLON;
  43087. (function (BABYLON) {
  43088. var VideoTexture = (function (_super) {
  43089. __extends(VideoTexture, _super);
  43090. /**
  43091. * Creates a video texture.
  43092. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  43093. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  43094. * @param {BABYLON.Scene} scene is obviously the current scene.
  43095. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  43096. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  43097. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  43098. */
  43099. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  43100. if (generateMipMaps === void 0) { generateMipMaps = false; }
  43101. if (invertY === void 0) { invertY = false; }
  43102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43103. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  43104. _this._autoLaunch = true;
  43105. var urls;
  43106. _this.name = name;
  43107. if (urlsOrVideo instanceof HTMLVideoElement) {
  43108. _this.video = urlsOrVideo;
  43109. }
  43110. else {
  43111. urls = urlsOrVideo;
  43112. _this.video = document.createElement("video");
  43113. _this.video.autoplay = false;
  43114. _this.video.loop = true;
  43115. }
  43116. _this._generateMipMaps = generateMipMaps;
  43117. _this._samplingMode = samplingMode;
  43118. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  43119. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  43120. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  43121. }
  43122. else {
  43123. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43124. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43125. _this._generateMipMaps = false;
  43126. }
  43127. if (urls) {
  43128. _this.video.addEventListener("canplay", function () {
  43129. _this._createTexture();
  43130. });
  43131. urls.forEach(function (url) {
  43132. var source = document.createElement("source");
  43133. source.src = url;
  43134. _this.video.appendChild(source);
  43135. });
  43136. }
  43137. else {
  43138. _this._createTexture();
  43139. }
  43140. _this._lastUpdate = BABYLON.Tools.Now;
  43141. return _this;
  43142. }
  43143. VideoTexture.prototype.__setTextureReady = function () {
  43144. this._texture.isReady = true;
  43145. };
  43146. VideoTexture.prototype._createTexture = function () {
  43147. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  43148. if (this._autoLaunch) {
  43149. this._autoLaunch = false;
  43150. this.video.play();
  43151. }
  43152. this._setTextureReady = this.__setTextureReady.bind(this);
  43153. this.video.addEventListener("playing", this._setTextureReady);
  43154. };
  43155. VideoTexture.prototype.update = function () {
  43156. var now = BABYLON.Tools.Now;
  43157. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  43158. return false;
  43159. }
  43160. this._lastUpdate = now;
  43161. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  43162. return true;
  43163. };
  43164. VideoTexture.prototype.dispose = function () {
  43165. _super.prototype.dispose.call(this);
  43166. this.video.removeEventListener("playing", this._setTextureReady);
  43167. };
  43168. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  43169. var video = document.createElement("video");
  43170. var constraintsDeviceId;
  43171. if (constraints && constraints.deviceId) {
  43172. constraintsDeviceId = {
  43173. exact: constraints.deviceId
  43174. };
  43175. }
  43176. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  43177. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  43178. if (navigator.getUserMedia) {
  43179. navigator.getUserMedia({
  43180. video: {
  43181. deviceId: constraintsDeviceId,
  43182. width: {
  43183. min: (constraints && constraints.minWidth) || 256,
  43184. max: (constraints && constraints.maxWidth) || 640
  43185. },
  43186. height: {
  43187. min: (constraints && constraints.minHeight) || 256,
  43188. max: (constraints && constraints.maxHeight) || 480
  43189. }
  43190. }
  43191. }, function (stream) {
  43192. if (video.mozSrcObject !== undefined) {
  43193. video.mozSrcObject = stream;
  43194. }
  43195. else {
  43196. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  43197. }
  43198. video.play();
  43199. if (onReady) {
  43200. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  43201. }
  43202. }, function (e) {
  43203. BABYLON.Tools.Error(e.name);
  43204. });
  43205. }
  43206. };
  43207. return VideoTexture;
  43208. }(BABYLON.Texture));
  43209. BABYLON.VideoTexture = VideoTexture;
  43210. })(BABYLON || (BABYLON = {}));
  43211. //# sourceMappingURL=babylon.videoTexture.js.map
  43212. var BABYLON;
  43213. (function (BABYLON) {
  43214. var RawTexture = (function (_super) {
  43215. __extends(RawTexture, _super);
  43216. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  43217. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43218. if (invertY === void 0) { invertY = false; }
  43219. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43220. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  43221. _this.format = format;
  43222. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  43223. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43224. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43225. return _this;
  43226. }
  43227. RawTexture.prototype.update = function (data) {
  43228. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  43229. };
  43230. // Statics
  43231. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43232. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43233. if (invertY === void 0) { invertY = false; }
  43234. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43235. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  43236. };
  43237. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43238. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43239. if (invertY === void 0) { invertY = false; }
  43240. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43241. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43242. };
  43243. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43244. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43245. if (invertY === void 0) { invertY = false; }
  43246. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43247. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43248. };
  43249. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43250. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43251. if (invertY === void 0) { invertY = false; }
  43252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43253. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  43254. };
  43255. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43256. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43257. if (invertY === void 0) { invertY = false; }
  43258. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43259. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  43260. };
  43261. return RawTexture;
  43262. }(BABYLON.Texture));
  43263. BABYLON.RawTexture = RawTexture;
  43264. })(BABYLON || (BABYLON = {}));
  43265. //# sourceMappingURL=babylon.rawTexture.js.map
  43266. var BABYLON;
  43267. (function (BABYLON) {
  43268. var PostProcess = (function () {
  43269. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  43270. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  43271. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43272. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  43273. if (blockCompilation === void 0) { blockCompilation = false; }
  43274. this.name = name;
  43275. this.width = -1;
  43276. this.height = -1;
  43277. this.autoClear = true;
  43278. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  43279. /*
  43280. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  43281. Can only be used on a single postprocess or on the last one of a chain.
  43282. */
  43283. this.enablePixelPerfectMode = false;
  43284. this.samples = 1;
  43285. this._reusable = false;
  43286. this._textures = new BABYLON.SmartArray(2);
  43287. this._currentRenderTextureInd = 0;
  43288. this._scaleRatio = new BABYLON.Vector2(1, 1);
  43289. // Events
  43290. /**
  43291. * An event triggered when the postprocess is activated.
  43292. * @type {BABYLON.Observable}
  43293. */
  43294. this.onActivateObservable = new BABYLON.Observable();
  43295. /**
  43296. * An event triggered when the postprocess changes its size.
  43297. * @type {BABYLON.Observable}
  43298. */
  43299. this.onSizeChangedObservable = new BABYLON.Observable();
  43300. /**
  43301. * An event triggered when the postprocess applies its effect.
  43302. * @type {BABYLON.Observable}
  43303. */
  43304. this.onApplyObservable = new BABYLON.Observable();
  43305. /**
  43306. * An event triggered before rendering the postprocess
  43307. * @type {BABYLON.Observable}
  43308. */
  43309. this.onBeforeRenderObservable = new BABYLON.Observable();
  43310. /**
  43311. * An event triggered after rendering the postprocess
  43312. * @type {BABYLON.Observable}
  43313. */
  43314. this.onAfterRenderObservable = new BABYLON.Observable();
  43315. if (camera != null) {
  43316. this._camera = camera;
  43317. this._scene = camera.getScene();
  43318. camera.attachPostProcess(this);
  43319. this._engine = this._scene.getEngine();
  43320. }
  43321. else {
  43322. this._engine = engine;
  43323. }
  43324. this._options = options;
  43325. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  43326. this._reusable = reusable || false;
  43327. this._textureType = textureType;
  43328. this._samplers = samplers || [];
  43329. this._samplers.push("textureSampler");
  43330. this._fragmentUrl = fragmentUrl;
  43331. this._vertexUrl = vertexUrl;
  43332. this._parameters = parameters || [];
  43333. this._parameters.push("scale");
  43334. this._indexParameters = indexParameters;
  43335. if (!blockCompilation) {
  43336. this.updateEffect(defines);
  43337. }
  43338. }
  43339. Object.defineProperty(PostProcess.prototype, "onActivate", {
  43340. set: function (callback) {
  43341. if (this._onActivateObserver) {
  43342. this.onActivateObservable.remove(this._onActivateObserver);
  43343. }
  43344. this._onActivateObserver = this.onActivateObservable.add(callback);
  43345. },
  43346. enumerable: true,
  43347. configurable: true
  43348. });
  43349. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  43350. set: function (callback) {
  43351. if (this._onSizeChangedObserver) {
  43352. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  43353. }
  43354. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  43355. },
  43356. enumerable: true,
  43357. configurable: true
  43358. });
  43359. Object.defineProperty(PostProcess.prototype, "onApply", {
  43360. set: function (callback) {
  43361. if (this._onApplyObserver) {
  43362. this.onApplyObservable.remove(this._onApplyObserver);
  43363. }
  43364. this._onApplyObserver = this.onApplyObservable.add(callback);
  43365. },
  43366. enumerable: true,
  43367. configurable: true
  43368. });
  43369. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  43370. set: function (callback) {
  43371. if (this._onBeforeRenderObserver) {
  43372. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  43373. }
  43374. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  43375. },
  43376. enumerable: true,
  43377. configurable: true
  43378. });
  43379. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  43380. set: function (callback) {
  43381. if (this._onAfterRenderObserver) {
  43382. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  43383. }
  43384. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  43385. },
  43386. enumerable: true,
  43387. configurable: true
  43388. });
  43389. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  43390. get: function () {
  43391. return this._textures.data[this._currentRenderTextureInd];
  43392. },
  43393. enumerable: true,
  43394. configurable: true
  43395. });
  43396. PostProcess.prototype.getCamera = function () {
  43397. return this._camera;
  43398. };
  43399. PostProcess.prototype.getEngine = function () {
  43400. return this._engine;
  43401. };
  43402. PostProcess.prototype.shareOutputWith = function (postProcess) {
  43403. this._disposeTextures();
  43404. this._shareOutputWithPostProcess = postProcess;
  43405. return this;
  43406. };
  43407. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters) {
  43408. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, null, null, indexParameters || this._indexParameters);
  43409. };
  43410. PostProcess.prototype.isReusable = function () {
  43411. return this._reusable;
  43412. };
  43413. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  43414. PostProcess.prototype.markTextureDirty = function () {
  43415. this.width = -1;
  43416. };
  43417. PostProcess.prototype.activate = function (camera, sourceTexture) {
  43418. var _this = this;
  43419. if (!this._shareOutputWithPostProcess) {
  43420. camera = camera || this._camera;
  43421. var scene = camera.getScene();
  43422. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  43423. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  43424. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  43425. var desiredWidth = this._options.width || requiredWidth;
  43426. var desiredHeight = this._options.height || requiredHeight;
  43427. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  43428. if (!this._options.width) {
  43429. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  43430. }
  43431. if (!this._options.height) {
  43432. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  43433. }
  43434. }
  43435. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  43436. if (this._textures.length > 0) {
  43437. for (var i = 0; i < this._textures.length; i++) {
  43438. this._engine._releaseTexture(this._textures.data[i]);
  43439. }
  43440. this._textures.reset();
  43441. }
  43442. this.width = desiredWidth;
  43443. this.height = desiredHeight;
  43444. var textureSize = { width: this.width, height: this.height };
  43445. var textureOptions = {
  43446. generateMipMaps: false,
  43447. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  43448. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  43449. samplingMode: this.renderTargetSamplingMode,
  43450. type: this._textureType
  43451. };
  43452. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  43453. if (this._reusable) {
  43454. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  43455. }
  43456. this.onSizeChangedObservable.notifyObservers(this);
  43457. }
  43458. this._textures.forEach(function (texture) {
  43459. if (texture.samples !== _this.samples) {
  43460. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  43461. }
  43462. });
  43463. }
  43464. var target = this._shareOutputWithPostProcess ? this._shareOutputWithPostProcess.outputTexture : this.outputTexture;
  43465. if (this.enablePixelPerfectMode) {
  43466. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  43467. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  43468. }
  43469. else {
  43470. this._scaleRatio.copyFromFloats(1, 1);
  43471. this._engine.bindFramebuffer(target);
  43472. }
  43473. this.onActivateObservable.notifyObservers(camera);
  43474. // Clear
  43475. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  43476. if (this.clearColor) {
  43477. this._engine.clear(this.clearColor, true, true, true);
  43478. }
  43479. else {
  43480. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  43481. }
  43482. }
  43483. if (this._reusable) {
  43484. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  43485. }
  43486. };
  43487. Object.defineProperty(PostProcess.prototype, "isSupported", {
  43488. get: function () {
  43489. return this._effect.isSupported;
  43490. },
  43491. enumerable: true,
  43492. configurable: true
  43493. });
  43494. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  43495. get: function () {
  43496. if (this._shareOutputWithPostProcess) {
  43497. return this._shareOutputWithPostProcess.aspectRatio;
  43498. }
  43499. return this.width / this.height;
  43500. },
  43501. enumerable: true,
  43502. configurable: true
  43503. });
  43504. PostProcess.prototype.apply = function () {
  43505. // Check
  43506. if (!this._effect || !this._effect.isReady())
  43507. return null;
  43508. // States
  43509. this._engine.enableEffect(this._effect);
  43510. this._engine.setState(false);
  43511. this._engine.setDepthBuffer(false);
  43512. this._engine.setDepthWrite(false);
  43513. // Alpha
  43514. this._engine.setAlphaMode(this.alphaMode);
  43515. if (this.alphaConstants) {
  43516. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  43517. }
  43518. // Texture
  43519. var source = this._shareOutputWithPostProcess ? this._shareOutputWithPostProcess.outputTexture : this.outputTexture;
  43520. this._effect._bindTexture("textureSampler", source);
  43521. // Parameters
  43522. this._effect.setVector2("scale", this._scaleRatio);
  43523. this.onApplyObservable.notifyObservers(this._effect);
  43524. return this._effect;
  43525. };
  43526. PostProcess.prototype._disposeTextures = function () {
  43527. if (this._shareOutputWithPostProcess) {
  43528. return;
  43529. }
  43530. if (this._textures.length > 0) {
  43531. for (var i = 0; i < this._textures.length; i++) {
  43532. this._engine._releaseTexture(this._textures.data[i]);
  43533. }
  43534. }
  43535. this._textures.dispose();
  43536. };
  43537. PostProcess.prototype.dispose = function (camera) {
  43538. camera = camera || this._camera;
  43539. this._disposeTextures();
  43540. if (!camera) {
  43541. return;
  43542. }
  43543. camera.detachPostProcess(this);
  43544. var index = camera._postProcesses.indexOf(this);
  43545. if (index === 0 && camera._postProcesses.length > 0) {
  43546. this._camera._postProcesses[0].markTextureDirty();
  43547. }
  43548. this.onActivateObservable.clear();
  43549. this.onAfterRenderObservable.clear();
  43550. this.onApplyObservable.clear();
  43551. this.onBeforeRenderObservable.clear();
  43552. this.onSizeChangedObservable.clear();
  43553. };
  43554. return PostProcess;
  43555. }());
  43556. BABYLON.PostProcess = PostProcess;
  43557. })(BABYLON || (BABYLON = {}));
  43558. //# sourceMappingURL=babylon.postProcess.js.map
  43559. var BABYLON;
  43560. (function (BABYLON) {
  43561. var PassPostProcess = (function (_super) {
  43562. __extends(PassPostProcess, _super);
  43563. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  43564. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43565. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  43566. }
  43567. return PassPostProcess;
  43568. }(BABYLON.PostProcess));
  43569. BABYLON.PassPostProcess = PassPostProcess;
  43570. })(BABYLON || (BABYLON = {}));
  43571. //# sourceMappingURL=babylon.passPostProcess.js.map
  43572. var BABYLON;
  43573. (function (BABYLON) {
  43574. var ShadowGenerator = (function () {
  43575. /**
  43576. * Creates a ShadowGenerator object.
  43577. * A ShadowGenerator is the required tool to use the shadows.
  43578. * Each light casting shadows needs to use its own ShadowGenerator.
  43579. * Required parameters :
  43580. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  43581. * - `light` : the light object generating the shadows.
  43582. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  43583. */
  43584. function ShadowGenerator(mapSize, light) {
  43585. // Members
  43586. this._filter = ShadowGenerator.FILTER_NONE;
  43587. this.blurScale = 2;
  43588. this._blurBoxOffset = 0;
  43589. this._bias = 0.00005;
  43590. this._lightDirection = BABYLON.Vector3.Zero();
  43591. this.forceBackFacesOnly = false;
  43592. this._darkness = 0;
  43593. this._transparencyShadow = false;
  43594. this._viewMatrix = BABYLON.Matrix.Zero();
  43595. this._projectionMatrix = BABYLON.Matrix.Zero();
  43596. this._transformMatrix = BABYLON.Matrix.Zero();
  43597. this._worldViewProjection = BABYLON.Matrix.Zero();
  43598. this._currentFaceIndex = 0;
  43599. this._currentFaceIndexCache = 0;
  43600. this._useFullFloat = true;
  43601. this._isCube = false;
  43602. this._mapSize = mapSize;
  43603. this._light = light;
  43604. this._scene = light.getScene();
  43605. light._shadowGenerator = this;
  43606. // Texture type fallback from float to int if not supported.
  43607. var caps = this._scene.getEngine().getCaps();
  43608. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  43609. this._useFullFloat = true;
  43610. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43611. }
  43612. else {
  43613. this._useFullFloat = false;
  43614. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43615. }
  43616. this._initializeGenerator(1);
  43617. }
  43618. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  43619. // Static
  43620. get: function () {
  43621. return ShadowGenerator._FILTER_NONE;
  43622. },
  43623. enumerable: true,
  43624. configurable: true
  43625. });
  43626. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  43627. get: function () {
  43628. return ShadowGenerator._FILTER_POISSONSAMPLING;
  43629. },
  43630. enumerable: true,
  43631. configurable: true
  43632. });
  43633. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  43634. get: function () {
  43635. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  43636. },
  43637. enumerable: true,
  43638. configurable: true
  43639. });
  43640. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  43641. get: function () {
  43642. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  43643. },
  43644. enumerable: true,
  43645. configurable: true
  43646. });
  43647. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  43648. get: function () {
  43649. return this._bias;
  43650. },
  43651. set: function (bias) {
  43652. this._bias = bias;
  43653. },
  43654. enumerable: true,
  43655. configurable: true
  43656. });
  43657. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  43658. get: function () {
  43659. return this._blurBoxOffset;
  43660. },
  43661. set: function (value) {
  43662. var _this = this;
  43663. if (this._blurBoxOffset === value) {
  43664. return;
  43665. }
  43666. this._blurBoxOffset = value;
  43667. if (this._boxBlurPostprocess) {
  43668. this._boxBlurPostprocess.dispose();
  43669. }
  43670. var textureType;
  43671. var caps = this._scene.getEngine().getCaps();
  43672. if (this._useFullFloat) {
  43673. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43674. }
  43675. else {
  43676. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43677. }
  43678. 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);
  43679. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  43680. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  43681. });
  43682. },
  43683. enumerable: true,
  43684. configurable: true
  43685. });
  43686. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  43687. get: function () {
  43688. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  43689. },
  43690. set: function (value) {
  43691. this._depthScale = value;
  43692. },
  43693. enumerable: true,
  43694. configurable: true
  43695. });
  43696. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  43697. get: function () {
  43698. return this._filter;
  43699. },
  43700. set: function (value) {
  43701. if (this._filter === value) {
  43702. return;
  43703. }
  43704. this._filter = value;
  43705. this._applyFilterValues();
  43706. this._light._markMeshesAsLightDirty();
  43707. },
  43708. enumerable: true,
  43709. configurable: true
  43710. });
  43711. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  43712. get: function () {
  43713. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  43714. return this.useExponentialShadowMap;
  43715. },
  43716. set: function (value) {
  43717. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  43718. this.useExponentialShadowMap = value;
  43719. },
  43720. enumerable: true,
  43721. configurable: true
  43722. });
  43723. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  43724. get: function () {
  43725. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  43726. },
  43727. set: function (value) {
  43728. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  43729. },
  43730. enumerable: true,
  43731. configurable: true
  43732. });
  43733. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  43734. get: function () {
  43735. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  43736. },
  43737. set: function (value) {
  43738. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  43739. },
  43740. enumerable: true,
  43741. configurable: true
  43742. });
  43743. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  43744. get: function () {
  43745. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  43746. return this.useBlurExponentialShadowMap;
  43747. },
  43748. set: function (value) {
  43749. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  43750. this.useBlurExponentialShadowMap = value;
  43751. },
  43752. enumerable: true,
  43753. configurable: true
  43754. });
  43755. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  43756. get: function () {
  43757. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  43758. },
  43759. set: function (value) {
  43760. if (this._light.needCube() && value) {
  43761. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  43762. }
  43763. else {
  43764. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  43765. }
  43766. },
  43767. enumerable: true,
  43768. configurable: true
  43769. });
  43770. ShadowGenerator.prototype._initializeGenerator = function (boxBlurOffset) {
  43771. var _this = this;
  43772. var light = this._light;
  43773. var scene = this._scene;
  43774. var textureType = this._textureType;
  43775. light._markMeshesAsLightDirty();
  43776. // Render target
  43777. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", this._mapSize, this._scene, false, true, textureType, light.needCube());
  43778. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43779. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43780. this._shadowMap.anisotropicFilteringLevel = 1;
  43781. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43782. this._shadowMap.renderParticles = false;
  43783. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  43784. _this._currentFaceIndex = faceIndex;
  43785. });
  43786. this._shadowMap.onAfterUnbindObservable.add(function () {
  43787. if (!_this.useBlurExponentialShadowMap) {
  43788. return;
  43789. }
  43790. if (!_this._shadowMap2) {
  43791. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", _this._mapSize, _this._scene, false, true, textureType);
  43792. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43793. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43794. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43795. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  43796. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  43797. effect.setTexture("textureSampler", _this._shadowMap);
  43798. });
  43799. _this.blurBoxOffset = boxBlurOffset;
  43800. }
  43801. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  43802. });
  43803. // Custom render function
  43804. var renderSubMesh = function (subMesh) {
  43805. var mesh = subMesh.getRenderingMesh();
  43806. var scene = _this._scene;
  43807. var engine = scene.getEngine();
  43808. // Culling
  43809. engine.setState(subMesh.getMaterial().backFaceCulling);
  43810. // Managing instances
  43811. var batch = mesh._getInstancesRenderList(subMesh._id);
  43812. if (batch.mustReturn) {
  43813. return;
  43814. }
  43815. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  43816. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  43817. engine.enableEffect(_this._effect);
  43818. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  43819. var material = subMesh.getMaterial();
  43820. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  43821. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  43822. _this._effect.setVector3("lightPosition", _this.getLight().position);
  43823. if (_this.getLight().needCube()) {
  43824. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  43825. }
  43826. // Alpha test
  43827. if (material && material.needAlphaTesting()) {
  43828. var alphaTexture = material.getAlphaTestTexture();
  43829. _this._effect.setTexture("diffuseSampler", alphaTexture);
  43830. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  43831. }
  43832. // Bones
  43833. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43834. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43835. }
  43836. if (_this.forceBackFacesOnly) {
  43837. engine.setState(true, 0, false, true);
  43838. }
  43839. // Draw
  43840. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  43841. if (_this.forceBackFacesOnly) {
  43842. engine.setState(true, 0, false, false);
  43843. }
  43844. }
  43845. else {
  43846. // Need to reset refresh rate of the shadowMap
  43847. _this._shadowMap.resetRefreshCounter();
  43848. }
  43849. };
  43850. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  43851. var index;
  43852. for (index = 0; index < opaqueSubMeshes.length; index++) {
  43853. renderSubMesh(opaqueSubMeshes.data[index]);
  43854. }
  43855. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  43856. renderSubMesh(alphaTestSubMeshes.data[index]);
  43857. }
  43858. if (_this._transparencyShadow) {
  43859. for (index = 0; index < transparentSubMeshes.length; index++) {
  43860. renderSubMesh(transparentSubMeshes.data[index]);
  43861. }
  43862. }
  43863. };
  43864. this._shadowMap.onClearObservable.add(function (engine) {
  43865. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  43866. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  43867. }
  43868. else {
  43869. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  43870. }
  43871. });
  43872. };
  43873. ShadowGenerator.prototype._applyFilterValues = function () {
  43874. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  43875. this._shadowMap.anisotropicFilteringLevel = 16;
  43876. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43877. }
  43878. else {
  43879. this._shadowMap.anisotropicFilteringLevel = 1;
  43880. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  43881. }
  43882. };
  43883. ShadowGenerator.prototype.recreateShadowMap = function () {
  43884. // Clean up existing data.
  43885. this._disposeRTTandPostProcesses();
  43886. // Reinitializes.
  43887. this._initializeGenerator(this.blurBoxOffset);
  43888. // Reaffect the filter.
  43889. this._applyFilterValues();
  43890. };
  43891. /**
  43892. * Boolean : true when the ShadowGenerator is finally computed.
  43893. */
  43894. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  43895. var defines = [];
  43896. if (this._useFullFloat) {
  43897. defines.push("#define FULLFLOAT");
  43898. }
  43899. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  43900. defines.push("#define ESM");
  43901. }
  43902. if (this.getLight().needCube()) {
  43903. defines.push("#define CUBEMAP");
  43904. }
  43905. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43906. var mesh = subMesh.getMesh();
  43907. var material = subMesh.getMaterial();
  43908. // Alpha test
  43909. if (material && material.needAlphaTesting()) {
  43910. defines.push("#define ALPHATEST");
  43911. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43912. attribs.push(BABYLON.VertexBuffer.UVKind);
  43913. defines.push("#define UV1");
  43914. }
  43915. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  43916. var alphaTexture = material.getAlphaTestTexture();
  43917. if (alphaTexture.coordinatesIndex === 1) {
  43918. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43919. defines.push("#define UV2");
  43920. }
  43921. }
  43922. }
  43923. // Bones
  43924. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43925. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43926. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43927. if (mesh.numBoneInfluencers > 4) {
  43928. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43929. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43930. }
  43931. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43932. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43933. }
  43934. else {
  43935. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43936. }
  43937. // Instances
  43938. if (useInstances) {
  43939. defines.push("#define INSTANCES");
  43940. attribs.push("world0");
  43941. attribs.push("world1");
  43942. attribs.push("world2");
  43943. attribs.push("world3");
  43944. }
  43945. // Get correct effect
  43946. var join = defines.join("\n");
  43947. if (this._cachedDefines !== join) {
  43948. this._cachedDefines = join;
  43949. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  43950. }
  43951. return this._effect.isReady();
  43952. };
  43953. /**
  43954. * Returns a RenderTargetTexture object : the shadow map texture.
  43955. */
  43956. ShadowGenerator.prototype.getShadowMap = function () {
  43957. return this._shadowMap;
  43958. };
  43959. /**
  43960. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  43961. */
  43962. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  43963. if (this._shadowMap2) {
  43964. return this._shadowMap2;
  43965. }
  43966. return this._shadowMap;
  43967. };
  43968. /**
  43969. * Returns the associated light object.
  43970. */
  43971. ShadowGenerator.prototype.getLight = function () {
  43972. return this._light;
  43973. };
  43974. // Methods
  43975. /**
  43976. * Returns a Matrix object : the updated transformation matrix.
  43977. */
  43978. ShadowGenerator.prototype.getTransformMatrix = function () {
  43979. var scene = this._scene;
  43980. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  43981. return this._transformMatrix;
  43982. }
  43983. this._currentRenderID = scene.getRenderId();
  43984. this._currentFaceIndexCache = this._currentFaceIndex;
  43985. var lightPosition = this._light.position;
  43986. if (this._light.computeTransformedInformation()) {
  43987. lightPosition = this._light.transformedPosition;
  43988. }
  43989. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  43990. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  43991. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  43992. }
  43993. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  43994. this._cachedPosition = lightPosition.clone();
  43995. this._cachedDirection = this._lightDirection.clone();
  43996. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  43997. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  43998. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  43999. }
  44000. return this._transformMatrix;
  44001. };
  44002. /**
  44003. * Returns the darkness value (float).
  44004. */
  44005. ShadowGenerator.prototype.getDarkness = function () {
  44006. return this._darkness;
  44007. };
  44008. /**
  44009. * Sets the ShadowGenerator darkness value (float <= 1.0).
  44010. * Returns the ShadowGenerator.
  44011. */
  44012. ShadowGenerator.prototype.setDarkness = function (darkness) {
  44013. if (darkness >= 1.0)
  44014. this._darkness = 1.0;
  44015. else if (darkness <= 0.0)
  44016. this._darkness = 0.0;
  44017. else
  44018. this._darkness = darkness;
  44019. return this;
  44020. };
  44021. /**
  44022. * Sets the ability to have transparent shadow (boolean).
  44023. * Returns the ShadowGenerator.
  44024. */
  44025. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  44026. this._transparencyShadow = hasShadow;
  44027. return this;
  44028. };
  44029. ShadowGenerator.prototype._packHalf = function (depth) {
  44030. var scale = depth * 255.0;
  44031. var fract = scale - Math.floor(scale);
  44032. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  44033. };
  44034. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  44035. if (this._shadowMap) {
  44036. this._shadowMap.dispose();
  44037. }
  44038. if (this._shadowMap2) {
  44039. this._shadowMap2.dispose();
  44040. }
  44041. if (this._downSamplePostprocess) {
  44042. this._downSamplePostprocess.dispose();
  44043. }
  44044. if (this._boxBlurPostprocess) {
  44045. this._boxBlurPostprocess.dispose();
  44046. }
  44047. };
  44048. /**
  44049. * Disposes the ShadowGenerator.
  44050. * Returns nothing.
  44051. */
  44052. ShadowGenerator.prototype.dispose = function () {
  44053. this._disposeRTTandPostProcesses();
  44054. this._light._shadowGenerator = null;
  44055. this._light._markMeshesAsLightDirty();
  44056. };
  44057. /**
  44058. * Serializes the ShadowGenerator and returns a serializationObject.
  44059. */
  44060. ShadowGenerator.prototype.serialize = function () {
  44061. var serializationObject = {};
  44062. var shadowMap = this.getShadowMap();
  44063. serializationObject.lightId = this._light.id;
  44064. serializationObject.mapSize = shadowMap.getRenderSize();
  44065. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  44066. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  44067. serializationObject.usePoissonSampling = this.usePoissonSampling;
  44068. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  44069. serializationObject.depthScale = this.depthScale;
  44070. serializationObject.darkness = this.getDarkness();
  44071. serializationObject.renderList = [];
  44072. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  44073. var mesh = shadowMap.renderList[meshIndex];
  44074. serializationObject.renderList.push(mesh.id);
  44075. }
  44076. return serializationObject;
  44077. };
  44078. /**
  44079. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  44080. */
  44081. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  44082. //casting to point light, as light is missing the position attr and typescript complains.
  44083. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  44084. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  44085. var shadowMap = shadowGenerator.getShadowMap();
  44086. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  44087. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  44088. meshes.forEach(function (mesh) {
  44089. shadowMap.renderList.push(mesh);
  44090. });
  44091. }
  44092. if (parsedShadowGenerator.usePoissonSampling) {
  44093. shadowGenerator.usePoissonSampling = true;
  44094. }
  44095. else if (parsedShadowGenerator.useExponentialShadowMap) {
  44096. shadowGenerator.useExponentialShadowMap = true;
  44097. }
  44098. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  44099. shadowGenerator.useBlurExponentialShadowMap = true;
  44100. }
  44101. else if (parsedShadowGenerator.useVarianceShadowMap) {
  44102. shadowGenerator.useExponentialShadowMap = true;
  44103. }
  44104. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  44105. shadowGenerator.useBlurExponentialShadowMap = true;
  44106. }
  44107. if (parsedShadowGenerator.depthScale) {
  44108. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  44109. }
  44110. if (parsedShadowGenerator.blurScale) {
  44111. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  44112. }
  44113. if (parsedShadowGenerator.blurBoxOffset) {
  44114. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  44115. }
  44116. if (parsedShadowGenerator.bias !== undefined) {
  44117. shadowGenerator.bias = parsedShadowGenerator.bias;
  44118. }
  44119. if (parsedShadowGenerator.darkness) {
  44120. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  44121. }
  44122. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  44123. return shadowGenerator;
  44124. };
  44125. /**
  44126. * This creates the defines related to the standard BJS materials.
  44127. */
  44128. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  44129. var scene = this._scene;
  44130. var light = this._light;
  44131. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  44132. return;
  44133. }
  44134. defines["SHADOW" + lightIndex] = true;
  44135. if (this.usePoissonSampling) {
  44136. defines["SHADOWPCF" + lightIndex] = true;
  44137. }
  44138. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  44139. defines["SHADOWESM" + lightIndex] = true;
  44140. }
  44141. if (light.needCube()) {
  44142. defines["SHADOWCUBE" + lightIndex] = true;
  44143. }
  44144. };
  44145. /**
  44146. * This binds shadow lights related to the standard BJS materials.
  44147. * It implies the unifroms available on the materials are the standard BJS ones.
  44148. */
  44149. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect, depthValuesAlreadySet) {
  44150. var light = this._light;
  44151. var scene = this._scene;
  44152. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  44153. return;
  44154. }
  44155. if (!light.needCube()) {
  44156. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  44157. }
  44158. else {
  44159. if (!depthValuesAlreadySet) {
  44160. depthValuesAlreadySet = true;
  44161. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  44162. }
  44163. }
  44164. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  44165. light._uniformBuffer.updateFloat3("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, lightIndex);
  44166. return depthValuesAlreadySet;
  44167. };
  44168. return ShadowGenerator;
  44169. }());
  44170. ShadowGenerator._FILTER_NONE = 0;
  44171. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  44172. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  44173. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  44174. BABYLON.ShadowGenerator = ShadowGenerator;
  44175. })(BABYLON || (BABYLON = {}));
  44176. //# sourceMappingURL=babylon.shadowGenerator.js.map
  44177. var BABYLON;
  44178. (function (BABYLON) {
  44179. var DefaultLoadingScreen = (function () {
  44180. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  44181. if (_loadingText === void 0) { _loadingText = ""; }
  44182. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  44183. var _this = this;
  44184. this._renderingCanvas = _renderingCanvas;
  44185. this._loadingText = _loadingText;
  44186. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  44187. // Resize
  44188. this._resizeLoadingUI = function () {
  44189. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  44190. _this._loadingDiv.style.position = "absolute";
  44191. _this._loadingDiv.style.left = canvasRect.left + "px";
  44192. _this._loadingDiv.style.top = canvasRect.top + "px";
  44193. _this._loadingDiv.style.width = canvasRect.width + "px";
  44194. _this._loadingDiv.style.height = canvasRect.height + "px";
  44195. };
  44196. }
  44197. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  44198. var _this = this;
  44199. if (this._loadingDiv) {
  44200. // Do not add a loading screen if there is already one
  44201. return;
  44202. }
  44203. this._loadingDiv = document.createElement("div");
  44204. this._loadingDiv.id = "babylonjsLoadingDiv";
  44205. this._loadingDiv.style.opacity = "0";
  44206. this._loadingDiv.style.transition = "opacity 1.5s ease";
  44207. // Loading text
  44208. this._loadingTextDiv = document.createElement("div");
  44209. this._loadingTextDiv.style.position = "absolute";
  44210. this._loadingTextDiv.style.left = "0";
  44211. this._loadingTextDiv.style.top = "50%";
  44212. this._loadingTextDiv.style.marginTop = "80px";
  44213. this._loadingTextDiv.style.width = "100%";
  44214. this._loadingTextDiv.style.height = "20px";
  44215. this._loadingTextDiv.style.fontFamily = "Arial";
  44216. this._loadingTextDiv.style.fontSize = "14px";
  44217. this._loadingTextDiv.style.color = "white";
  44218. this._loadingTextDiv.style.textAlign = "center";
  44219. this._loadingTextDiv.innerHTML = "Loading";
  44220. this._loadingDiv.appendChild(this._loadingTextDiv);
  44221. //set the predefined text
  44222. this._loadingTextDiv.innerHTML = this._loadingText;
  44223. // Loading img
  44224. var imgBack = new Image();
  44225. 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==";
  44226. imgBack.style.position = "absolute";
  44227. imgBack.style.left = "50%";
  44228. imgBack.style.top = "50%";
  44229. imgBack.style.marginLeft = "-50px";
  44230. imgBack.style.marginTop = "-50px";
  44231. imgBack.style.transition = "transform 1.0s ease";
  44232. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  44233. var deg = 360;
  44234. var onTransitionEnd = function () {
  44235. deg += 360;
  44236. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  44237. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  44238. };
  44239. imgBack.addEventListener("transitionend", onTransitionEnd);
  44240. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  44241. this._loadingDiv.appendChild(imgBack);
  44242. // front image
  44243. var imgFront = new Image();
  44244. 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=";
  44245. imgFront.style.position = "absolute";
  44246. imgFront.style.left = "50%";
  44247. imgFront.style.top = "50%";
  44248. imgFront.style.marginLeft = "-50px";
  44249. imgFront.style.marginTop = "-50px";
  44250. this._loadingDiv.appendChild(imgFront);
  44251. this._resizeLoadingUI();
  44252. window.addEventListener("resize", this._resizeLoadingUI);
  44253. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  44254. document.body.appendChild(this._loadingDiv);
  44255. setTimeout(function () {
  44256. _this._loadingDiv.style.opacity = "1";
  44257. imgBack.style.transform = "rotateZ(360deg)";
  44258. imgBack.style.webkitTransform = "rotateZ(360deg)";
  44259. }, 0);
  44260. };
  44261. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  44262. var _this = this;
  44263. if (!this._loadingDiv) {
  44264. return;
  44265. }
  44266. var onTransitionEnd = function () {
  44267. if (!_this._loadingDiv) {
  44268. return;
  44269. }
  44270. document.body.removeChild(_this._loadingDiv);
  44271. window.removeEventListener("resize", _this._resizeLoadingUI);
  44272. _this._loadingDiv = null;
  44273. };
  44274. this._loadingDiv.style.opacity = "0";
  44275. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  44276. };
  44277. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  44278. set: function (text) {
  44279. this._loadingText = text;
  44280. if (this._loadingTextDiv) {
  44281. this._loadingTextDiv.innerHTML = this._loadingText;
  44282. }
  44283. },
  44284. enumerable: true,
  44285. configurable: true
  44286. });
  44287. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  44288. get: function () {
  44289. return this._loadingDivBackgroundColor;
  44290. },
  44291. set: function (color) {
  44292. this._loadingDivBackgroundColor = color;
  44293. if (!this._loadingDiv) {
  44294. return;
  44295. }
  44296. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  44297. },
  44298. enumerable: true,
  44299. configurable: true
  44300. });
  44301. return DefaultLoadingScreen;
  44302. }());
  44303. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  44304. })(BABYLON || (BABYLON = {}));
  44305. //# sourceMappingURL=babylon.loadingScreen.js.map
  44306. var BABYLON;
  44307. (function (BABYLON) {
  44308. var SceneLoader = (function () {
  44309. function SceneLoader() {
  44310. }
  44311. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  44312. get: function () {
  44313. return 0;
  44314. },
  44315. enumerable: true,
  44316. configurable: true
  44317. });
  44318. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  44319. get: function () {
  44320. return 1;
  44321. },
  44322. enumerable: true,
  44323. configurable: true
  44324. });
  44325. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  44326. get: function () {
  44327. return 2;
  44328. },
  44329. enumerable: true,
  44330. configurable: true
  44331. });
  44332. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  44333. get: function () {
  44334. return 3;
  44335. },
  44336. enumerable: true,
  44337. configurable: true
  44338. });
  44339. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  44340. get: function () {
  44341. return SceneLoader._ForceFullSceneLoadingForIncremental;
  44342. },
  44343. set: function (value) {
  44344. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  44345. },
  44346. enumerable: true,
  44347. configurable: true
  44348. });
  44349. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  44350. get: function () {
  44351. return SceneLoader._ShowLoadingScreen;
  44352. },
  44353. set: function (value) {
  44354. SceneLoader._ShowLoadingScreen = value;
  44355. },
  44356. enumerable: true,
  44357. configurable: true
  44358. });
  44359. Object.defineProperty(SceneLoader, "loggingLevel", {
  44360. get: function () {
  44361. return SceneLoader._loggingLevel;
  44362. },
  44363. set: function (value) {
  44364. SceneLoader._loggingLevel = value;
  44365. },
  44366. enumerable: true,
  44367. configurable: true
  44368. });
  44369. SceneLoader._getDefaultPlugin = function () {
  44370. return SceneLoader._registeredPlugins[".babylon"];
  44371. };
  44372. SceneLoader._getPluginForExtension = function (extension) {
  44373. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  44374. if (registeredPlugin) {
  44375. return registeredPlugin;
  44376. }
  44377. return SceneLoader._getDefaultPlugin();
  44378. };
  44379. SceneLoader._getPluginForDirectLoad = function (data) {
  44380. for (var extension in SceneLoader._registeredPlugins) {
  44381. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  44382. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  44383. return SceneLoader._registeredPlugins[extension];
  44384. }
  44385. }
  44386. return SceneLoader._getDefaultPlugin();
  44387. };
  44388. SceneLoader._getPluginForFilename = function (sceneFilename) {
  44389. if (sceneFilename.name) {
  44390. sceneFilename = sceneFilename.name;
  44391. }
  44392. var dotPosition = sceneFilename.lastIndexOf(".");
  44393. var queryStringPosition = sceneFilename.indexOf("?");
  44394. if (queryStringPosition === -1) {
  44395. queryStringPosition = sceneFilename.length;
  44396. }
  44397. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  44398. return SceneLoader._getPluginForExtension(extension);
  44399. };
  44400. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  44401. SceneLoader._getDirectLoad = function (sceneFilename) {
  44402. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  44403. return sceneFilename.substr(5);
  44404. }
  44405. return null;
  44406. };
  44407. // Public functions
  44408. SceneLoader.GetPluginForExtension = function (extension) {
  44409. return SceneLoader._getPluginForExtension(extension).plugin;
  44410. };
  44411. SceneLoader.RegisterPlugin = function (plugin) {
  44412. if (typeof plugin.extensions === "string") {
  44413. var extension = plugin.extensions;
  44414. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  44415. plugin: plugin,
  44416. isBinary: false
  44417. };
  44418. }
  44419. else {
  44420. var extensions = plugin.extensions;
  44421. Object.keys(extensions).forEach(function (extension) {
  44422. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  44423. plugin: plugin,
  44424. isBinary: extensions[extension].isBinary
  44425. };
  44426. });
  44427. }
  44428. };
  44429. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  44430. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  44431. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  44432. return;
  44433. }
  44434. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  44435. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  44436. return;
  44437. }
  44438. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  44439. var loadingToken = {};
  44440. scene._addPendingData(loadingToken);
  44441. var manifestChecked = function (success) {
  44442. scene.database = database;
  44443. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(directLoad) : SceneLoader._getPluginForFilename(sceneFilename);
  44444. var plugin = registeredPlugin.plugin;
  44445. var useArrayBuffer = registeredPlugin.isBinary;
  44446. var importMeshFromData = function (data) {
  44447. var meshes = [];
  44448. var particleSystems = [];
  44449. var skeletons = [];
  44450. if (scene.isDisposed) {
  44451. if (onerror) {
  44452. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  44453. }
  44454. return;
  44455. }
  44456. try {
  44457. if (plugin.importMesh) {
  44458. var syncedPlugin = plugin;
  44459. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  44460. if (onerror) {
  44461. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  44462. }
  44463. scene._removePendingData(loadingToken);
  44464. return;
  44465. }
  44466. if (onsuccess) {
  44467. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  44468. onsuccess(meshes, particleSystems, skeletons);
  44469. scene._removePendingData(loadingToken);
  44470. }
  44471. }
  44472. else {
  44473. var asyncedPlugin = plugin;
  44474. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  44475. if (onsuccess) {
  44476. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  44477. onsuccess(meshes, particleSystems, skeletons);
  44478. scene._removePendingData(loadingToken);
  44479. }
  44480. }, function () {
  44481. if (onerror) {
  44482. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  44483. }
  44484. scene._removePendingData(loadingToken);
  44485. });
  44486. }
  44487. }
  44488. catch (e) {
  44489. if (onerror) {
  44490. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  44491. }
  44492. scene._removePendingData(loadingToken);
  44493. }
  44494. };
  44495. if (directLoad) {
  44496. importMeshFromData(directLoad);
  44497. return;
  44498. }
  44499. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  44500. importMeshFromData(data);
  44501. }, progressCallBack, database, useArrayBuffer, function () {
  44502. if (onerror) {
  44503. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  44504. }
  44505. });
  44506. };
  44507. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  44508. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  44509. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  44510. }
  44511. else {
  44512. // If the scene is a data stream or offline support is not enabled, it's a direct load
  44513. manifestChecked(true);
  44514. }
  44515. };
  44516. /**
  44517. * Load a scene
  44518. * @param rootUrl a string that defines the root url for scene and resources
  44519. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  44520. * @param engine is the instance of BABYLON.Engine to use to create the scene
  44521. */
  44522. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  44523. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  44524. };
  44525. /**
  44526. * Append a scene
  44527. * @param rootUrl a string that defines the root url for scene and resources
  44528. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  44529. * @param scene is the instance of BABYLON.Scene to append to
  44530. */
  44531. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  44532. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  44533. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  44534. return;
  44535. }
  44536. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  44537. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  44538. var plugin = registeredPlugin.plugin;
  44539. var useArrayBuffer = registeredPlugin.isBinary;
  44540. var database;
  44541. var loadingToken = {};
  44542. scene._addPendingData(loadingToken);
  44543. if (SceneLoader.ShowLoadingScreen) {
  44544. scene.getEngine().displayLoadingUI();
  44545. }
  44546. var loadSceneFromData = function (data) {
  44547. scene.database = database;
  44548. if (plugin.load) {
  44549. var syncedPlugin = plugin;
  44550. if (!syncedPlugin.load(scene, data, rootUrl)) {
  44551. if (onerror) {
  44552. onerror(scene);
  44553. }
  44554. scene._removePendingData(loadingToken);
  44555. scene.getEngine().hideLoadingUI();
  44556. return;
  44557. }
  44558. if (onsuccess) {
  44559. onsuccess(scene);
  44560. }
  44561. scene._removePendingData(loadingToken);
  44562. }
  44563. else {
  44564. var asyncedPlugin = plugin;
  44565. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  44566. if (onsuccess) {
  44567. onsuccess(scene);
  44568. }
  44569. scene._removePendingData(loadingToken);
  44570. }, function () {
  44571. if (onerror) {
  44572. onerror(scene);
  44573. }
  44574. scene._removePendingData(loadingToken);
  44575. scene.getEngine().hideLoadingUI();
  44576. });
  44577. }
  44578. if (SceneLoader.ShowLoadingScreen) {
  44579. scene.executeWhenReady(function () {
  44580. scene.getEngine().hideLoadingUI();
  44581. });
  44582. }
  44583. };
  44584. var manifestChecked = function (success) {
  44585. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  44586. };
  44587. if (directLoad) {
  44588. loadSceneFromData(directLoad);
  44589. return;
  44590. }
  44591. if (rootUrl.indexOf("file:") === -1) {
  44592. if (scene.getEngine().enableOfflineSupport) {
  44593. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  44594. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  44595. }
  44596. else {
  44597. manifestChecked(true);
  44598. }
  44599. }
  44600. else {
  44601. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  44602. }
  44603. };
  44604. return SceneLoader;
  44605. }());
  44606. // Flags
  44607. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  44608. SceneLoader._ShowLoadingScreen = true;
  44609. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  44610. // Members
  44611. SceneLoader._registeredPlugins = {};
  44612. BABYLON.SceneLoader = SceneLoader;
  44613. ;
  44614. })(BABYLON || (BABYLON = {}));
  44615. //# sourceMappingURL=babylon.sceneLoader.js.map
  44616. var BABYLON;
  44617. (function (BABYLON) {
  44618. var Internals;
  44619. (function (Internals) {
  44620. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  44621. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  44622. var parsedMaterial = parsedData.materials[index];
  44623. if (parsedMaterial.id === id) {
  44624. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  44625. }
  44626. }
  44627. return null;
  44628. };
  44629. var isDescendantOf = function (mesh, names, hierarchyIds) {
  44630. names = (names instanceof Array) ? names : [names];
  44631. for (var i in names) {
  44632. if (mesh.name === names[i]) {
  44633. hierarchyIds.push(mesh.id);
  44634. return true;
  44635. }
  44636. }
  44637. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  44638. hierarchyIds.push(mesh.id);
  44639. return true;
  44640. }
  44641. return false;
  44642. };
  44643. var logOperation = function (operation, producer) {
  44644. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  44645. };
  44646. BABYLON.SceneLoader.RegisterPlugin({
  44647. extensions: ".babylon",
  44648. canDirectLoad: function (data) {
  44649. if (data.indexOf("babylon") !== -1) {
  44650. return true;
  44651. }
  44652. return false;
  44653. },
  44654. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  44655. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  44656. // when SceneLoader.debugLogging = true (default), or exception encountered.
  44657. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  44658. // and avoid problems with multiple concurrent .babylon loads.
  44659. var log = "importMesh has failed JSON parse";
  44660. try {
  44661. var parsedData = JSON.parse(data);
  44662. log = "";
  44663. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  44664. var loadedSkeletonsIds = [];
  44665. var loadedMaterialsIds = [];
  44666. var hierarchyIds = [];
  44667. var index;
  44668. var cache;
  44669. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  44670. var parsedMesh = parsedData.meshes[index];
  44671. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  44672. if (meshesNames instanceof Array) {
  44673. // Remove found mesh name from list.
  44674. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  44675. }
  44676. //Geometry?
  44677. if (parsedMesh.geometryId) {
  44678. //does the file contain geometries?
  44679. if (parsedData.geometries) {
  44680. //find the correct geometry and add it to the scene
  44681. var found = false;
  44682. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  44683. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  44684. return;
  44685. }
  44686. else {
  44687. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  44688. if (parsedGeometryData.id === parsedMesh.geometryId) {
  44689. switch (geometryType) {
  44690. case "boxes":
  44691. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  44692. break;
  44693. case "spheres":
  44694. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  44695. break;
  44696. case "cylinders":
  44697. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  44698. break;
  44699. case "toruses":
  44700. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  44701. break;
  44702. case "grounds":
  44703. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  44704. break;
  44705. case "planes":
  44706. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  44707. break;
  44708. case "torusKnots":
  44709. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  44710. break;
  44711. case "vertexData":
  44712. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  44713. break;
  44714. }
  44715. found = true;
  44716. }
  44717. });
  44718. }
  44719. });
  44720. if (!found) {
  44721. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  44722. }
  44723. }
  44724. }
  44725. // Material ?
  44726. if (parsedMesh.materialId) {
  44727. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  44728. if (!materialFound && parsedData.multiMaterials) {
  44729. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  44730. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  44731. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  44732. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  44733. var subMatId = parsedMultiMaterial.materials[matIndex];
  44734. loadedMaterialsIds.push(subMatId);
  44735. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  44736. log += "\n\tMaterial " + mat.toString(fullDetails);
  44737. }
  44738. loadedMaterialsIds.push(parsedMultiMaterial.id);
  44739. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  44740. materialFound = true;
  44741. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  44742. break;
  44743. }
  44744. }
  44745. }
  44746. if (!materialFound) {
  44747. loadedMaterialsIds.push(parsedMesh.materialId);
  44748. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  44749. if (!mat) {
  44750. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  44751. }
  44752. else {
  44753. log += "\n\tMaterial " + mat.toString(fullDetails);
  44754. }
  44755. }
  44756. }
  44757. // Skeleton ?
  44758. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  44759. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  44760. if (!skeletonAlreadyLoaded) {
  44761. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  44762. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  44763. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  44764. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  44765. skeletons.push(skeleton);
  44766. loadedSkeletonsIds.push(parsedSkeleton.id);
  44767. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  44768. }
  44769. }
  44770. }
  44771. }
  44772. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  44773. meshes.push(mesh);
  44774. log += "\n\tMesh " + mesh.toString(fullDetails);
  44775. }
  44776. }
  44777. // Connecting parents
  44778. var currentMesh;
  44779. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  44780. currentMesh = scene.meshes[index];
  44781. if (currentMesh._waitingParentId) {
  44782. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  44783. currentMesh._waitingParentId = undefined;
  44784. }
  44785. }
  44786. // freeze and compute world matrix application
  44787. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  44788. currentMesh = scene.meshes[index];
  44789. if (currentMesh._waitingFreezeWorldMatrix) {
  44790. currentMesh.freezeWorldMatrix();
  44791. currentMesh._waitingFreezeWorldMatrix = undefined;
  44792. }
  44793. else {
  44794. currentMesh.computeWorldMatrix(true);
  44795. }
  44796. }
  44797. // Particles
  44798. if (parsedData.particleSystems) {
  44799. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  44800. var parsedParticleSystem = parsedData.particleSystems[index];
  44801. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  44802. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  44803. }
  44804. }
  44805. }
  44806. return true;
  44807. }
  44808. catch (err) {
  44809. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  44810. log = null;
  44811. throw err;
  44812. }
  44813. finally {
  44814. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  44815. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  44816. }
  44817. }
  44818. },
  44819. load: function (scene, data, rootUrl) {
  44820. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  44821. // when SceneLoader.debugLogging = true (default), or exception encountered.
  44822. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  44823. // and avoid problems with multiple concurrent .babylon loads.
  44824. var log = "importScene has failed JSON parse";
  44825. try {
  44826. var parsedData = JSON.parse(data);
  44827. log = "";
  44828. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  44829. // Scene
  44830. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  44831. scene.autoClear = parsedData.autoClear;
  44832. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  44833. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  44834. if (parsedData.gravity) {
  44835. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  44836. }
  44837. // Fog
  44838. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  44839. scene.fogMode = parsedData.fogMode;
  44840. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  44841. scene.fogStart = parsedData.fogStart;
  44842. scene.fogEnd = parsedData.fogEnd;
  44843. scene.fogDensity = parsedData.fogDensity;
  44844. log += "\tFog mode for scene: ";
  44845. switch (scene.fogMode) {
  44846. // getters not compiling, so using hardcoded
  44847. case 1:
  44848. log += "exp\n";
  44849. break;
  44850. case 2:
  44851. log += "exp2\n";
  44852. break;
  44853. case 3:
  44854. log += "linear\n";
  44855. break;
  44856. }
  44857. }
  44858. //Physics
  44859. if (parsedData.physicsEnabled) {
  44860. var physicsPlugin;
  44861. if (parsedData.physicsEngine === "cannon") {
  44862. physicsPlugin = new BABYLON.CannonJSPlugin();
  44863. }
  44864. else if (parsedData.physicsEngine === "oimo") {
  44865. physicsPlugin = new BABYLON.OimoJSPlugin();
  44866. }
  44867. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  44868. //else - default engine, which is currently oimo
  44869. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  44870. scene.enablePhysics(physicsGravity, physicsPlugin);
  44871. }
  44872. // Metadata
  44873. if (parsedData.metadata !== undefined) {
  44874. scene.metadata = parsedData.metadata;
  44875. }
  44876. //collisions, if defined. otherwise, default is true
  44877. if (parsedData.collisionsEnabled != undefined) {
  44878. scene.collisionsEnabled = parsedData.collisionsEnabled;
  44879. }
  44880. scene.workerCollisions = !!parsedData.workerCollisions;
  44881. var index;
  44882. var cache;
  44883. // Lights
  44884. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  44885. var parsedLight = parsedData.lights[index];
  44886. var light = BABYLON.Light.Parse(parsedLight, scene);
  44887. log += (index === 0 ? "\n\tLights:" : "");
  44888. log += "\n\t\t" + light.toString(fullDetails);
  44889. }
  44890. // Animations
  44891. if (parsedData.animations) {
  44892. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  44893. var parsedAnimation = parsedData.animations[index];
  44894. var animation = BABYLON.Animation.Parse(parsedAnimation);
  44895. scene.animations.push(animation);
  44896. log += (index === 0 ? "\n\tAnimations:" : "");
  44897. log += "\n\t\t" + animation.toString(fullDetails);
  44898. }
  44899. }
  44900. if (parsedData.autoAnimate) {
  44901. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  44902. }
  44903. // Materials
  44904. if (parsedData.materials) {
  44905. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  44906. var parsedMaterial = parsedData.materials[index];
  44907. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  44908. log += (index === 0 ? "\n\tMaterials:" : "");
  44909. log += "\n\t\t" + mat.toString(fullDetails);
  44910. }
  44911. }
  44912. if (parsedData.multiMaterials) {
  44913. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  44914. var parsedMultiMaterial = parsedData.multiMaterials[index];
  44915. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  44916. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  44917. log += "\n\t\t" + mmat.toString(fullDetails);
  44918. }
  44919. }
  44920. // Morph targets
  44921. if (parsedData.morphTargetManagers) {
  44922. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  44923. var managerData = _a[_i];
  44924. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  44925. }
  44926. }
  44927. // Skeletons
  44928. if (parsedData.skeletons) {
  44929. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  44930. var parsedSkeleton = parsedData.skeletons[index];
  44931. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  44932. log += (index === 0 ? "\n\tSkeletons:" : "");
  44933. log += "\n\t\t" + skeleton.toString(fullDetails);
  44934. }
  44935. }
  44936. // Geometries
  44937. var geometries = parsedData.geometries;
  44938. if (geometries) {
  44939. // Boxes
  44940. var boxes = geometries.boxes;
  44941. if (boxes) {
  44942. for (index = 0, cache = boxes.length; index < cache; index++) {
  44943. var parsedBox = boxes[index];
  44944. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  44945. }
  44946. }
  44947. // Spheres
  44948. var spheres = geometries.spheres;
  44949. if (spheres) {
  44950. for (index = 0, cache = spheres.length; index < cache; index++) {
  44951. var parsedSphere = spheres[index];
  44952. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  44953. }
  44954. }
  44955. // Cylinders
  44956. var cylinders = geometries.cylinders;
  44957. if (cylinders) {
  44958. for (index = 0, cache = cylinders.length; index < cache; index++) {
  44959. var parsedCylinder = cylinders[index];
  44960. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  44961. }
  44962. }
  44963. // Toruses
  44964. var toruses = geometries.toruses;
  44965. if (toruses) {
  44966. for (index = 0, cache = toruses.length; index < cache; index++) {
  44967. var parsedTorus = toruses[index];
  44968. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  44969. }
  44970. }
  44971. // Grounds
  44972. var grounds = geometries.grounds;
  44973. if (grounds) {
  44974. for (index = 0, cache = grounds.length; index < cache; index++) {
  44975. var parsedGround = grounds[index];
  44976. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  44977. }
  44978. }
  44979. // Planes
  44980. var planes = geometries.planes;
  44981. if (planes) {
  44982. for (index = 0, cache = planes.length; index < cache; index++) {
  44983. var parsedPlane = planes[index];
  44984. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  44985. }
  44986. }
  44987. // TorusKnots
  44988. var torusKnots = geometries.torusKnots;
  44989. if (torusKnots) {
  44990. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  44991. var parsedTorusKnot = torusKnots[index];
  44992. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  44993. }
  44994. }
  44995. // VertexData
  44996. var vertexData = geometries.vertexData;
  44997. if (vertexData) {
  44998. for (index = 0, cache = vertexData.length; index < cache; index++) {
  44999. var parsedVertexData = vertexData[index];
  45000. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  45001. }
  45002. }
  45003. }
  45004. // Meshes
  45005. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  45006. var parsedMesh = parsedData.meshes[index];
  45007. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  45008. log += (index === 0 ? "\n\tMeshes:" : "");
  45009. log += "\n\t\t" + mesh.toString(fullDetails);
  45010. }
  45011. // Cameras
  45012. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  45013. var parsedCamera = parsedData.cameras[index];
  45014. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  45015. log += (index === 0 ? "\n\tCameras:" : "");
  45016. log += "\n\t\t" + camera.toString(fullDetails);
  45017. }
  45018. if (parsedData.activeCameraID) {
  45019. scene.setActiveCameraByID(parsedData.activeCameraID);
  45020. }
  45021. // Browsing all the graph to connect the dots
  45022. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  45023. var camera = scene.cameras[index];
  45024. if (camera._waitingParentId) {
  45025. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  45026. camera._waitingParentId = undefined;
  45027. }
  45028. }
  45029. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  45030. var light = scene.lights[index];
  45031. if (light._waitingParentId) {
  45032. light.parent = scene.getLastEntryByID(light._waitingParentId);
  45033. light._waitingParentId = undefined;
  45034. }
  45035. }
  45036. // Sounds
  45037. var loadedSounds = [];
  45038. var loadedSound;
  45039. if (BABYLON.AudioEngine && parsedData.sounds) {
  45040. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  45041. var parsedSound = parsedData.sounds[index];
  45042. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45043. if (!parsedSound.url)
  45044. parsedSound.url = parsedSound.name;
  45045. if (!loadedSounds[parsedSound.url]) {
  45046. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  45047. loadedSounds[parsedSound.url] = loadedSound;
  45048. }
  45049. else {
  45050. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  45051. }
  45052. }
  45053. else {
  45054. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  45055. }
  45056. }
  45057. }
  45058. loadedSounds = [];
  45059. // Connect parents & children and parse actions
  45060. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45061. var mesh = scene.meshes[index];
  45062. if (mesh._waitingParentId) {
  45063. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  45064. mesh._waitingParentId = undefined;
  45065. }
  45066. if (mesh._waitingActions) {
  45067. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  45068. mesh._waitingActions = undefined;
  45069. }
  45070. }
  45071. // freeze world matrix application
  45072. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45073. var currentMesh = scene.meshes[index];
  45074. if (currentMesh._waitingFreezeWorldMatrix) {
  45075. currentMesh.freezeWorldMatrix();
  45076. currentMesh._waitingFreezeWorldMatrix = undefined;
  45077. }
  45078. else {
  45079. currentMesh.computeWorldMatrix(true);
  45080. }
  45081. }
  45082. // Particles Systems
  45083. if (parsedData.particleSystems) {
  45084. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  45085. var parsedParticleSystem = parsedData.particleSystems[index];
  45086. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  45087. }
  45088. }
  45089. // Lens flares
  45090. if (parsedData.lensFlareSystems) {
  45091. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  45092. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  45093. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  45094. }
  45095. }
  45096. // Shadows
  45097. if (parsedData.shadowGenerators) {
  45098. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  45099. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  45100. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  45101. }
  45102. }
  45103. // Lights exclusions / inclusions
  45104. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  45105. var light = scene.lights[index];
  45106. // Excluded check
  45107. if (light._excludedMeshesIds.length > 0) {
  45108. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  45109. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  45110. if (excludedMesh) {
  45111. light.excludedMeshes.push(excludedMesh);
  45112. }
  45113. }
  45114. light._excludedMeshesIds = [];
  45115. }
  45116. // Included check
  45117. if (light._includedOnlyMeshesIds.length > 0) {
  45118. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  45119. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  45120. if (includedOnlyMesh) {
  45121. light.includedOnlyMeshes.push(includedOnlyMesh);
  45122. }
  45123. }
  45124. light._includedOnlyMeshesIds = [];
  45125. }
  45126. }
  45127. // Actions (scene)
  45128. if (parsedData.actions) {
  45129. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  45130. }
  45131. // Finish
  45132. return true;
  45133. }
  45134. catch (err) {
  45135. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  45136. log = null;
  45137. throw err;
  45138. }
  45139. finally {
  45140. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  45141. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  45142. }
  45143. }
  45144. }
  45145. });
  45146. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45147. })(BABYLON || (BABYLON = {}));
  45148. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  45149. var BABYLON;
  45150. (function (BABYLON) {
  45151. var FilesInput = (function () {
  45152. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  45153. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  45154. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  45155. this._engine = p_engine;
  45156. this._canvas = p_canvas;
  45157. this._currentScene = p_scene;
  45158. this._sceneLoadedCallback = p_sceneLoadedCallback;
  45159. this._progressCallback = p_progressCallback;
  45160. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  45161. this._textureLoadingCallback = p_textureLoadingCallback;
  45162. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  45163. }
  45164. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  45165. var _this = this;
  45166. if (p_elementToMonitor) {
  45167. this._elementToMonitor = p_elementToMonitor;
  45168. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  45169. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  45170. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  45171. }
  45172. };
  45173. FilesInput.prototype.renderFunction = function () {
  45174. if (this._additionnalRenderLoopLogicCallback) {
  45175. this._additionnalRenderLoopLogicCallback();
  45176. }
  45177. if (this._currentScene) {
  45178. if (this._textureLoadingCallback) {
  45179. var remaining = this._currentScene.getWaitingItemsCount();
  45180. if (remaining > 0) {
  45181. this._textureLoadingCallback(remaining);
  45182. }
  45183. }
  45184. this._currentScene.render();
  45185. }
  45186. };
  45187. FilesInput.prototype.drag = function (e) {
  45188. e.stopPropagation();
  45189. e.preventDefault();
  45190. };
  45191. FilesInput.prototype.drop = function (eventDrop) {
  45192. eventDrop.stopPropagation();
  45193. eventDrop.preventDefault();
  45194. this.loadFiles(eventDrop);
  45195. };
  45196. FilesInput.prototype.loadFiles = function (event) {
  45197. if (this._startingProcessingFilesCallback)
  45198. this._startingProcessingFilesCallback();
  45199. // Handling data transfer via drag'n'drop
  45200. if (event && event.dataTransfer && event.dataTransfer.files) {
  45201. this._filesToLoad = event.dataTransfer.files;
  45202. }
  45203. // Handling files from input files
  45204. if (event && event.target && event.target.files) {
  45205. this._filesToLoad = event.target.files;
  45206. }
  45207. if (this._filesToLoad && this._filesToLoad.length > 0) {
  45208. for (var i = 0; i < this._filesToLoad.length; i++) {
  45209. var name_1 = this._filesToLoad[i].name.toLowerCase();
  45210. var extension = name_1.split('.').pop();
  45211. var type = this._filesToLoad[i].type;
  45212. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  45213. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  45214. this._sceneFileToLoad = this._filesToLoad[i];
  45215. }
  45216. else {
  45217. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  45218. }
  45219. }
  45220. this.reload();
  45221. }
  45222. };
  45223. FilesInput.prototype.reload = function () {
  45224. var _this = this;
  45225. var that = this;
  45226. // If a ".babylon" file has been provided
  45227. if (this._sceneFileToLoad) {
  45228. if (this._currentScene) {
  45229. if (BABYLON.Tools.errorsCount > 0) {
  45230. BABYLON.Tools.ClearLogCache();
  45231. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  45232. }
  45233. this._engine.stopRenderLoop();
  45234. this._currentScene.dispose();
  45235. }
  45236. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  45237. that._currentScene = newScene;
  45238. // Wait for textures and shaders to be ready
  45239. that._currentScene.executeWhenReady(function () {
  45240. if (that._sceneLoadedCallback) {
  45241. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  45242. }
  45243. that._engine.runRenderLoop(function () { that.renderFunction(); });
  45244. });
  45245. }, function (progress) {
  45246. if (_this._progressCallback) {
  45247. _this._progressCallback(progress);
  45248. }
  45249. });
  45250. }
  45251. else {
  45252. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  45253. }
  45254. };
  45255. return FilesInput;
  45256. }());
  45257. FilesInput.FilesToLoad = new Array();
  45258. BABYLON.FilesInput = FilesInput;
  45259. })(BABYLON || (BABYLON = {}));
  45260. //# sourceMappingURL=babylon.filesInput.js.map
  45261. var BABYLON;
  45262. (function (BABYLON) {
  45263. /**
  45264. * This class implement a typical dictionary using a string as key and the generic type T as value.
  45265. * The underlying implementation relies on an associative array to ensure the best performances.
  45266. * The value can be anything including 'null' but except 'undefined'
  45267. */
  45268. var StringDictionary = (function () {
  45269. function StringDictionary() {
  45270. this._count = 0;
  45271. this._data = {};
  45272. }
  45273. /**
  45274. * This will clear this dictionary and copy the content from the 'source' one.
  45275. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  45276. * @param source the dictionary to take the content from and copy to this dictionary
  45277. */
  45278. StringDictionary.prototype.copyFrom = function (source) {
  45279. var _this = this;
  45280. this.clear();
  45281. source.forEach(function (t, v) { return _this.add(t, v); });
  45282. };
  45283. /**
  45284. * Get a value based from its key
  45285. * @param key the given key to get the matching value from
  45286. * @return the value if found, otherwise undefined is returned
  45287. */
  45288. StringDictionary.prototype.get = function (key) {
  45289. var val = this._data[key];
  45290. if (val !== undefined) {
  45291. return val;
  45292. }
  45293. return undefined;
  45294. };
  45295. /**
  45296. * Get a value from its key or add it if it doesn't exist.
  45297. * This method will ensure you that a given key/data will be present in the dictionary.
  45298. * @param key the given key to get the matching value from
  45299. * @param factory the factory that will create the value if the key is not present in the dictionary.
  45300. * The factory will only be invoked if there's no data for the given key.
  45301. * @return the value corresponding to the key.
  45302. */
  45303. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  45304. var val = this.get(key);
  45305. if (val !== undefined) {
  45306. return val;
  45307. }
  45308. val = factory(key);
  45309. if (val) {
  45310. this.add(key, val);
  45311. }
  45312. return val;
  45313. };
  45314. /**
  45315. * Get a value from its key if present in the dictionary otherwise add it
  45316. * @param key the key to get the value from
  45317. * @param val if there's no such key/value pair in the dictionary add it with this value
  45318. * @return the value corresponding to the key
  45319. */
  45320. StringDictionary.prototype.getOrAdd = function (key, val) {
  45321. var curVal = this.get(key);
  45322. if (curVal !== undefined) {
  45323. return curVal;
  45324. }
  45325. this.add(key, val);
  45326. return val;
  45327. };
  45328. /**
  45329. * Check if there's a given key in the dictionary
  45330. * @param key the key to check for
  45331. * @return true if the key is present, false otherwise
  45332. */
  45333. StringDictionary.prototype.contains = function (key) {
  45334. return this._data[key] !== undefined;
  45335. };
  45336. /**
  45337. * Add a new key and its corresponding value
  45338. * @param key the key to add
  45339. * @param value the value corresponding to the key
  45340. * @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
  45341. */
  45342. StringDictionary.prototype.add = function (key, value) {
  45343. if (this._data[key] !== undefined) {
  45344. return false;
  45345. }
  45346. this._data[key] = value;
  45347. ++this._count;
  45348. return true;
  45349. };
  45350. StringDictionary.prototype.set = function (key, value) {
  45351. if (this._data[key] === undefined) {
  45352. return false;
  45353. }
  45354. this._data[key] = value;
  45355. return true;
  45356. };
  45357. /**
  45358. * Get the element of the given key and remove it from the dictionary
  45359. * @param key
  45360. */
  45361. StringDictionary.prototype.getAndRemove = function (key) {
  45362. var val = this.get(key);
  45363. if (val !== undefined) {
  45364. delete this._data[key];
  45365. --this._count;
  45366. return val;
  45367. }
  45368. return null;
  45369. };
  45370. /**
  45371. * Remove a key/value from the dictionary.
  45372. * @param key the key to remove
  45373. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  45374. */
  45375. StringDictionary.prototype.remove = function (key) {
  45376. if (this.contains(key)) {
  45377. delete this._data[key];
  45378. --this._count;
  45379. return true;
  45380. }
  45381. return false;
  45382. };
  45383. /**
  45384. * Clear the whole content of the dictionary
  45385. */
  45386. StringDictionary.prototype.clear = function () {
  45387. this._data = {};
  45388. this._count = 0;
  45389. };
  45390. Object.defineProperty(StringDictionary.prototype, "count", {
  45391. get: function () {
  45392. return this._count;
  45393. },
  45394. enumerable: true,
  45395. configurable: true
  45396. });
  45397. /**
  45398. * Execute a callback on each key/val of the dictionary.
  45399. * Note that you can remove any element in this dictionary in the callback implementation
  45400. * @param callback the callback to execute on a given key/value pair
  45401. */
  45402. StringDictionary.prototype.forEach = function (callback) {
  45403. for (var cur in this._data) {
  45404. var val = this._data[cur];
  45405. callback(cur, val);
  45406. }
  45407. };
  45408. /**
  45409. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  45410. * If the callback returns null or undefined the method will iterate to the next key/value pair
  45411. * Note that you can remove any element in this dictionary in the callback implementation
  45412. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  45413. */
  45414. StringDictionary.prototype.first = function (callback) {
  45415. for (var cur in this._data) {
  45416. var val = this._data[cur];
  45417. var res = callback(cur, val);
  45418. if (res) {
  45419. return res;
  45420. }
  45421. }
  45422. return null;
  45423. };
  45424. return StringDictionary;
  45425. }());
  45426. BABYLON.StringDictionary = StringDictionary;
  45427. })(BABYLON || (BABYLON = {}));
  45428. //# sourceMappingURL=babylon.stringDictionary.js.map
  45429. var BABYLON;
  45430. (function (BABYLON) {
  45431. var Tags = (function () {
  45432. function Tags() {
  45433. }
  45434. Tags.EnableFor = function (obj) {
  45435. obj._tags = obj._tags || {};
  45436. obj.hasTags = function () {
  45437. return Tags.HasTags(obj);
  45438. };
  45439. obj.addTags = function (tagsString) {
  45440. return Tags.AddTagsTo(obj, tagsString);
  45441. };
  45442. obj.removeTags = function (tagsString) {
  45443. return Tags.RemoveTagsFrom(obj, tagsString);
  45444. };
  45445. obj.matchesTagsQuery = function (tagsQuery) {
  45446. return Tags.MatchesQuery(obj, tagsQuery);
  45447. };
  45448. };
  45449. Tags.DisableFor = function (obj) {
  45450. delete obj._tags;
  45451. delete obj.hasTags;
  45452. delete obj.addTags;
  45453. delete obj.removeTags;
  45454. delete obj.matchesTagsQuery;
  45455. };
  45456. Tags.HasTags = function (obj) {
  45457. if (!obj._tags) {
  45458. return false;
  45459. }
  45460. return !BABYLON.Tools.IsEmpty(obj._tags);
  45461. };
  45462. Tags.GetTags = function (obj, asString) {
  45463. if (asString === void 0) { asString = true; }
  45464. if (!obj._tags) {
  45465. return null;
  45466. }
  45467. if (asString) {
  45468. var tagsArray = [];
  45469. for (var tag in obj._tags) {
  45470. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  45471. tagsArray.push(tag);
  45472. }
  45473. }
  45474. return tagsArray.join(" ");
  45475. }
  45476. else {
  45477. return obj._tags;
  45478. }
  45479. };
  45480. // the tags 'true' and 'false' are reserved and cannot be used as tags
  45481. // a tag cannot start with '||', '&&', and '!'
  45482. // it cannot contain whitespaces
  45483. Tags.AddTagsTo = function (obj, tagsString) {
  45484. if (!tagsString) {
  45485. return;
  45486. }
  45487. if (typeof tagsString !== "string") {
  45488. return;
  45489. }
  45490. var tags = tagsString.split(" ");
  45491. tags.forEach(function (tag, index, array) {
  45492. Tags._AddTagTo(obj, tag);
  45493. });
  45494. };
  45495. Tags._AddTagTo = function (obj, tag) {
  45496. tag = tag.trim();
  45497. if (tag === "" || tag === "true" || tag === "false") {
  45498. return;
  45499. }
  45500. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  45501. return;
  45502. }
  45503. Tags.EnableFor(obj);
  45504. obj._tags[tag] = true;
  45505. };
  45506. Tags.RemoveTagsFrom = function (obj, tagsString) {
  45507. if (!Tags.HasTags(obj)) {
  45508. return;
  45509. }
  45510. var tags = tagsString.split(" ");
  45511. for (var t in tags) {
  45512. Tags._RemoveTagFrom(obj, tags[t]);
  45513. }
  45514. };
  45515. Tags._RemoveTagFrom = function (obj, tag) {
  45516. delete obj._tags[tag];
  45517. };
  45518. Tags.MatchesQuery = function (obj, tagsQuery) {
  45519. if (tagsQuery === undefined) {
  45520. return true;
  45521. }
  45522. if (tagsQuery === "") {
  45523. return Tags.HasTags(obj);
  45524. }
  45525. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  45526. };
  45527. return Tags;
  45528. }());
  45529. BABYLON.Tags = Tags;
  45530. })(BABYLON || (BABYLON = {}));
  45531. //# sourceMappingURL=babylon.tags.js.map
  45532. var BABYLON;
  45533. (function (BABYLON) {
  45534. var Internals;
  45535. (function (Internals) {
  45536. var AndOrNotEvaluator = (function () {
  45537. function AndOrNotEvaluator() {
  45538. }
  45539. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  45540. if (!query.match(/\([^\(\)]*\)/g)) {
  45541. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  45542. }
  45543. else {
  45544. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  45545. // remove parenthesis
  45546. r = r.slice(1, r.length - 1);
  45547. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  45548. });
  45549. }
  45550. if (query === "true") {
  45551. return true;
  45552. }
  45553. if (query === "false") {
  45554. return false;
  45555. }
  45556. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  45557. };
  45558. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  45559. evaluateCallback = evaluateCallback || (function (r) {
  45560. return r === "true" ? true : false;
  45561. });
  45562. var result;
  45563. var or = parenthesisContent.split("||");
  45564. for (var i in or) {
  45565. if (or.hasOwnProperty(i)) {
  45566. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  45567. var and = ori.split("&&");
  45568. if (and.length > 1) {
  45569. for (var j = 0; j < and.length; ++j) {
  45570. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  45571. if (andj !== "true" && andj !== "false") {
  45572. if (andj[0] === "!") {
  45573. result = !evaluateCallback(andj.substring(1));
  45574. }
  45575. else {
  45576. result = evaluateCallback(andj);
  45577. }
  45578. }
  45579. else {
  45580. result = andj === "true" ? true : false;
  45581. }
  45582. if (!result) {
  45583. ori = "false";
  45584. break;
  45585. }
  45586. }
  45587. }
  45588. if (result || ori === "true") {
  45589. result = true;
  45590. break;
  45591. }
  45592. // result equals false (or undefined)
  45593. if (ori !== "true" && ori !== "false") {
  45594. if (ori[0] === "!") {
  45595. result = !evaluateCallback(ori.substring(1));
  45596. }
  45597. else {
  45598. result = evaluateCallback(ori);
  45599. }
  45600. }
  45601. else {
  45602. result = ori === "true" ? true : false;
  45603. }
  45604. }
  45605. }
  45606. // the whole parenthesis scope is replaced by 'true' or 'false'
  45607. return result ? "true" : "false";
  45608. };
  45609. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  45610. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  45611. // remove whitespaces
  45612. r = r.replace(/[\s]/g, function () { return ""; });
  45613. return r.length % 2 ? "!" : "";
  45614. });
  45615. booleanString = booleanString.trim();
  45616. if (booleanString === "!true") {
  45617. booleanString = "false";
  45618. }
  45619. else if (booleanString === "!false") {
  45620. booleanString = "true";
  45621. }
  45622. return booleanString;
  45623. };
  45624. return AndOrNotEvaluator;
  45625. }());
  45626. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  45627. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45628. })(BABYLON || (BABYLON = {}));
  45629. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  45630. var BABYLON;
  45631. (function (BABYLON) {
  45632. var Database = (function () {
  45633. function Database(urlToScene, callbackManifestChecked) {
  45634. // Handling various flavors of prefixed version of IndexedDB
  45635. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  45636. this.callbackManifestChecked = callbackManifestChecked;
  45637. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  45638. this.db = null;
  45639. this.enableSceneOffline = false;
  45640. this.enableTexturesOffline = false;
  45641. this.manifestVersionFound = 0;
  45642. this.mustUpdateRessources = false;
  45643. this.hasReachedQuota = false;
  45644. if (!Database.IDBStorageEnabled) {
  45645. this.callbackManifestChecked(true);
  45646. }
  45647. else {
  45648. this.checkManifestFile();
  45649. }
  45650. }
  45651. Database.prototype.checkManifestFile = function () {
  45652. var _this = this;
  45653. function noManifestFile() {
  45654. that.enableSceneOffline = false;
  45655. that.enableTexturesOffline = false;
  45656. that.callbackManifestChecked(false);
  45657. }
  45658. var that = this;
  45659. var timeStampUsed = false;
  45660. var manifestURL = this.currentSceneUrl + ".manifest";
  45661. var xhr = new XMLHttpRequest();
  45662. if (navigator.onLine) {
  45663. // Adding a timestamp to by-pass browsers' cache
  45664. timeStampUsed = true;
  45665. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  45666. }
  45667. xhr.open("GET", manifestURL, true);
  45668. xhr.addEventListener("load", function () {
  45669. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  45670. try {
  45671. var manifestFile = JSON.parse(xhr.response);
  45672. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  45673. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  45674. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  45675. _this.manifestVersionFound = manifestFile.version;
  45676. }
  45677. if (_this.callbackManifestChecked) {
  45678. _this.callbackManifestChecked(true);
  45679. }
  45680. }
  45681. catch (ex) {
  45682. noManifestFile();
  45683. }
  45684. }
  45685. else {
  45686. noManifestFile();
  45687. }
  45688. }, false);
  45689. xhr.addEventListener("error", function (event) {
  45690. if (timeStampUsed) {
  45691. timeStampUsed = false;
  45692. // Let's retry without the timeStamp
  45693. // It could fail when coupled with HTML5 Offline API
  45694. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  45695. xhr.open("GET", retryManifestURL, true);
  45696. xhr.send();
  45697. }
  45698. else {
  45699. noManifestFile();
  45700. }
  45701. }, false);
  45702. try {
  45703. xhr.send();
  45704. }
  45705. catch (ex) {
  45706. BABYLON.Tools.Error("Error on XHR send request.");
  45707. that.callbackManifestChecked(false);
  45708. }
  45709. };
  45710. Database.prototype.openAsync = function (successCallback, errorCallback) {
  45711. var _this = this;
  45712. function handleError() {
  45713. that.isSupported = false;
  45714. if (errorCallback)
  45715. errorCallback();
  45716. }
  45717. var that = this;
  45718. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  45719. // Your browser doesn't support IndexedDB
  45720. this.isSupported = false;
  45721. if (errorCallback)
  45722. errorCallback();
  45723. }
  45724. else {
  45725. // If the DB hasn't been opened or created yet
  45726. if (!this.db) {
  45727. this.hasReachedQuota = false;
  45728. this.isSupported = true;
  45729. var request = this.idbFactory.open("babylonjs", 1);
  45730. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  45731. request.onerror = function (event) {
  45732. handleError();
  45733. };
  45734. // executes when a version change transaction cannot complete due to other active transactions
  45735. request.onblocked = function (event) {
  45736. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  45737. handleError();
  45738. };
  45739. // DB has been opened successfully
  45740. request.onsuccess = function (event) {
  45741. _this.db = request.result;
  45742. successCallback();
  45743. };
  45744. // Initialization of the DB. Creating Scenes & Textures stores
  45745. request.onupgradeneeded = function (event) {
  45746. _this.db = (event.target).result;
  45747. try {
  45748. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  45749. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  45750. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  45751. }
  45752. catch (ex) {
  45753. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  45754. handleError();
  45755. }
  45756. };
  45757. }
  45758. else {
  45759. if (successCallback)
  45760. successCallback();
  45761. }
  45762. }
  45763. };
  45764. Database.prototype.loadImageFromDB = function (url, image) {
  45765. var _this = this;
  45766. var completeURL = Database.ReturnFullUrlLocation(url);
  45767. var saveAndLoadImage = function () {
  45768. if (!_this.hasReachedQuota && _this.db !== null) {
  45769. // the texture is not yet in the DB, let's try to save it
  45770. _this._saveImageIntoDBAsync(completeURL, image);
  45771. }
  45772. else {
  45773. image.src = url;
  45774. }
  45775. };
  45776. if (!this.mustUpdateRessources) {
  45777. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  45778. }
  45779. else {
  45780. saveAndLoadImage();
  45781. }
  45782. };
  45783. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  45784. if (this.isSupported && this.db !== null) {
  45785. var texture;
  45786. var transaction = this.db.transaction(["textures"]);
  45787. transaction.onabort = function (event) {
  45788. image.src = url;
  45789. };
  45790. transaction.oncomplete = function (event) {
  45791. var blobTextureURL;
  45792. if (texture) {
  45793. var URL = window.URL || window.webkitURL;
  45794. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  45795. image.onerror = function () {
  45796. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  45797. image.src = url;
  45798. };
  45799. image.src = blobTextureURL;
  45800. }
  45801. else {
  45802. notInDBCallback();
  45803. }
  45804. };
  45805. var getRequest = transaction.objectStore("textures").get(url);
  45806. getRequest.onsuccess = function (event) {
  45807. texture = (event.target).result;
  45808. };
  45809. getRequest.onerror = function (event) {
  45810. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  45811. image.src = url;
  45812. };
  45813. }
  45814. else {
  45815. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  45816. image.src = url;
  45817. }
  45818. };
  45819. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  45820. var _this = this;
  45821. if (this.isSupported) {
  45822. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  45823. var generateBlobUrl = function () {
  45824. var blobTextureURL;
  45825. if (blob) {
  45826. var URL = window.URL || window.webkitURL;
  45827. try {
  45828. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  45829. }
  45830. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  45831. catch (ex) {
  45832. blobTextureURL = URL.createObjectURL(blob);
  45833. }
  45834. }
  45835. image.src = blobTextureURL;
  45836. };
  45837. if (Database.IsUASupportingBlobStorage) {
  45838. var xhr = new XMLHttpRequest(), blob;
  45839. xhr.open("GET", url, true);
  45840. xhr.responseType = "blob";
  45841. xhr.addEventListener("load", function () {
  45842. if (xhr.status === 200) {
  45843. // Blob as response (XHR2)
  45844. blob = xhr.response;
  45845. var transaction = _this.db.transaction(["textures"], "readwrite");
  45846. // the transaction could abort because of a QuotaExceededError error
  45847. transaction.onabort = function (event) {
  45848. try {
  45849. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  45850. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  45851. _this.hasReachedQuota = true;
  45852. }
  45853. }
  45854. catch (ex) { }
  45855. generateBlobUrl();
  45856. };
  45857. transaction.oncomplete = function (event) {
  45858. generateBlobUrl();
  45859. };
  45860. var newTexture = { textureUrl: url, data: blob };
  45861. try {
  45862. // Put the blob into the dabase
  45863. var addRequest = transaction.objectStore("textures").put(newTexture);
  45864. addRequest.onsuccess = function (event) {
  45865. };
  45866. addRequest.onerror = function (event) {
  45867. generateBlobUrl();
  45868. };
  45869. }
  45870. catch (ex) {
  45871. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  45872. if (ex.code === 25) {
  45873. Database.IsUASupportingBlobStorage = false;
  45874. }
  45875. image.src = url;
  45876. }
  45877. }
  45878. else {
  45879. image.src = url;
  45880. }
  45881. }, false);
  45882. xhr.addEventListener("error", function (event) {
  45883. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  45884. image.src = url;
  45885. }, false);
  45886. xhr.send();
  45887. }
  45888. else {
  45889. image.src = url;
  45890. }
  45891. }
  45892. else {
  45893. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  45894. image.src = url;
  45895. }
  45896. };
  45897. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  45898. var _this = this;
  45899. var updateVersion = function (event) {
  45900. // the version is not yet in the DB or we need to update it
  45901. _this._saveVersionIntoDBAsync(url, versionLoaded);
  45902. };
  45903. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  45904. };
  45905. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  45906. var _this = this;
  45907. if (this.isSupported) {
  45908. var version;
  45909. try {
  45910. var transaction = this.db.transaction(["versions"]);
  45911. transaction.oncomplete = function (event) {
  45912. if (version) {
  45913. // If the version in the JSON file is > than the version in DB
  45914. if (_this.manifestVersionFound > version.data) {
  45915. _this.mustUpdateRessources = true;
  45916. updateInDBCallback();
  45917. }
  45918. else {
  45919. callback(version.data);
  45920. }
  45921. }
  45922. else {
  45923. _this.mustUpdateRessources = true;
  45924. updateInDBCallback();
  45925. }
  45926. };
  45927. transaction.onabort = function (event) {
  45928. callback(-1);
  45929. };
  45930. var getRequest = transaction.objectStore("versions").get(url);
  45931. getRequest.onsuccess = function (event) {
  45932. version = (event.target).result;
  45933. };
  45934. getRequest.onerror = function (event) {
  45935. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  45936. callback(-1);
  45937. };
  45938. }
  45939. catch (ex) {
  45940. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  45941. callback(-1);
  45942. }
  45943. }
  45944. else {
  45945. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  45946. callback(-1);
  45947. }
  45948. };
  45949. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  45950. var _this = this;
  45951. if (this.isSupported && !this.hasReachedQuota) {
  45952. try {
  45953. // Open a transaction to the database
  45954. var transaction = this.db.transaction(["versions"], "readwrite");
  45955. // the transaction could abort because of a QuotaExceededError error
  45956. transaction.onabort = function (event) {
  45957. try {
  45958. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  45959. _this.hasReachedQuota = true;
  45960. }
  45961. }
  45962. catch (ex) { }
  45963. callback(-1);
  45964. };
  45965. transaction.oncomplete = function (event) {
  45966. callback(_this.manifestVersionFound);
  45967. };
  45968. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  45969. // Put the scene into the database
  45970. var addRequest = transaction.objectStore("versions").put(newVersion);
  45971. addRequest.onsuccess = function (event) {
  45972. };
  45973. addRequest.onerror = function (event) {
  45974. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  45975. };
  45976. }
  45977. catch (ex) {
  45978. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  45979. callback(-1);
  45980. }
  45981. }
  45982. else {
  45983. callback(-1);
  45984. }
  45985. };
  45986. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  45987. var _this = this;
  45988. var completeUrl = Database.ReturnFullUrlLocation(url);
  45989. var saveAndLoadFile = function (event) {
  45990. // the scene is not yet in the DB, let's try to save it
  45991. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  45992. };
  45993. this._checkVersionFromDB(completeUrl, function (version) {
  45994. if (version !== -1) {
  45995. if (!_this.mustUpdateRessources) {
  45996. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  45997. }
  45998. else {
  45999. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  46000. }
  46001. }
  46002. else {
  46003. errorCallback();
  46004. }
  46005. });
  46006. };
  46007. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  46008. if (this.isSupported) {
  46009. var targetStore;
  46010. if (url.indexOf(".babylon") !== -1) {
  46011. targetStore = "scenes";
  46012. }
  46013. else {
  46014. targetStore = "textures";
  46015. }
  46016. var file;
  46017. var transaction = this.db.transaction([targetStore]);
  46018. transaction.oncomplete = function (event) {
  46019. if (file) {
  46020. callback(file.data);
  46021. }
  46022. else {
  46023. notInDBCallback();
  46024. }
  46025. };
  46026. transaction.onabort = function (event) {
  46027. notInDBCallback();
  46028. };
  46029. var getRequest = transaction.objectStore(targetStore).get(url);
  46030. getRequest.onsuccess = function (event) {
  46031. file = (event.target).result;
  46032. };
  46033. getRequest.onerror = function (event) {
  46034. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  46035. notInDBCallback();
  46036. };
  46037. }
  46038. else {
  46039. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46040. callback();
  46041. }
  46042. };
  46043. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  46044. var _this = this;
  46045. if (this.isSupported) {
  46046. var targetStore;
  46047. if (url.indexOf(".babylon") !== -1) {
  46048. targetStore = "scenes";
  46049. }
  46050. else {
  46051. targetStore = "textures";
  46052. }
  46053. // Create XHR
  46054. var xhr = new XMLHttpRequest(), fileData;
  46055. xhr.open("GET", url, true);
  46056. if (useArrayBuffer) {
  46057. xhr.responseType = "arraybuffer";
  46058. }
  46059. xhr.onprogress = progressCallback;
  46060. xhr.addEventListener("load", function () {
  46061. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  46062. // Blob as response (XHR2)
  46063. //fileData = xhr.responseText;
  46064. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  46065. if (!_this.hasReachedQuota) {
  46066. // Open a transaction to the database
  46067. var transaction = _this.db.transaction([targetStore], "readwrite");
  46068. // the transaction could abort because of a QuotaExceededError error
  46069. transaction.onabort = function (event) {
  46070. try {
  46071. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  46072. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  46073. _this.hasReachedQuota = true;
  46074. }
  46075. }
  46076. catch (ex) { }
  46077. callback(fileData);
  46078. };
  46079. transaction.oncomplete = function (event) {
  46080. callback(fileData);
  46081. };
  46082. var newFile;
  46083. if (targetStore === "scenes") {
  46084. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  46085. }
  46086. else {
  46087. newFile = { textureUrl: url, data: fileData };
  46088. }
  46089. try {
  46090. // Put the scene into the database
  46091. var addRequest = transaction.objectStore(targetStore).put(newFile);
  46092. addRequest.onsuccess = function (event) {
  46093. };
  46094. addRequest.onerror = function (event) {
  46095. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  46096. };
  46097. }
  46098. catch (ex) {
  46099. callback(fileData);
  46100. }
  46101. }
  46102. else {
  46103. callback(fileData);
  46104. }
  46105. }
  46106. else {
  46107. callback();
  46108. }
  46109. }, false);
  46110. xhr.addEventListener("error", function (event) {
  46111. BABYLON.Tools.Error("error on XHR request.");
  46112. callback();
  46113. }, false);
  46114. xhr.send();
  46115. }
  46116. else {
  46117. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46118. callback();
  46119. }
  46120. };
  46121. return Database;
  46122. }());
  46123. Database.IsUASupportingBlobStorage = true;
  46124. Database.IDBStorageEnabled = true;
  46125. Database.parseURL = function (url) {
  46126. var a = document.createElement('a');
  46127. a.href = url;
  46128. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  46129. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  46130. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  46131. return absLocation;
  46132. };
  46133. Database.ReturnFullUrlLocation = function (url) {
  46134. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  46135. return (Database.parseURL(window.location.href) + url);
  46136. }
  46137. else {
  46138. return url;
  46139. }
  46140. };
  46141. BABYLON.Database = Database;
  46142. })(BABYLON || (BABYLON = {}));
  46143. //# sourceMappingURL=babylon.database.js.map
  46144. var BABYLON;
  46145. (function (BABYLON) {
  46146. var FresnelParameters = (function () {
  46147. function FresnelParameters() {
  46148. this._isEnabled = true;
  46149. this.leftColor = BABYLON.Color3.White();
  46150. this.rightColor = BABYLON.Color3.Black();
  46151. this.bias = 0;
  46152. this.power = 1;
  46153. }
  46154. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  46155. get: function () {
  46156. return this._isEnabled;
  46157. },
  46158. set: function (value) {
  46159. if (this._isEnabled === value) {
  46160. return;
  46161. }
  46162. this._isEnabled = value;
  46163. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  46164. },
  46165. enumerable: true,
  46166. configurable: true
  46167. });
  46168. FresnelParameters.prototype.clone = function () {
  46169. var newFresnelParameters = new FresnelParameters();
  46170. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  46171. return newFresnelParameters;
  46172. };
  46173. FresnelParameters.prototype.serialize = function () {
  46174. var serializationObject = {};
  46175. serializationObject.isEnabled = this.isEnabled;
  46176. serializationObject.leftColor = this.leftColor;
  46177. serializationObject.rightColor = this.rightColor;
  46178. serializationObject.bias = this.bias;
  46179. serializationObject.power = this.power;
  46180. return serializationObject;
  46181. };
  46182. FresnelParameters.Parse = function (parsedFresnelParameters) {
  46183. var fresnelParameters = new FresnelParameters();
  46184. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  46185. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  46186. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  46187. fresnelParameters.bias = parsedFresnelParameters.bias;
  46188. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  46189. return fresnelParameters;
  46190. };
  46191. return FresnelParameters;
  46192. }());
  46193. BABYLON.FresnelParameters = FresnelParameters;
  46194. })(BABYLON || (BABYLON = {}));
  46195. //# sourceMappingURL=babylon.fresnelParameters.js.map
  46196. var BABYLON;
  46197. (function (BABYLON) {
  46198. var MultiMaterial = (function (_super) {
  46199. __extends(MultiMaterial, _super);
  46200. function MultiMaterial(name, scene) {
  46201. var _this = _super.call(this, name, scene, true) || this;
  46202. _this.subMaterials = new Array();
  46203. scene.multiMaterials.push(_this);
  46204. return _this;
  46205. }
  46206. // Properties
  46207. MultiMaterial.prototype.getSubMaterial = function (index) {
  46208. if (index < 0 || index >= this.subMaterials.length) {
  46209. return this.getScene().defaultMaterial;
  46210. }
  46211. return this.subMaterials[index];
  46212. };
  46213. // Methods
  46214. MultiMaterial.prototype.getClassName = function () {
  46215. return "MultiMaterial";
  46216. };
  46217. MultiMaterial.prototype.isReady = function (mesh) {
  46218. for (var index = 0; index < this.subMaterials.length; index++) {
  46219. var subMaterial = this.subMaterials[index];
  46220. if (subMaterial) {
  46221. if (!this.subMaterials[index].isReady(mesh)) {
  46222. return false;
  46223. }
  46224. }
  46225. }
  46226. return true;
  46227. };
  46228. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  46229. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  46230. for (var index = 0; index < this.subMaterials.length; index++) {
  46231. var subMaterial = null;
  46232. if (cloneChildren) {
  46233. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  46234. }
  46235. else {
  46236. subMaterial = this.subMaterials[index];
  46237. }
  46238. newMultiMaterial.subMaterials.push(subMaterial);
  46239. }
  46240. return newMultiMaterial;
  46241. };
  46242. MultiMaterial.prototype.serialize = function () {
  46243. var serializationObject = {};
  46244. serializationObject.name = this.name;
  46245. serializationObject.id = this.id;
  46246. serializationObject.tags = BABYLON.Tags.GetTags(this);
  46247. serializationObject.materials = [];
  46248. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  46249. var subMat = this.subMaterials[matIndex];
  46250. if (subMat) {
  46251. serializationObject.materials.push(subMat.id);
  46252. }
  46253. else {
  46254. serializationObject.materials.push(null);
  46255. }
  46256. }
  46257. return serializationObject;
  46258. };
  46259. return MultiMaterial;
  46260. }(BABYLON.Material));
  46261. BABYLON.MultiMaterial = MultiMaterial;
  46262. })(BABYLON || (BABYLON = {}));
  46263. //# sourceMappingURL=babylon.multiMaterial.js.map
  46264. var BABYLON;
  46265. (function (BABYLON) {
  46266. var FreeCameraTouchInput = (function () {
  46267. function FreeCameraTouchInput() {
  46268. this._offsetX = null;
  46269. this._offsetY = null;
  46270. this._pointerCount = 0;
  46271. this._pointerPressed = [];
  46272. this.touchAngularSensibility = 200000.0;
  46273. this.touchMoveSensibility = 250.0;
  46274. }
  46275. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  46276. var _this = this;
  46277. var previousPosition;
  46278. if (this._pointerInput === undefined) {
  46279. this._onLostFocus = function (evt) {
  46280. _this._offsetX = null;
  46281. _this._offsetY = null;
  46282. };
  46283. this._pointerInput = function (p, s) {
  46284. var evt = p.event;
  46285. if (evt.pointerType === "mouse") {
  46286. return;
  46287. }
  46288. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  46289. if (!noPreventDefault) {
  46290. evt.preventDefault();
  46291. }
  46292. _this._pointerPressed.push(evt.pointerId);
  46293. if (_this._pointerPressed.length !== 1) {
  46294. return;
  46295. }
  46296. previousPosition = {
  46297. x: evt.clientX,
  46298. y: evt.clientY
  46299. };
  46300. }
  46301. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  46302. if (!noPreventDefault) {
  46303. evt.preventDefault();
  46304. }
  46305. var index = _this._pointerPressed.indexOf(evt.pointerId);
  46306. if (index === -1) {
  46307. return;
  46308. }
  46309. _this._pointerPressed.splice(index, 1);
  46310. if (index != 0) {
  46311. return;
  46312. }
  46313. previousPosition = null;
  46314. _this._offsetX = null;
  46315. _this._offsetY = null;
  46316. }
  46317. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46318. if (!noPreventDefault) {
  46319. evt.preventDefault();
  46320. }
  46321. if (!previousPosition) {
  46322. return;
  46323. }
  46324. var index = _this._pointerPressed.indexOf(evt.pointerId);
  46325. if (index != 0) {
  46326. return;
  46327. }
  46328. _this._offsetX = evt.clientX - previousPosition.x;
  46329. _this._offsetY = -(evt.clientY - previousPosition.y);
  46330. }
  46331. };
  46332. }
  46333. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46334. element.addEventListener("blur", this._onLostFocus);
  46335. };
  46336. FreeCameraTouchInput.prototype.detachControl = function (element) {
  46337. if (this._pointerInput && element) {
  46338. this.camera.getScene().onPointerObservable.remove(this._observer);
  46339. this._observer = null;
  46340. element.removeEventListener("blur", this._onLostFocus);
  46341. this._onLostFocus = null;
  46342. this._pointerPressed = [];
  46343. this._offsetX = null;
  46344. this._offsetY = null;
  46345. this._pointerCount = 0;
  46346. }
  46347. };
  46348. FreeCameraTouchInput.prototype.checkInputs = function () {
  46349. if (this._offsetX) {
  46350. var camera = this.camera;
  46351. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  46352. if (this._pointerPressed.length > 1) {
  46353. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  46354. }
  46355. else {
  46356. var speed = camera._computeLocalCameraSpeed();
  46357. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  46358. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  46359. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  46360. }
  46361. }
  46362. };
  46363. FreeCameraTouchInput.prototype.getTypeName = function () {
  46364. return "FreeCameraTouchInput";
  46365. };
  46366. FreeCameraTouchInput.prototype.getSimpleName = function () {
  46367. return "touch";
  46368. };
  46369. return FreeCameraTouchInput;
  46370. }());
  46371. __decorate([
  46372. BABYLON.serialize()
  46373. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  46374. __decorate([
  46375. BABYLON.serialize()
  46376. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  46377. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  46378. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  46379. })(BABYLON || (BABYLON = {}));
  46380. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  46381. /// <reference path="babylon.freeCamera.ts" />
  46382. var BABYLON;
  46383. (function (BABYLON) {
  46384. // We're mainly based on the logic defined into the FreeCamera code
  46385. var TouchCamera = (function (_super) {
  46386. __extends(TouchCamera, _super);
  46387. //-- end properties for backward compatibility for inputs
  46388. function TouchCamera(name, position, scene) {
  46389. var _this = _super.call(this, name, position, scene) || this;
  46390. _this.inputs.addTouch();
  46391. _this._setupInputs();
  46392. return _this;
  46393. }
  46394. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  46395. //-- Begin properties for backward compatibility for inputs
  46396. get: function () {
  46397. var touch = this.inputs.attached["touch"];
  46398. if (touch)
  46399. return touch.touchAngularSensibility;
  46400. },
  46401. set: function (value) {
  46402. var touch = this.inputs.attached["touch"];
  46403. if (touch)
  46404. touch.touchAngularSensibility = value;
  46405. },
  46406. enumerable: true,
  46407. configurable: true
  46408. });
  46409. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  46410. get: function () {
  46411. var touch = this.inputs.attached["touch"];
  46412. if (touch)
  46413. return touch.touchMoveSensibility;
  46414. },
  46415. set: function (value) {
  46416. var touch = this.inputs.attached["touch"];
  46417. if (touch)
  46418. touch.touchMoveSensibility = value;
  46419. },
  46420. enumerable: true,
  46421. configurable: true
  46422. });
  46423. TouchCamera.prototype.getClassName = function () {
  46424. return "TouchCamera";
  46425. };
  46426. TouchCamera.prototype._setupInputs = function () {
  46427. var mouse = this.inputs.attached["mouse"];
  46428. if (mouse) {
  46429. mouse.touchEnabled = false;
  46430. }
  46431. };
  46432. return TouchCamera;
  46433. }(BABYLON.FreeCamera));
  46434. BABYLON.TouchCamera = TouchCamera;
  46435. })(BABYLON || (BABYLON = {}));
  46436. //# sourceMappingURL=babylon.touchCamera.js.map
  46437. var BABYLON;
  46438. (function (BABYLON) {
  46439. var ProceduralTexture = (function (_super) {
  46440. __extends(ProceduralTexture, _super);
  46441. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  46442. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46443. if (isCube === void 0) { isCube = false; }
  46444. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  46445. _this.isCube = isCube;
  46446. _this.isEnabled = true;
  46447. _this._currentRefreshId = -1;
  46448. _this._refreshRate = 1;
  46449. _this._vertexBuffers = {};
  46450. _this._uniforms = new Array();
  46451. _this._samplers = new Array();
  46452. _this._textures = new Array();
  46453. _this._floats = new Array();
  46454. _this._floatsArrays = {};
  46455. _this._colors3 = new Array();
  46456. _this._colors4 = new Array();
  46457. _this._vectors2 = new Array();
  46458. _this._vectors3 = new Array();
  46459. _this._matrices = new Array();
  46460. _this._fallbackTextureUsed = false;
  46461. scene._proceduralTextures.push(_this);
  46462. _this.name = name;
  46463. _this.isRenderTarget = true;
  46464. _this._size = size;
  46465. _this._generateMipMaps = generateMipMaps;
  46466. _this.setFragment(fragment);
  46467. _this._fallbackTexture = fallbackTexture;
  46468. var engine = scene.getEngine();
  46469. if (isCube) {
  46470. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  46471. _this.setFloat("face", 0);
  46472. }
  46473. else {
  46474. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  46475. }
  46476. // VBO
  46477. var vertices = [];
  46478. vertices.push(1, 1);
  46479. vertices.push(-1, 1);
  46480. vertices.push(-1, -1);
  46481. vertices.push(1, -1);
  46482. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  46483. // Indices
  46484. var indices = [];
  46485. indices.push(0);
  46486. indices.push(1);
  46487. indices.push(2);
  46488. indices.push(0);
  46489. indices.push(2);
  46490. indices.push(3);
  46491. _this._indexBuffer = engine.createIndexBuffer(indices);
  46492. return _this;
  46493. }
  46494. ProceduralTexture.prototype.reset = function () {
  46495. if (this._effect === undefined) {
  46496. return;
  46497. }
  46498. var engine = this.getScene().getEngine();
  46499. engine._releaseEffect(this._effect);
  46500. };
  46501. ProceduralTexture.prototype.isReady = function () {
  46502. var _this = this;
  46503. var engine = this.getScene().getEngine();
  46504. var shaders;
  46505. if (!this._fragment) {
  46506. return false;
  46507. }
  46508. if (this._fallbackTextureUsed) {
  46509. return true;
  46510. }
  46511. if (this._fragment.fragmentElement !== undefined) {
  46512. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  46513. }
  46514. else {
  46515. shaders = { vertex: "procedural", fragment: this._fragment };
  46516. }
  46517. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  46518. _this.releaseInternalTexture();
  46519. if (_this._fallbackTexture) {
  46520. _this._texture = _this._fallbackTexture._texture;
  46521. _this._texture.references++;
  46522. }
  46523. _this._fallbackTextureUsed = true;
  46524. });
  46525. return this._effect.isReady();
  46526. };
  46527. ProceduralTexture.prototype.resetRefreshCounter = function () {
  46528. this._currentRefreshId = -1;
  46529. };
  46530. ProceduralTexture.prototype.setFragment = function (fragment) {
  46531. this._fragment = fragment;
  46532. };
  46533. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  46534. get: function () {
  46535. return this._refreshRate;
  46536. },
  46537. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  46538. set: function (value) {
  46539. this._refreshRate = value;
  46540. this.resetRefreshCounter();
  46541. },
  46542. enumerable: true,
  46543. configurable: true
  46544. });
  46545. ProceduralTexture.prototype._shouldRender = function () {
  46546. if (!this.isEnabled || !this.isReady() || !this._texture) {
  46547. return false;
  46548. }
  46549. if (this._fallbackTextureUsed) {
  46550. return false;
  46551. }
  46552. if (this._currentRefreshId === -1) {
  46553. this._currentRefreshId = 1;
  46554. return true;
  46555. }
  46556. if (this.refreshRate === this._currentRefreshId) {
  46557. this._currentRefreshId = 1;
  46558. return true;
  46559. }
  46560. this._currentRefreshId++;
  46561. return false;
  46562. };
  46563. ProceduralTexture.prototype.getRenderSize = function () {
  46564. return this._size;
  46565. };
  46566. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  46567. if (this._fallbackTextureUsed) {
  46568. return;
  46569. }
  46570. this.releaseInternalTexture();
  46571. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  46572. };
  46573. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  46574. if (this._uniforms.indexOf(uniformName) === -1) {
  46575. this._uniforms.push(uniformName);
  46576. }
  46577. };
  46578. ProceduralTexture.prototype.setTexture = function (name, texture) {
  46579. if (this._samplers.indexOf(name) === -1) {
  46580. this._samplers.push(name);
  46581. }
  46582. this._textures[name] = texture;
  46583. return this;
  46584. };
  46585. ProceduralTexture.prototype.setFloat = function (name, value) {
  46586. this._checkUniform(name);
  46587. this._floats[name] = value;
  46588. return this;
  46589. };
  46590. ProceduralTexture.prototype.setFloats = function (name, value) {
  46591. this._checkUniform(name);
  46592. this._floatsArrays[name] = value;
  46593. return this;
  46594. };
  46595. ProceduralTexture.prototype.setColor3 = function (name, value) {
  46596. this._checkUniform(name);
  46597. this._colors3[name] = value;
  46598. return this;
  46599. };
  46600. ProceduralTexture.prototype.setColor4 = function (name, value) {
  46601. this._checkUniform(name);
  46602. this._colors4[name] = value;
  46603. return this;
  46604. };
  46605. ProceduralTexture.prototype.setVector2 = function (name, value) {
  46606. this._checkUniform(name);
  46607. this._vectors2[name] = value;
  46608. return this;
  46609. };
  46610. ProceduralTexture.prototype.setVector3 = function (name, value) {
  46611. this._checkUniform(name);
  46612. this._vectors3[name] = value;
  46613. return this;
  46614. };
  46615. ProceduralTexture.prototype.setMatrix = function (name, value) {
  46616. this._checkUniform(name);
  46617. this._matrices[name] = value;
  46618. return this;
  46619. };
  46620. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  46621. var scene = this.getScene();
  46622. var engine = scene.getEngine();
  46623. // Render
  46624. engine.enableEffect(this._effect);
  46625. engine.setState(false);
  46626. // Texture
  46627. for (var name in this._textures) {
  46628. this._effect.setTexture(name, this._textures[name]);
  46629. }
  46630. // Float
  46631. for (name in this._floats) {
  46632. this._effect.setFloat(name, this._floats[name]);
  46633. }
  46634. // Floats
  46635. for (name in this._floatsArrays) {
  46636. this._effect.setArray(name, this._floatsArrays[name]);
  46637. }
  46638. // Color3
  46639. for (name in this._colors3) {
  46640. this._effect.setColor3(name, this._colors3[name]);
  46641. }
  46642. // Color4
  46643. for (name in this._colors4) {
  46644. var color = this._colors4[name];
  46645. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46646. }
  46647. // Vector2
  46648. for (name in this._vectors2) {
  46649. this._effect.setVector2(name, this._vectors2[name]);
  46650. }
  46651. // Vector3
  46652. for (name in this._vectors3) {
  46653. this._effect.setVector3(name, this._vectors3[name]);
  46654. }
  46655. // Matrix
  46656. for (name in this._matrices) {
  46657. this._effect.setMatrix(name, this._matrices[name]);
  46658. }
  46659. if (this.isCube) {
  46660. for (var face = 0; face < 6; face++) {
  46661. engine.bindFramebuffer(this._texture, face);
  46662. // VBOs
  46663. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46664. this._effect.setFloat("face", face);
  46665. // Clear
  46666. engine.clear(scene.clearColor, true, true, true);
  46667. // Draw order
  46668. engine.draw(true, 0, 6);
  46669. // Mipmaps
  46670. if (face === 5) {
  46671. engine.generateMipMapsForCubemap(this._texture);
  46672. }
  46673. }
  46674. }
  46675. else {
  46676. engine.bindFramebuffer(this._texture);
  46677. // VBOs
  46678. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46679. // Clear
  46680. engine.clear(scene.clearColor, true, true, true);
  46681. // Draw order
  46682. engine.draw(true, 0, 6);
  46683. }
  46684. // Unbind
  46685. engine.unBindFramebuffer(this._texture, this.isCube);
  46686. if (this.onGenerated) {
  46687. this.onGenerated();
  46688. }
  46689. };
  46690. ProceduralTexture.prototype.clone = function () {
  46691. var textureSize = this.getSize();
  46692. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  46693. // Base texture
  46694. newTexture.hasAlpha = this.hasAlpha;
  46695. newTexture.level = this.level;
  46696. // RenderTarget Texture
  46697. newTexture.coordinatesMode = this.coordinatesMode;
  46698. return newTexture;
  46699. };
  46700. ProceduralTexture.prototype.dispose = function () {
  46701. var index = this.getScene()._proceduralTextures.indexOf(this);
  46702. if (index >= 0) {
  46703. this.getScene()._proceduralTextures.splice(index, 1);
  46704. }
  46705. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46706. if (vertexBuffer) {
  46707. vertexBuffer.dispose();
  46708. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46709. }
  46710. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  46711. this._indexBuffer = null;
  46712. }
  46713. _super.prototype.dispose.call(this);
  46714. };
  46715. return ProceduralTexture;
  46716. }(BABYLON.Texture));
  46717. BABYLON.ProceduralTexture = ProceduralTexture;
  46718. })(BABYLON || (BABYLON = {}));
  46719. //# sourceMappingURL=babylon.proceduralTexture.js.map
  46720. /// <reference path="babylon.proceduralTexture.ts" />
  46721. var BABYLON;
  46722. (function (BABYLON) {
  46723. var CustomProceduralTexture = (function (_super) {
  46724. __extends(CustomProceduralTexture, _super);
  46725. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  46726. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  46727. _this._animate = true;
  46728. _this._time = 0;
  46729. _this._texturePath = texturePath;
  46730. //Try to load json
  46731. _this.loadJson(texturePath);
  46732. _this.refreshRate = 1;
  46733. return _this;
  46734. }
  46735. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  46736. var _this = this;
  46737. var that = this;
  46738. function noConfigFile() {
  46739. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  46740. try {
  46741. that.setFragment(that._texturePath);
  46742. }
  46743. catch (ex) {
  46744. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  46745. }
  46746. }
  46747. var configFileUrl = jsonUrl + "/config.json";
  46748. var xhr = new XMLHttpRequest();
  46749. xhr.open("GET", configFileUrl, true);
  46750. xhr.addEventListener("load", function () {
  46751. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  46752. try {
  46753. _this._config = JSON.parse(xhr.response);
  46754. _this.updateShaderUniforms();
  46755. _this.updateTextures();
  46756. _this.setFragment(_this._texturePath + "/custom");
  46757. _this._animate = _this._config.animate;
  46758. _this.refreshRate = _this._config.refreshrate;
  46759. }
  46760. catch (ex) {
  46761. noConfigFile();
  46762. }
  46763. }
  46764. else {
  46765. noConfigFile();
  46766. }
  46767. }, false);
  46768. xhr.addEventListener("error", function () {
  46769. noConfigFile();
  46770. }, false);
  46771. try {
  46772. xhr.send();
  46773. }
  46774. catch (ex) {
  46775. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  46776. }
  46777. };
  46778. CustomProceduralTexture.prototype.isReady = function () {
  46779. if (!_super.prototype.isReady.call(this)) {
  46780. return false;
  46781. }
  46782. for (var name in this._textures) {
  46783. var texture = this._textures[name];
  46784. if (!texture.isReady()) {
  46785. return false;
  46786. }
  46787. }
  46788. return true;
  46789. };
  46790. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  46791. if (this._animate) {
  46792. this._time += this.getScene().getAnimationRatio() * 0.03;
  46793. this.updateShaderUniforms();
  46794. }
  46795. _super.prototype.render.call(this, useCameraPostProcess);
  46796. };
  46797. CustomProceduralTexture.prototype.updateTextures = function () {
  46798. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  46799. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  46800. }
  46801. };
  46802. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  46803. if (this._config) {
  46804. for (var j = 0; j < this._config.uniforms.length; j++) {
  46805. var uniform = this._config.uniforms[j];
  46806. switch (uniform.type) {
  46807. case "float":
  46808. this.setFloat(uniform.name, uniform.value);
  46809. break;
  46810. case "color3":
  46811. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  46812. break;
  46813. case "color4":
  46814. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  46815. break;
  46816. case "vector2":
  46817. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  46818. break;
  46819. case "vector3":
  46820. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  46821. break;
  46822. }
  46823. }
  46824. }
  46825. this.setFloat("time", this._time);
  46826. };
  46827. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  46828. get: function () {
  46829. return this._animate;
  46830. },
  46831. set: function (value) {
  46832. this._animate = value;
  46833. },
  46834. enumerable: true,
  46835. configurable: true
  46836. });
  46837. return CustomProceduralTexture;
  46838. }(BABYLON.ProceduralTexture));
  46839. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  46840. })(BABYLON || (BABYLON = {}));
  46841. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  46842. var BABYLON;
  46843. (function (BABYLON) {
  46844. var FreeCameraGamepadInput = (function () {
  46845. function FreeCameraGamepadInput() {
  46846. this.gamepadAngularSensibility = 200;
  46847. this.gamepadMoveSensibility = 40;
  46848. // private members
  46849. this._cameraTransform = BABYLON.Matrix.Identity();
  46850. this._deltaTransform = BABYLON.Vector3.Zero();
  46851. this._vector3 = BABYLON.Vector3.Zero();
  46852. this._vector2 = BABYLON.Vector2.Zero();
  46853. }
  46854. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  46855. var _this = this;
  46856. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  46857. };
  46858. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  46859. if (this._gamepads) {
  46860. this._gamepads.dispose();
  46861. }
  46862. this.gamepad = null;
  46863. };
  46864. FreeCameraGamepadInput.prototype.checkInputs = function () {
  46865. if (this.gamepad && this.gamepad.leftStick) {
  46866. var camera = this.camera;
  46867. var LSValues = this.gamepad.leftStick;
  46868. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  46869. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  46870. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  46871. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  46872. var RSValues = this.gamepad.rightStick;
  46873. if (RSValues) {
  46874. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  46875. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  46876. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  46877. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  46878. }
  46879. else {
  46880. RSValues = { x: 0, y: 0 };
  46881. }
  46882. if (!camera.rotationQuaternion) {
  46883. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  46884. }
  46885. else {
  46886. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  46887. }
  46888. var speed = camera._computeLocalCameraSpeed() * 50.0;
  46889. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  46890. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  46891. camera.cameraDirection.addInPlace(this._deltaTransform);
  46892. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  46893. camera.cameraRotation.addInPlace(this._vector2);
  46894. }
  46895. };
  46896. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  46897. // Only the first gamepad found can control the camera
  46898. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  46899. // prioritize XBOX gamepads.
  46900. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  46901. this.gamepad = gamepad;
  46902. }
  46903. }
  46904. };
  46905. FreeCameraGamepadInput.prototype.getTypeName = function () {
  46906. return "FreeCameraGamepadInput";
  46907. };
  46908. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  46909. return "gamepad";
  46910. };
  46911. return FreeCameraGamepadInput;
  46912. }());
  46913. __decorate([
  46914. BABYLON.serialize()
  46915. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  46916. __decorate([
  46917. BABYLON.serialize()
  46918. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  46919. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  46920. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  46921. })(BABYLON || (BABYLON = {}));
  46922. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  46923. var BABYLON;
  46924. (function (BABYLON) {
  46925. var ArcRotateCameraGamepadInput = (function () {
  46926. function ArcRotateCameraGamepadInput() {
  46927. this.gamepadRotationSensibility = 80;
  46928. this.gamepadMoveSensibility = 40;
  46929. }
  46930. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  46931. var _this = this;
  46932. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  46933. };
  46934. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  46935. if (this._gamepads) {
  46936. this._gamepads.dispose();
  46937. }
  46938. this.gamepad = null;
  46939. };
  46940. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  46941. if (this.gamepad) {
  46942. var camera = this.camera;
  46943. var RSValues = this.gamepad.rightStick;
  46944. if (RSValues) {
  46945. if (RSValues.x != 0) {
  46946. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  46947. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  46948. camera.inertialAlphaOffset += normalizedRX;
  46949. }
  46950. }
  46951. if (RSValues.y != 0) {
  46952. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  46953. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  46954. camera.inertialBetaOffset += normalizedRY;
  46955. }
  46956. }
  46957. }
  46958. var LSValues = this.gamepad.leftStick;
  46959. if (LSValues && LSValues.y != 0) {
  46960. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  46961. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  46962. this.camera.inertialRadiusOffset -= normalizedLY;
  46963. }
  46964. }
  46965. }
  46966. };
  46967. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  46968. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  46969. // prioritize XBOX gamepads.
  46970. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  46971. this.gamepad = gamepad;
  46972. }
  46973. }
  46974. };
  46975. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  46976. return "ArcRotateCameraGamepadInput";
  46977. };
  46978. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  46979. return "gamepad";
  46980. };
  46981. return ArcRotateCameraGamepadInput;
  46982. }());
  46983. __decorate([
  46984. BABYLON.serialize()
  46985. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  46986. __decorate([
  46987. BABYLON.serialize()
  46988. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  46989. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  46990. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  46991. })(BABYLON || (BABYLON = {}));
  46992. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  46993. var BABYLON;
  46994. (function (BABYLON) {
  46995. var Gamepads = (function () {
  46996. function Gamepads(ongamedpadconnected) {
  46997. var _this = this;
  46998. this.babylonGamepads = [];
  46999. this.oneGamepadConnected = false;
  47000. this.isMonitoring = false;
  47001. this.gamepadEventSupported = 'GamepadEvent' in window;
  47002. this.gamepadSupport = (navigator.getGamepads ||
  47003. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  47004. this._callbackGamepadConnected = ongamedpadconnected;
  47005. if (this.gamepadSupport) {
  47006. //first add already-connected gamepads
  47007. this._updateGamepadObjects();
  47008. if (this.babylonGamepads.length) {
  47009. this._startMonitoringGamepads();
  47010. }
  47011. // Checking if the gamepad connected event is supported (like in Firefox)
  47012. if (this.gamepadEventSupported) {
  47013. this._onGamepadConnectedEvent = function (evt) {
  47014. _this._onGamepadConnected(evt.gamepad);
  47015. };
  47016. this._onGamepadDisonnectedEvent = function (evt) {
  47017. _this._onGamepadDisconnected(evt);
  47018. };
  47019. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  47020. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  47021. }
  47022. else {
  47023. this._startMonitoringGamepads();
  47024. }
  47025. }
  47026. }
  47027. Gamepads.prototype.dispose = function () {
  47028. if (Gamepads.gamepadDOMInfo) {
  47029. document.body.removeChild(Gamepads.gamepadDOMInfo);
  47030. }
  47031. if (this._onGamepadConnectedEvent) {
  47032. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  47033. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  47034. this._onGamepadConnectedEvent = null;
  47035. this._onGamepadDisonnectedEvent = null;
  47036. }
  47037. };
  47038. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  47039. var newGamepad = this._addNewGamepad(gamepad);
  47040. if (this._callbackGamepadConnected)
  47041. this._callbackGamepadConnected(newGamepad);
  47042. this._startMonitoringGamepads();
  47043. };
  47044. Gamepads.prototype._addNewGamepad = function (gamepad) {
  47045. if (!this.oneGamepadConnected) {
  47046. this.oneGamepadConnected = true;
  47047. if (Gamepads.gamepadDOMInfo) {
  47048. document.body.removeChild(Gamepads.gamepadDOMInfo);
  47049. Gamepads.gamepadDOMInfo = null;
  47050. }
  47051. }
  47052. var newGamepad;
  47053. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  47054. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  47055. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  47056. }
  47057. else if (gamepad.pose) {
  47058. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  47059. }
  47060. else {
  47061. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  47062. }
  47063. this.babylonGamepads.push(newGamepad);
  47064. return newGamepad;
  47065. };
  47066. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  47067. // Remove the gamepad from the list of gamepads to monitor.
  47068. for (var i in this.babylonGamepads) {
  47069. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  47070. this.babylonGamepads.splice(+i, 1);
  47071. break;
  47072. }
  47073. }
  47074. // If no gamepads are left, stop the polling loop.
  47075. if (this.babylonGamepads.length == 0) {
  47076. this._stopMonitoringGamepads();
  47077. }
  47078. };
  47079. Gamepads.prototype._startMonitoringGamepads = function () {
  47080. if (!this.isMonitoring) {
  47081. this.isMonitoring = true;
  47082. this._checkGamepadsStatus();
  47083. }
  47084. };
  47085. Gamepads.prototype._stopMonitoringGamepads = function () {
  47086. this.isMonitoring = false;
  47087. };
  47088. Gamepads.prototype._checkGamepadsStatus = function () {
  47089. var _this = this;
  47090. // updating gamepad objects
  47091. this._updateGamepadObjects();
  47092. for (var i in this.babylonGamepads) {
  47093. this.babylonGamepads[i].update();
  47094. }
  47095. if (this.isMonitoring) {
  47096. if (window.requestAnimationFrame) {
  47097. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47098. }
  47099. else if (window.mozRequestAnimationFrame) {
  47100. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47101. }
  47102. else if (window.webkitRequestAnimationFrame) {
  47103. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47104. }
  47105. }
  47106. };
  47107. // This function is called only on Chrome, which does not yet support
  47108. // connection/disconnection events, but requires you to monitor
  47109. // an array for changes.
  47110. Gamepads.prototype._updateGamepadObjects = function () {
  47111. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  47112. for (var i = 0; i < gamepads.length; i++) {
  47113. if (gamepads[i]) {
  47114. if (!(gamepads[i].index in this.babylonGamepads)) {
  47115. var newGamepad = this._addNewGamepad(gamepads[i]);
  47116. if (this._callbackGamepadConnected) {
  47117. this._callbackGamepadConnected(newGamepad);
  47118. }
  47119. }
  47120. else {
  47121. this.babylonGamepads[i].browserGamepad = gamepads[i];
  47122. }
  47123. }
  47124. }
  47125. };
  47126. return Gamepads;
  47127. }());
  47128. BABYLON.Gamepads = Gamepads;
  47129. var StickValues = (function () {
  47130. function StickValues(x, y) {
  47131. this.x = x;
  47132. this.y = y;
  47133. }
  47134. return StickValues;
  47135. }());
  47136. BABYLON.StickValues = StickValues;
  47137. var Gamepad = (function () {
  47138. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  47139. if (leftStickX === void 0) { leftStickX = 0; }
  47140. if (leftStickY === void 0) { leftStickY = 1; }
  47141. if (rightStickX === void 0) { rightStickX = 2; }
  47142. if (rightStickY === void 0) { rightStickY = 3; }
  47143. this.id = id;
  47144. this.index = index;
  47145. this.browserGamepad = browserGamepad;
  47146. this.type = Gamepad.GAMEPAD;
  47147. this._leftStickAxisX = leftStickX;
  47148. this._leftStickAxisY = leftStickY;
  47149. this._rightStickAxisX = rightStickX;
  47150. this._rightStickAxisY = rightStickY;
  47151. if (this.browserGamepad.axes.length >= 2) {
  47152. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47153. }
  47154. if (this.browserGamepad.axes.length >= 4) {
  47155. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47156. }
  47157. }
  47158. Gamepad.prototype.onleftstickchanged = function (callback) {
  47159. this._onleftstickchanged = callback;
  47160. };
  47161. Gamepad.prototype.onrightstickchanged = function (callback) {
  47162. this._onrightstickchanged = callback;
  47163. };
  47164. Object.defineProperty(Gamepad.prototype, "leftStick", {
  47165. get: function () {
  47166. return this._leftStick;
  47167. },
  47168. set: function (newValues) {
  47169. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  47170. this._onleftstickchanged(newValues);
  47171. }
  47172. this._leftStick = newValues;
  47173. },
  47174. enumerable: true,
  47175. configurable: true
  47176. });
  47177. Object.defineProperty(Gamepad.prototype, "rightStick", {
  47178. get: function () {
  47179. return this._rightStick;
  47180. },
  47181. set: function (newValues) {
  47182. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  47183. this._onrightstickchanged(newValues);
  47184. }
  47185. this._rightStick = newValues;
  47186. },
  47187. enumerable: true,
  47188. configurable: true
  47189. });
  47190. Gamepad.prototype.update = function () {
  47191. if (this._leftStick) {
  47192. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47193. }
  47194. if (this._rightStick) {
  47195. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47196. }
  47197. };
  47198. return Gamepad;
  47199. }());
  47200. Gamepad.GAMEPAD = 0;
  47201. Gamepad.GENERIC = 1;
  47202. Gamepad.XBOX = 2;
  47203. Gamepad.POSE_ENABLED = 3;
  47204. BABYLON.Gamepad = Gamepad;
  47205. var GenericPad = (function (_super) {
  47206. __extends(GenericPad, _super);
  47207. function GenericPad(id, index, gamepad) {
  47208. var _this = _super.call(this, id, index, gamepad) || this;
  47209. _this.id = id;
  47210. _this.index = index;
  47211. _this.gamepad = gamepad;
  47212. _this.type = Gamepad.GENERIC;
  47213. _this._buttons = new Array(gamepad.buttons.length);
  47214. return _this;
  47215. }
  47216. GenericPad.prototype.onbuttondown = function (callback) {
  47217. this._onbuttondown = callback;
  47218. };
  47219. GenericPad.prototype.onbuttonup = function (callback) {
  47220. this._onbuttonup = callback;
  47221. };
  47222. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  47223. if (newValue !== currentValue) {
  47224. if (this._onbuttondown && newValue === 1) {
  47225. this._onbuttondown(buttonIndex);
  47226. }
  47227. if (this._onbuttonup && newValue === 0) {
  47228. this._onbuttonup(buttonIndex);
  47229. }
  47230. }
  47231. return newValue;
  47232. };
  47233. GenericPad.prototype.update = function () {
  47234. _super.prototype.update.call(this);
  47235. for (var index = 0; index < this._buttons.length; index++) {
  47236. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  47237. }
  47238. };
  47239. return GenericPad;
  47240. }(Gamepad));
  47241. BABYLON.GenericPad = GenericPad;
  47242. var Xbox360Button;
  47243. (function (Xbox360Button) {
  47244. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  47245. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  47246. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  47247. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  47248. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  47249. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  47250. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  47251. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  47252. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  47253. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  47254. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  47255. var Xbox360Dpad;
  47256. (function (Xbox360Dpad) {
  47257. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  47258. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  47259. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  47260. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  47261. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  47262. var Xbox360Pad = (function (_super) {
  47263. __extends(Xbox360Pad, _super);
  47264. function Xbox360Pad(id, index, gamepad, xboxOne) {
  47265. if (xboxOne === void 0) { xboxOne = false; }
  47266. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  47267. _this._leftTrigger = 0;
  47268. _this._rightTrigger = 0;
  47269. _this._buttonA = 0;
  47270. _this._buttonB = 0;
  47271. _this._buttonX = 0;
  47272. _this._buttonY = 0;
  47273. _this._buttonBack = 0;
  47274. _this._buttonStart = 0;
  47275. _this._buttonLB = 0;
  47276. _this._buttonRB = 0;
  47277. _this._buttonLeftStick = 0;
  47278. _this._buttonRightStick = 0;
  47279. _this._dPadUp = 0;
  47280. _this._dPadDown = 0;
  47281. _this._dPadLeft = 0;
  47282. _this._dPadRight = 0;
  47283. _this._isXboxOnePad = false;
  47284. _this.type = Gamepad.XBOX;
  47285. _this._isXboxOnePad = xboxOne;
  47286. return _this;
  47287. }
  47288. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  47289. this._onlefttriggerchanged = callback;
  47290. };
  47291. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  47292. this._onrighttriggerchanged = callback;
  47293. };
  47294. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  47295. get: function () {
  47296. return this._leftTrigger;
  47297. },
  47298. set: function (newValue) {
  47299. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  47300. this._onlefttriggerchanged(newValue);
  47301. }
  47302. this._leftTrigger = newValue;
  47303. },
  47304. enumerable: true,
  47305. configurable: true
  47306. });
  47307. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  47308. get: function () {
  47309. return this._rightTrigger;
  47310. },
  47311. set: function (newValue) {
  47312. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  47313. this._onrighttriggerchanged(newValue);
  47314. }
  47315. this._rightTrigger = newValue;
  47316. },
  47317. enumerable: true,
  47318. configurable: true
  47319. });
  47320. Xbox360Pad.prototype.onbuttondown = function (callback) {
  47321. this._onbuttondown = callback;
  47322. };
  47323. Xbox360Pad.prototype.onbuttonup = function (callback) {
  47324. this._onbuttonup = callback;
  47325. };
  47326. Xbox360Pad.prototype.ondpaddown = function (callback) {
  47327. this._ondpaddown = callback;
  47328. };
  47329. Xbox360Pad.prototype.ondpadup = function (callback) {
  47330. this._ondpadup = callback;
  47331. };
  47332. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  47333. if (newValue !== currentValue) {
  47334. if (this._onbuttondown && newValue === 1) {
  47335. this._onbuttondown(buttonType);
  47336. }
  47337. if (this._onbuttonup && newValue === 0) {
  47338. this._onbuttonup(buttonType);
  47339. }
  47340. }
  47341. return newValue;
  47342. };
  47343. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  47344. if (newValue !== currentValue) {
  47345. if (this._ondpaddown && newValue === 1) {
  47346. this._ondpaddown(buttonType);
  47347. }
  47348. if (this._ondpadup && newValue === 0) {
  47349. this._ondpadup(buttonType);
  47350. }
  47351. }
  47352. return newValue;
  47353. };
  47354. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  47355. get: function () {
  47356. return this._buttonA;
  47357. },
  47358. set: function (value) {
  47359. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  47360. },
  47361. enumerable: true,
  47362. configurable: true
  47363. });
  47364. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  47365. get: function () {
  47366. return this._buttonB;
  47367. },
  47368. set: function (value) {
  47369. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  47370. },
  47371. enumerable: true,
  47372. configurable: true
  47373. });
  47374. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  47375. get: function () {
  47376. return this._buttonX;
  47377. },
  47378. set: function (value) {
  47379. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  47380. },
  47381. enumerable: true,
  47382. configurable: true
  47383. });
  47384. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  47385. get: function () {
  47386. return this._buttonY;
  47387. },
  47388. set: function (value) {
  47389. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  47390. },
  47391. enumerable: true,
  47392. configurable: true
  47393. });
  47394. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  47395. get: function () {
  47396. return this._buttonStart;
  47397. },
  47398. set: function (value) {
  47399. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  47400. },
  47401. enumerable: true,
  47402. configurable: true
  47403. });
  47404. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  47405. get: function () {
  47406. return this._buttonBack;
  47407. },
  47408. set: function (value) {
  47409. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  47410. },
  47411. enumerable: true,
  47412. configurable: true
  47413. });
  47414. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  47415. get: function () {
  47416. return this._buttonLB;
  47417. },
  47418. set: function (value) {
  47419. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  47420. },
  47421. enumerable: true,
  47422. configurable: true
  47423. });
  47424. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  47425. get: function () {
  47426. return this._buttonRB;
  47427. },
  47428. set: function (value) {
  47429. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  47430. },
  47431. enumerable: true,
  47432. configurable: true
  47433. });
  47434. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  47435. get: function () {
  47436. return this._buttonLeftStick;
  47437. },
  47438. set: function (value) {
  47439. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  47440. },
  47441. enumerable: true,
  47442. configurable: true
  47443. });
  47444. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  47445. get: function () {
  47446. return this._buttonRightStick;
  47447. },
  47448. set: function (value) {
  47449. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  47450. },
  47451. enumerable: true,
  47452. configurable: true
  47453. });
  47454. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  47455. get: function () {
  47456. return this._dPadUp;
  47457. },
  47458. set: function (value) {
  47459. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  47460. },
  47461. enumerable: true,
  47462. configurable: true
  47463. });
  47464. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  47465. get: function () {
  47466. return this._dPadDown;
  47467. },
  47468. set: function (value) {
  47469. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  47470. },
  47471. enumerable: true,
  47472. configurable: true
  47473. });
  47474. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  47475. get: function () {
  47476. return this._dPadLeft;
  47477. },
  47478. set: function (value) {
  47479. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  47480. },
  47481. enumerable: true,
  47482. configurable: true
  47483. });
  47484. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  47485. get: function () {
  47486. return this._dPadRight;
  47487. },
  47488. set: function (value) {
  47489. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  47490. },
  47491. enumerable: true,
  47492. configurable: true
  47493. });
  47494. Xbox360Pad.prototype.update = function () {
  47495. _super.prototype.update.call(this);
  47496. if (this._isXboxOnePad) {
  47497. this.buttonA = this.browserGamepad.buttons[0].value;
  47498. this.buttonB = this.browserGamepad.buttons[1].value;
  47499. this.buttonX = this.browserGamepad.buttons[2].value;
  47500. this.buttonY = this.browserGamepad.buttons[3].value;
  47501. this.buttonLB = this.browserGamepad.buttons[4].value;
  47502. this.buttonRB = this.browserGamepad.buttons[5].value;
  47503. this.leftTrigger = this.browserGamepad.axes[2];
  47504. this.rightTrigger = this.browserGamepad.axes[5];
  47505. this.buttonBack = this.browserGamepad.buttons[9].value;
  47506. this.buttonStart = this.browserGamepad.buttons[8].value;
  47507. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  47508. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  47509. this.dPadUp = this.browserGamepad.buttons[11].value;
  47510. this.dPadDown = this.browserGamepad.buttons[12].value;
  47511. this.dPadLeft = this.browserGamepad.buttons[13].value;
  47512. this.dPadRight = this.browserGamepad.buttons[14].value;
  47513. }
  47514. else {
  47515. this.buttonA = this.browserGamepad.buttons[0].value;
  47516. this.buttonB = this.browserGamepad.buttons[1].value;
  47517. this.buttonX = this.browserGamepad.buttons[2].value;
  47518. this.buttonY = this.browserGamepad.buttons[3].value;
  47519. this.buttonLB = this.browserGamepad.buttons[4].value;
  47520. this.buttonRB = this.browserGamepad.buttons[5].value;
  47521. this.leftTrigger = this.browserGamepad.buttons[6].value;
  47522. this.rightTrigger = this.browserGamepad.buttons[7].value;
  47523. this.buttonBack = this.browserGamepad.buttons[8].value;
  47524. this.buttonStart = this.browserGamepad.buttons[9].value;
  47525. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  47526. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  47527. this.dPadUp = this.browserGamepad.buttons[12].value;
  47528. this.dPadDown = this.browserGamepad.buttons[13].value;
  47529. this.dPadLeft = this.browserGamepad.buttons[14].value;
  47530. this.dPadRight = this.browserGamepad.buttons[15].value;
  47531. }
  47532. };
  47533. return Xbox360Pad;
  47534. }(Gamepad));
  47535. BABYLON.Xbox360Pad = Xbox360Pad;
  47536. })(BABYLON || (BABYLON = {}));
  47537. //# sourceMappingURL=babylon.gamepads.js.map
  47538. var BABYLON;
  47539. (function (BABYLON) {
  47540. var PoseEnabledControllerType;
  47541. (function (PoseEnabledControllerType) {
  47542. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  47543. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  47544. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  47545. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  47546. var PoseEnabledControllerHelper = (function () {
  47547. function PoseEnabledControllerHelper() {
  47548. }
  47549. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  47550. // for now, only Oculus and Vive are supported
  47551. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  47552. return new OculusTouchController(vrGamepad);
  47553. }
  47554. else {
  47555. return new ViveController(vrGamepad);
  47556. }
  47557. };
  47558. return PoseEnabledControllerHelper;
  47559. }());
  47560. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  47561. var PoseEnabledController = (function (_super) {
  47562. __extends(PoseEnabledController, _super);
  47563. function PoseEnabledController(vrGamepad) {
  47564. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  47565. _this.vrGamepad = vrGamepad;
  47566. _this.deviceScaleFactor = 1;
  47567. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  47568. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  47569. _this.controllerType = PoseEnabledControllerType.GENERIC;
  47570. _this.position = BABYLON.Vector3.Zero();
  47571. _this.rotationQuaternion = new BABYLON.Quaternion();
  47572. _this.devicePosition = BABYLON.Vector3.Zero();
  47573. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  47574. _this._calculatedPosition = BABYLON.Vector3.Zero();
  47575. _this._calculatedRotation = new BABYLON.Quaternion();
  47576. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  47577. return _this;
  47578. }
  47579. PoseEnabledController.prototype.update = function () {
  47580. _super.prototype.update.call(this);
  47581. var pose = this.vrGamepad.pose;
  47582. this.updateFromDevice(pose);
  47583. if (this._mesh) {
  47584. this._mesh.position.copyFrom(this._calculatedPosition);
  47585. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  47586. }
  47587. };
  47588. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  47589. if (poseData) {
  47590. this.rawPose = poseData;
  47591. if (poseData.position) {
  47592. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  47593. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  47594. this.devicePosition.z *= -1;
  47595. }
  47596. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  47597. this._calculatedPosition.addInPlace(this.position);
  47598. }
  47599. if (poseData.orientation) {
  47600. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  47601. if (this._mesh) {
  47602. if (this._mesh.getScene().useRightHandedSystem) {
  47603. this.deviceRotationQuaternion.z *= -1;
  47604. this.deviceRotationQuaternion.w *= -1;
  47605. }
  47606. else {
  47607. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  47608. }
  47609. }
  47610. // if the camera is set, rotate to the camera's rotation
  47611. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  47612. }
  47613. }
  47614. };
  47615. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  47616. if (this._mesh) {
  47617. this._mesh.parent = undefined;
  47618. }
  47619. this._mesh = mesh;
  47620. if (this._poseControlledCamera) {
  47621. this._mesh.parent = this._poseControlledCamera;
  47622. }
  47623. if (!this._mesh.rotationQuaternion) {
  47624. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  47625. }
  47626. };
  47627. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  47628. this._poseControlledCamera = camera;
  47629. if (this._mesh) {
  47630. this._mesh.parent = this._poseControlledCamera;
  47631. }
  47632. };
  47633. PoseEnabledController.prototype.detachMesh = function () {
  47634. this._mesh = undefined;
  47635. };
  47636. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  47637. get: function () {
  47638. return this._mesh;
  47639. },
  47640. enumerable: true,
  47641. configurable: true
  47642. });
  47643. PoseEnabledController.prototype.getForwardRay = function (length) {
  47644. if (length === void 0) { length = 100; }
  47645. if (!this.mesh) {
  47646. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  47647. }
  47648. var m = this.mesh.getWorldMatrix();
  47649. var origin = m.getTranslation();
  47650. var forward = new BABYLON.Vector3(0, 0, -1);
  47651. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  47652. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  47653. return new BABYLON.Ray(origin, direction, length);
  47654. };
  47655. return PoseEnabledController;
  47656. }(BABYLON.Gamepad));
  47657. BABYLON.PoseEnabledController = PoseEnabledController;
  47658. var WebVRController = (function (_super) {
  47659. __extends(WebVRController, _super);
  47660. function WebVRController(vrGamepad) {
  47661. var _this = _super.call(this, vrGamepad) || this;
  47662. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  47663. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  47664. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  47665. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  47666. _this.onPadStateChangedObservable = new BABYLON.Observable();
  47667. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  47668. _this.pad = { x: 0, y: 0 };
  47669. // avoid GC, store state in a tmp object
  47670. _this._changes = {
  47671. pressChanged: false,
  47672. touchChanged: false,
  47673. valueChanged: false,
  47674. changed: false
  47675. };
  47676. _this._buttons = new Array(vrGamepad.buttons.length);
  47677. _this.hand = vrGamepad.hand;
  47678. return _this;
  47679. }
  47680. WebVRController.prototype.onButtonStateChange = function (callback) {
  47681. this._onButtonStateChange = callback;
  47682. };
  47683. WebVRController.prototype.update = function () {
  47684. _super.prototype.update.call(this);
  47685. for (var index = 0; index < this._buttons.length; index++) {
  47686. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  47687. }
  47688. ;
  47689. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  47690. this.pad.x = this.leftStick.x;
  47691. this.pad.y = this.leftStick.y;
  47692. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  47693. }
  47694. };
  47695. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  47696. if (!currentState) {
  47697. this._buttons[buttonIndex] = {
  47698. pressed: newState.pressed,
  47699. touched: newState.touched,
  47700. value: newState.value
  47701. };
  47702. return;
  47703. }
  47704. this._checkChanges(newState, currentState);
  47705. if (this._changes.changed) {
  47706. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  47707. this.handleButtonChange(buttonIndex, newState, this._changes);
  47708. }
  47709. this._buttons[buttonIndex].pressed = newState.pressed;
  47710. this._buttons[buttonIndex].touched = newState.touched;
  47711. // oculus triggers are never 0, thou not touched.
  47712. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  47713. };
  47714. WebVRController.prototype._checkChanges = function (newState, currentState) {
  47715. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  47716. this._changes.touchChanged = newState.touched !== currentState.touched;
  47717. this._changes.valueChanged = newState.value !== currentState.value;
  47718. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  47719. return this._changes;
  47720. };
  47721. return WebVRController;
  47722. }(PoseEnabledController));
  47723. BABYLON.WebVRController = WebVRController;
  47724. var OculusTouchController = (function (_super) {
  47725. __extends(OculusTouchController, _super);
  47726. function OculusTouchController(vrGamepad) {
  47727. var _this = _super.call(this, vrGamepad) || this;
  47728. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  47729. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  47730. _this.controllerType = PoseEnabledControllerType.OCULUS;
  47731. return _this;
  47732. }
  47733. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  47734. var _this = this;
  47735. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  47736. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  47737. /*
  47738. Parent Mesh name: oculus_touch_left
  47739. - body
  47740. - trigger
  47741. - thumbstick
  47742. - grip
  47743. - button_y
  47744. - button_x
  47745. - button_enter
  47746. */
  47747. _this._defaultModel = newMeshes[1];
  47748. if (meshLoaded) {
  47749. meshLoaded(_this._defaultModel);
  47750. }
  47751. _this.attachToMesh(_this._defaultModel);
  47752. });
  47753. };
  47754. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  47755. // helper getters for left and right hand.
  47756. get: function () {
  47757. if (this.hand === 'right') {
  47758. return this.onMainButtonStateChangedObservable;
  47759. }
  47760. else {
  47761. throw new Error('No A button on left hand');
  47762. }
  47763. },
  47764. enumerable: true,
  47765. configurable: true
  47766. });
  47767. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  47768. get: function () {
  47769. if (this.hand === 'right') {
  47770. return this.onSecondaryButtonStateChangedObservable;
  47771. }
  47772. else {
  47773. throw new Error('No B button on left hand');
  47774. }
  47775. },
  47776. enumerable: true,
  47777. configurable: true
  47778. });
  47779. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  47780. get: function () {
  47781. if (this.hand === 'left') {
  47782. return this.onMainButtonStateChangedObservable;
  47783. }
  47784. else {
  47785. throw new Error('No X button on right hand');
  47786. }
  47787. },
  47788. enumerable: true,
  47789. configurable: true
  47790. });
  47791. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  47792. get: function () {
  47793. if (this.hand === 'left') {
  47794. return this.onSecondaryButtonStateChangedObservable;
  47795. }
  47796. else {
  47797. throw new Error('No Y button on right hand');
  47798. }
  47799. },
  47800. enumerable: true,
  47801. configurable: true
  47802. });
  47803. /*
  47804. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  47805. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  47806. 2) secondary trigger (same)
  47807. 3) A (right) X (left), touch, pressed = value
  47808. 4) B / Y
  47809. 5) thumb rest
  47810. */
  47811. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  47812. var notifyObject = state; //{ state: state, changes: changes };
  47813. var triggerDirection = this.hand === 'right' ? -1 : 1;
  47814. switch (buttonIdx) {
  47815. case 0:
  47816. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  47817. return;
  47818. case 1:
  47819. if (this._defaultModel) {
  47820. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  47821. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  47822. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  47823. }
  47824. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  47825. return;
  47826. case 2:
  47827. if (this._defaultModel) {
  47828. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  47829. }
  47830. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  47831. return;
  47832. case 3:
  47833. if (this._defaultModel) {
  47834. if (notifyObject.pressed) {
  47835. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  47836. }
  47837. else {
  47838. (this._defaultModel.getChildren()[1]).position.y = 0;
  47839. }
  47840. }
  47841. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  47842. return;
  47843. case 4:
  47844. if (this._defaultModel) {
  47845. if (notifyObject.pressed) {
  47846. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  47847. }
  47848. else {
  47849. (this._defaultModel.getChildren()[2]).position.y = 0;
  47850. }
  47851. }
  47852. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  47853. return;
  47854. case 5:
  47855. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  47856. return;
  47857. }
  47858. };
  47859. return OculusTouchController;
  47860. }(WebVRController));
  47861. BABYLON.OculusTouchController = OculusTouchController;
  47862. var ViveController = (function (_super) {
  47863. __extends(ViveController, _super);
  47864. function ViveController(vrGamepad) {
  47865. var _this = _super.call(this, vrGamepad) || this;
  47866. _this.controllerType = PoseEnabledControllerType.VIVE;
  47867. return _this;
  47868. }
  47869. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  47870. var _this = this;
  47871. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  47872. /*
  47873. Parent Mesh name: ViveWand
  47874. - body
  47875. - r_gripper
  47876. - l_gripper
  47877. - menu_button
  47878. - system_button
  47879. - trackpad
  47880. - trigger
  47881. - LED
  47882. */
  47883. _this._defaultModel = newMeshes[1];
  47884. if (meshLoaded) {
  47885. meshLoaded(_this._defaultModel);
  47886. }
  47887. _this.attachToMesh(_this._defaultModel);
  47888. });
  47889. };
  47890. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  47891. get: function () {
  47892. return this.onMainButtonStateChangedObservable;
  47893. },
  47894. enumerable: true,
  47895. configurable: true
  47896. });
  47897. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  47898. get: function () {
  47899. return this.onMainButtonStateChangedObservable;
  47900. },
  47901. enumerable: true,
  47902. configurable: true
  47903. });
  47904. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  47905. get: function () {
  47906. return this.onSecondaryButtonStateChangedObservable;
  47907. },
  47908. enumerable: true,
  47909. configurable: true
  47910. });
  47911. /**
  47912. * Vive mapping:
  47913. * 0: touchpad
  47914. * 1: trigger
  47915. * 2: left AND right buttons
  47916. * 3: menu button
  47917. */
  47918. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  47919. var notifyObject = state; //{ state: state, changes: changes };
  47920. switch (buttonIdx) {
  47921. case 0:
  47922. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  47923. return;
  47924. case 1:
  47925. if (this._defaultModel) {
  47926. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  47927. }
  47928. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  47929. return;
  47930. case 2:
  47931. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  47932. return;
  47933. case 3:
  47934. if (this._defaultModel) {
  47935. if (notifyObject.pressed) {
  47936. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  47937. }
  47938. else {
  47939. (this._defaultModel.getChildren()[2]).position.y = 0;
  47940. }
  47941. }
  47942. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  47943. return;
  47944. }
  47945. };
  47946. return ViveController;
  47947. }(WebVRController));
  47948. BABYLON.ViveController = ViveController;
  47949. })(BABYLON || (BABYLON = {}));
  47950. //# sourceMappingURL=babylon.extendedGamepad.js.map
  47951. /// <reference path="babylon.targetCamera.ts" />
  47952. var BABYLON;
  47953. (function (BABYLON) {
  47954. var FollowCamera = (function (_super) {
  47955. __extends(FollowCamera, _super);
  47956. function FollowCamera(name, position, scene, lockedTarget) {
  47957. var _this = _super.call(this, name, position, scene) || this;
  47958. _this.radius = 12;
  47959. _this.rotationOffset = 0;
  47960. _this.heightOffset = 4;
  47961. _this.cameraAcceleration = 0.05;
  47962. _this.maxCameraSpeed = 20;
  47963. _this.lockedTarget = lockedTarget;
  47964. return _this;
  47965. }
  47966. FollowCamera.prototype.getRadians = function (degrees) {
  47967. return degrees * Math.PI / 180;
  47968. };
  47969. FollowCamera.prototype.follow = function (cameraTarget) {
  47970. if (!cameraTarget)
  47971. return;
  47972. var yRotation;
  47973. if (cameraTarget.rotationQuaternion) {
  47974. var rotMatrix = new BABYLON.Matrix();
  47975. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  47976. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  47977. }
  47978. else {
  47979. yRotation = cameraTarget.rotation.y;
  47980. }
  47981. var radians = this.getRadians(this.rotationOffset) + yRotation;
  47982. var targetPosition = cameraTarget.getAbsolutePosition();
  47983. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  47984. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  47985. var dx = targetX - this.position.x;
  47986. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  47987. var dz = (targetZ) - this.position.z;
  47988. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  47989. var vy = dy * this.cameraAcceleration;
  47990. var vz = dz * this.cameraAcceleration * 2;
  47991. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  47992. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  47993. }
  47994. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  47995. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  47996. }
  47997. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  47998. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  47999. }
  48000. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  48001. this.setTarget(targetPosition);
  48002. };
  48003. FollowCamera.prototype._checkInputs = function () {
  48004. _super.prototype._checkInputs.call(this);
  48005. this.follow(this.lockedTarget);
  48006. };
  48007. FollowCamera.prototype.getClassName = function () {
  48008. return "FollowCamera";
  48009. };
  48010. return FollowCamera;
  48011. }(BABYLON.TargetCamera));
  48012. __decorate([
  48013. BABYLON.serialize()
  48014. ], FollowCamera.prototype, "radius", void 0);
  48015. __decorate([
  48016. BABYLON.serialize()
  48017. ], FollowCamera.prototype, "rotationOffset", void 0);
  48018. __decorate([
  48019. BABYLON.serialize()
  48020. ], FollowCamera.prototype, "heightOffset", void 0);
  48021. __decorate([
  48022. BABYLON.serialize()
  48023. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  48024. __decorate([
  48025. BABYLON.serialize()
  48026. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  48027. __decorate([
  48028. BABYLON.serializeAsMeshReference("lockedTargetId")
  48029. ], FollowCamera.prototype, "lockedTarget", void 0);
  48030. BABYLON.FollowCamera = FollowCamera;
  48031. var ArcFollowCamera = (function (_super) {
  48032. __extends(ArcFollowCamera, _super);
  48033. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  48034. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  48035. _this.alpha = alpha;
  48036. _this.beta = beta;
  48037. _this.radius = radius;
  48038. _this.target = target;
  48039. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  48040. _this.follow();
  48041. return _this;
  48042. }
  48043. ArcFollowCamera.prototype.follow = function () {
  48044. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  48045. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  48046. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  48047. var targetPosition = this.target.getAbsolutePosition();
  48048. this.position = targetPosition.add(this._cartesianCoordinates);
  48049. this.setTarget(targetPosition);
  48050. };
  48051. ArcFollowCamera.prototype._checkInputs = function () {
  48052. _super.prototype._checkInputs.call(this);
  48053. this.follow();
  48054. };
  48055. ArcFollowCamera.prototype.getClassName = function () {
  48056. return "ArcFollowCamera";
  48057. };
  48058. return ArcFollowCamera;
  48059. }(BABYLON.TargetCamera));
  48060. BABYLON.ArcFollowCamera = ArcFollowCamera;
  48061. })(BABYLON || (BABYLON = {}));
  48062. //# sourceMappingURL=babylon.followCamera.js.map
  48063. /// <reference path="babylon.touchCamera.ts" />
  48064. var BABYLON;
  48065. (function (BABYLON) {
  48066. // We're mainly based on the logic defined into the FreeCamera code
  48067. var UniversalCamera = (function (_super) {
  48068. __extends(UniversalCamera, _super);
  48069. //-- end properties for backward compatibility for inputs
  48070. function UniversalCamera(name, position, scene) {
  48071. var _this = _super.call(this, name, position, scene) || this;
  48072. _this.inputs.addGamepad();
  48073. return _this;
  48074. }
  48075. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  48076. //-- Begin properties for backward compatibility for inputs
  48077. get: function () {
  48078. var gamepad = this.inputs.attached["gamepad"];
  48079. if (gamepad)
  48080. return gamepad.gamepadAngularSensibility;
  48081. },
  48082. set: function (value) {
  48083. var gamepad = this.inputs.attached["gamepad"];
  48084. if (gamepad)
  48085. gamepad.gamepadAngularSensibility = value;
  48086. },
  48087. enumerable: true,
  48088. configurable: true
  48089. });
  48090. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  48091. get: function () {
  48092. var gamepad = this.inputs.attached["gamepad"];
  48093. if (gamepad)
  48094. return gamepad.gamepadMoveSensibility;
  48095. },
  48096. set: function (value) {
  48097. var gamepad = this.inputs.attached["gamepad"];
  48098. if (gamepad)
  48099. gamepad.gamepadMoveSensibility = value;
  48100. },
  48101. enumerable: true,
  48102. configurable: true
  48103. });
  48104. UniversalCamera.prototype.getClassName = function () {
  48105. return "UniversalCamera";
  48106. };
  48107. return UniversalCamera;
  48108. }(BABYLON.TouchCamera));
  48109. BABYLON.UniversalCamera = UniversalCamera;
  48110. })(BABYLON || (BABYLON = {}));
  48111. //# sourceMappingURL=babylon.universalCamera.js.map
  48112. /// <reference path="babylon.universalCamera.ts" />
  48113. var BABYLON;
  48114. (function (BABYLON) {
  48115. // We're mainly based on the logic defined into the FreeCamera code
  48116. var GamepadCamera = (function (_super) {
  48117. __extends(GamepadCamera, _super);
  48118. //-- end properties for backward compatibility for inputs
  48119. function GamepadCamera(name, position, scene) {
  48120. return _super.call(this, name, position, scene) || this;
  48121. }
  48122. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  48123. //-- Begin properties for backward compatibility for inputs
  48124. get: function () {
  48125. var gamepad = this.inputs.attached["gamepad"];
  48126. if (gamepad)
  48127. return gamepad.gamepadAngularSensibility;
  48128. },
  48129. set: function (value) {
  48130. var gamepad = this.inputs.attached["gamepad"];
  48131. if (gamepad)
  48132. gamepad.gamepadAngularSensibility = value;
  48133. },
  48134. enumerable: true,
  48135. configurable: true
  48136. });
  48137. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  48138. get: function () {
  48139. var gamepad = this.inputs.attached["gamepad"];
  48140. if (gamepad)
  48141. return gamepad.gamepadMoveSensibility;
  48142. },
  48143. set: function (value) {
  48144. var gamepad = this.inputs.attached["gamepad"];
  48145. if (gamepad)
  48146. gamepad.gamepadMoveSensibility = value;
  48147. },
  48148. enumerable: true,
  48149. configurable: true
  48150. });
  48151. GamepadCamera.prototype.getClassName = function () {
  48152. return "GamepadCamera";
  48153. };
  48154. return GamepadCamera;
  48155. }(BABYLON.UniversalCamera));
  48156. BABYLON.GamepadCamera = GamepadCamera;
  48157. })(BABYLON || (BABYLON = {}));
  48158. //# sourceMappingURL=babylon.gamepadCamera.js.map
  48159. var BABYLON;
  48160. (function (BABYLON) {
  48161. var PostProcessRenderPipelineManager = (function () {
  48162. function PostProcessRenderPipelineManager() {
  48163. this._renderPipelines = {};
  48164. }
  48165. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  48166. this._renderPipelines[renderPipeline._name] = renderPipeline;
  48167. };
  48168. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  48169. var renderPipeline = this._renderPipelines[renderPipelineName];
  48170. if (!renderPipeline) {
  48171. return;
  48172. }
  48173. renderPipeline._attachCameras(cameras, unique);
  48174. };
  48175. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  48176. var renderPipeline = this._renderPipelines[renderPipelineName];
  48177. if (!renderPipeline) {
  48178. return;
  48179. }
  48180. renderPipeline._detachCameras(cameras);
  48181. };
  48182. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  48183. var renderPipeline = this._renderPipelines[renderPipelineName];
  48184. if (!renderPipeline) {
  48185. return;
  48186. }
  48187. renderPipeline._enableEffect(renderEffectName, cameras);
  48188. };
  48189. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  48190. var renderPipeline = this._renderPipelines[renderPipelineName];
  48191. if (!renderPipeline) {
  48192. return;
  48193. }
  48194. renderPipeline._disableEffect(renderEffectName, cameras);
  48195. };
  48196. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  48197. var renderPipeline = this._renderPipelines[renderPipelineName];
  48198. if (!renderPipeline) {
  48199. return;
  48200. }
  48201. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  48202. };
  48203. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  48204. var renderPipeline = this._renderPipelines[renderPipelineName];
  48205. if (!renderPipeline) {
  48206. return;
  48207. }
  48208. renderPipeline._disableDisplayOnlyPass(cameras);
  48209. };
  48210. PostProcessRenderPipelineManager.prototype.update = function () {
  48211. for (var renderPipelineName in this._renderPipelines) {
  48212. var pipeline = this._renderPipelines[renderPipelineName];
  48213. if (!pipeline.isSupported) {
  48214. pipeline.dispose();
  48215. delete this._renderPipelines[renderPipelineName];
  48216. }
  48217. else {
  48218. pipeline._update();
  48219. }
  48220. }
  48221. };
  48222. return PostProcessRenderPipelineManager;
  48223. }());
  48224. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  48225. })(BABYLON || (BABYLON = {}));
  48226. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  48227. var BABYLON;
  48228. (function (BABYLON) {
  48229. var PostProcessRenderPass = (function () {
  48230. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  48231. this._enabled = true;
  48232. this._refCount = 0;
  48233. this._name = name;
  48234. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  48235. this.setRenderList(renderList);
  48236. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  48237. this._renderTexture.onAfterRenderObservable.add(afterRender);
  48238. this._scene = scene;
  48239. this._renderList = renderList;
  48240. }
  48241. // private
  48242. PostProcessRenderPass.prototype._incRefCount = function () {
  48243. if (this._refCount === 0) {
  48244. this._scene.customRenderTargets.push(this._renderTexture);
  48245. }
  48246. return ++this._refCount;
  48247. };
  48248. PostProcessRenderPass.prototype._decRefCount = function () {
  48249. this._refCount--;
  48250. if (this._refCount <= 0) {
  48251. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  48252. }
  48253. return this._refCount;
  48254. };
  48255. PostProcessRenderPass.prototype._update = function () {
  48256. this.setRenderList(this._renderList);
  48257. };
  48258. // public
  48259. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  48260. this._renderTexture.renderList = renderList;
  48261. };
  48262. PostProcessRenderPass.prototype.getRenderTexture = function () {
  48263. return this._renderTexture;
  48264. };
  48265. return PostProcessRenderPass;
  48266. }());
  48267. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  48268. })(BABYLON || (BABYLON = {}));
  48269. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  48270. var BABYLON;
  48271. (function (BABYLON) {
  48272. var PostProcessRenderEffect = (function () {
  48273. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  48274. this._engine = engine;
  48275. this._name = name;
  48276. this._singleInstance = singleInstance || true;
  48277. this._getPostProcess = getPostProcess;
  48278. this._cameras = [];
  48279. this._indicesForCamera = [];
  48280. this._postProcesses = {};
  48281. this._renderPasses = {};
  48282. this._renderEffectAsPasses = {};
  48283. }
  48284. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  48285. get: function () {
  48286. for (var index in this._postProcesses) {
  48287. if (!this._postProcesses[index].isSupported) {
  48288. return false;
  48289. }
  48290. }
  48291. return true;
  48292. },
  48293. enumerable: true,
  48294. configurable: true
  48295. });
  48296. PostProcessRenderEffect.prototype._update = function () {
  48297. for (var renderPassName in this._renderPasses) {
  48298. this._renderPasses[renderPassName]._update();
  48299. }
  48300. };
  48301. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  48302. this._renderPasses[renderPass._name] = renderPass;
  48303. this._linkParameters();
  48304. };
  48305. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  48306. delete this._renderPasses[renderPass._name];
  48307. this._linkParameters();
  48308. };
  48309. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  48310. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  48311. this._linkParameters();
  48312. };
  48313. PostProcessRenderEffect.prototype.getPass = function (passName) {
  48314. for (var renderPassName in this._renderPasses) {
  48315. if (renderPassName === passName) {
  48316. return this._renderPasses[passName];
  48317. }
  48318. }
  48319. };
  48320. PostProcessRenderEffect.prototype.emptyPasses = function () {
  48321. this._renderPasses = {};
  48322. this._linkParameters();
  48323. };
  48324. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  48325. var cameraKey;
  48326. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48327. for (var i = 0; i < _cam.length; i++) {
  48328. var camera = _cam[i];
  48329. var cameraName = camera.name;
  48330. if (this._singleInstance) {
  48331. cameraKey = 0;
  48332. }
  48333. else {
  48334. cameraKey = cameraName;
  48335. }
  48336. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  48337. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  48338. if (!this._indicesForCamera[cameraName]) {
  48339. this._indicesForCamera[cameraName] = [];
  48340. }
  48341. this._indicesForCamera[cameraName].push(index);
  48342. if (this._cameras.indexOf(camera) === -1) {
  48343. this._cameras[cameraName] = camera;
  48344. }
  48345. for (var passName in this._renderPasses) {
  48346. this._renderPasses[passName]._incRefCount();
  48347. }
  48348. }
  48349. this._linkParameters();
  48350. };
  48351. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  48352. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48353. for (var i = 0; i < _cam.length; i++) {
  48354. var camera = _cam[i];
  48355. var cameraName = camera.name;
  48356. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  48357. var index = this._cameras.indexOf(cameraName);
  48358. this._indicesForCamera.splice(index, 1);
  48359. this._cameras.splice(index, 1);
  48360. for (var passName in this._renderPasses) {
  48361. this._renderPasses[passName]._decRefCount();
  48362. }
  48363. }
  48364. };
  48365. PostProcessRenderEffect.prototype._enable = function (cameras) {
  48366. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48367. for (var i = 0; i < _cam.length; i++) {
  48368. var camera = _cam[i];
  48369. var cameraName = camera.name;
  48370. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  48371. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  48372. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  48373. }
  48374. }
  48375. for (var passName in this._renderPasses) {
  48376. this._renderPasses[passName]._incRefCount();
  48377. }
  48378. }
  48379. };
  48380. PostProcessRenderEffect.prototype._disable = function (cameras) {
  48381. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48382. for (var i = 0; i < _cam.length; i++) {
  48383. var camera = _cam[i];
  48384. var cameraName = camera.Name;
  48385. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  48386. for (var passName in this._renderPasses) {
  48387. this._renderPasses[passName]._decRefCount();
  48388. }
  48389. }
  48390. };
  48391. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  48392. if (this._singleInstance) {
  48393. return this._postProcesses[0];
  48394. }
  48395. else {
  48396. return this._postProcesses[camera.name];
  48397. }
  48398. };
  48399. PostProcessRenderEffect.prototype._linkParameters = function () {
  48400. var _this = this;
  48401. for (var index in this._postProcesses) {
  48402. if (this.applyParameters) {
  48403. this.applyParameters(this._postProcesses[index]);
  48404. }
  48405. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  48406. _this._linkTextures(effect);
  48407. });
  48408. }
  48409. };
  48410. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  48411. for (var renderPassName in this._renderPasses) {
  48412. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  48413. }
  48414. for (var renderEffectName in this._renderEffectAsPasses) {
  48415. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  48416. }
  48417. };
  48418. return PostProcessRenderEffect;
  48419. }());
  48420. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  48421. })(BABYLON || (BABYLON = {}));
  48422. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  48423. var BABYLON;
  48424. (function (BABYLON) {
  48425. var PostProcessRenderPipeline = (function () {
  48426. function PostProcessRenderPipeline(engine, name) {
  48427. this._engine = engine;
  48428. this._name = name;
  48429. this._renderEffects = {};
  48430. this._renderEffectsForIsolatedPass = {};
  48431. this._cameras = [];
  48432. }
  48433. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  48434. get: function () {
  48435. for (var renderEffectName in this._renderEffects) {
  48436. if (!this._renderEffects[renderEffectName].isSupported) {
  48437. return false;
  48438. }
  48439. }
  48440. return true;
  48441. },
  48442. enumerable: true,
  48443. configurable: true
  48444. });
  48445. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  48446. this._renderEffects[renderEffect._name] = renderEffect;
  48447. };
  48448. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  48449. var renderEffects = this._renderEffects[renderEffectName];
  48450. if (!renderEffects) {
  48451. return;
  48452. }
  48453. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  48454. };
  48455. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  48456. var renderEffects = this._renderEffects[renderEffectName];
  48457. if (!renderEffects) {
  48458. return;
  48459. }
  48460. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  48461. };
  48462. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  48463. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48464. var indicesToDelete = [];
  48465. var i;
  48466. for (i = 0; i < _cam.length; i++) {
  48467. var camera = _cam[i];
  48468. var cameraName = camera.name;
  48469. if (this._cameras.indexOf(camera) === -1) {
  48470. this._cameras[cameraName] = camera;
  48471. }
  48472. else if (unique) {
  48473. indicesToDelete.push(i);
  48474. }
  48475. }
  48476. for (i = 0; i < indicesToDelete.length; i++) {
  48477. cameras.splice(indicesToDelete[i], 1);
  48478. }
  48479. for (var renderEffectName in this._renderEffects) {
  48480. this._renderEffects[renderEffectName]._attachCameras(_cam);
  48481. }
  48482. };
  48483. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  48484. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48485. for (var renderEffectName in this._renderEffects) {
  48486. this._renderEffects[renderEffectName]._detachCameras(_cam);
  48487. }
  48488. for (var i = 0; i < _cam.length; i++) {
  48489. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  48490. }
  48491. };
  48492. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  48493. var _this = this;
  48494. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48495. var pass = null;
  48496. var renderEffectName;
  48497. for (renderEffectName in this._renderEffects) {
  48498. pass = this._renderEffects[renderEffectName].getPass(passName);
  48499. if (pass != null) {
  48500. break;
  48501. }
  48502. }
  48503. if (pass === null) {
  48504. return;
  48505. }
  48506. for (renderEffectName in this._renderEffects) {
  48507. this._renderEffects[renderEffectName]._disable(_cam);
  48508. }
  48509. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  48510. for (var i = 0; i < _cam.length; i++) {
  48511. var camera = _cam[i];
  48512. var cameraName = camera.name;
  48513. 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); });
  48514. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  48515. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  48516. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  48517. }
  48518. };
  48519. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  48520. var _this = this;
  48521. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48522. for (var i = 0; i < _cam.length; i++) {
  48523. var camera = _cam[i];
  48524. var cameraName = camera.name;
  48525. 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); });
  48526. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  48527. }
  48528. for (var renderEffectName in this._renderEffects) {
  48529. this._renderEffects[renderEffectName]._enable(_cam);
  48530. }
  48531. };
  48532. PostProcessRenderPipeline.prototype._update = function () {
  48533. for (var renderEffectName in this._renderEffects) {
  48534. this._renderEffects[renderEffectName]._update();
  48535. }
  48536. for (var i = 0; i < this._cameras.length; i++) {
  48537. var cameraName = this._cameras[i].name;
  48538. if (this._renderEffectsForIsolatedPass[cameraName]) {
  48539. this._renderEffectsForIsolatedPass[cameraName]._update();
  48540. }
  48541. }
  48542. };
  48543. PostProcessRenderPipeline.prototype.dispose = function () {
  48544. // Must be implemented by children
  48545. };
  48546. return PostProcessRenderPipeline;
  48547. }());
  48548. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  48549. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  48550. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  48551. })(BABYLON || (BABYLON = {}));
  48552. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  48553. var BABYLON;
  48554. (function (BABYLON) {
  48555. var DepthRenderer = (function () {
  48556. function DepthRenderer(scene, type) {
  48557. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  48558. var _this = this;
  48559. this._viewMatrix = BABYLON.Matrix.Zero();
  48560. this._projectionMatrix = BABYLON.Matrix.Zero();
  48561. this._transformMatrix = BABYLON.Matrix.Zero();
  48562. this._worldViewProjection = BABYLON.Matrix.Zero();
  48563. this._scene = scene;
  48564. var engine = scene.getEngine();
  48565. // Render target
  48566. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  48567. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48568. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48569. this._depthMap.refreshRate = 1;
  48570. this._depthMap.renderParticles = false;
  48571. this._depthMap.renderList = null;
  48572. // set default depth value to 1.0 (far away)
  48573. this._depthMap.onClearObservable.add(function (engine) {
  48574. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  48575. });
  48576. // Custom render function
  48577. var renderSubMesh = function (subMesh) {
  48578. var mesh = subMesh.getRenderingMesh();
  48579. var scene = _this._scene;
  48580. var engine = scene.getEngine();
  48581. // Culling
  48582. engine.setState(subMesh.getMaterial().backFaceCulling);
  48583. // Managing instances
  48584. var batch = mesh._getInstancesRenderList(subMesh._id);
  48585. if (batch.mustReturn) {
  48586. return;
  48587. }
  48588. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  48589. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  48590. engine.enableEffect(_this._effect);
  48591. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  48592. var material = subMesh.getMaterial();
  48593. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  48594. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  48595. // Alpha test
  48596. if (material && material.needAlphaTesting()) {
  48597. var alphaTexture = material.getAlphaTestTexture();
  48598. _this._effect.setTexture("diffuseSampler", alphaTexture);
  48599. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48600. }
  48601. // Bones
  48602. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48603. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48604. }
  48605. // Draw
  48606. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  48607. }
  48608. };
  48609. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  48610. var index;
  48611. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48612. renderSubMesh(opaqueSubMeshes.data[index]);
  48613. }
  48614. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48615. renderSubMesh(alphaTestSubMeshes.data[index]);
  48616. }
  48617. };
  48618. }
  48619. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  48620. var material = subMesh.getMaterial();
  48621. if (material.disableDepthWrite) {
  48622. return false;
  48623. }
  48624. var defines = [];
  48625. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48626. var mesh = subMesh.getMesh();
  48627. var scene = mesh.getScene();
  48628. // Alpha test
  48629. if (material && material.needAlphaTesting()) {
  48630. defines.push("#define ALPHATEST");
  48631. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48632. attribs.push(BABYLON.VertexBuffer.UVKind);
  48633. defines.push("#define UV1");
  48634. }
  48635. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48636. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48637. defines.push("#define UV2");
  48638. }
  48639. }
  48640. // Bones
  48641. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48642. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48643. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48644. if (mesh.numBoneInfluencers > 4) {
  48645. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48646. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48647. }
  48648. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48649. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48650. }
  48651. else {
  48652. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48653. }
  48654. // Instances
  48655. if (useInstances) {
  48656. defines.push("#define INSTANCES");
  48657. attribs.push("world0");
  48658. attribs.push("world1");
  48659. attribs.push("world2");
  48660. attribs.push("world3");
  48661. }
  48662. // Get correct effect
  48663. var join = defines.join("\n");
  48664. if (this._cachedDefines !== join) {
  48665. this._cachedDefines = join;
  48666. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  48667. }
  48668. return this._effect.isReady();
  48669. };
  48670. DepthRenderer.prototype.getDepthMap = function () {
  48671. return this._depthMap;
  48672. };
  48673. // Methods
  48674. DepthRenderer.prototype.dispose = function () {
  48675. this._depthMap.dispose();
  48676. };
  48677. return DepthRenderer;
  48678. }());
  48679. BABYLON.DepthRenderer = DepthRenderer;
  48680. })(BABYLON || (BABYLON = {}));
  48681. //# sourceMappingURL=babylon.depthRenderer.js.map
  48682. var BABYLON;
  48683. (function (BABYLON) {
  48684. var SSAORenderingPipeline = (function (_super) {
  48685. __extends(SSAORenderingPipeline, _super);
  48686. /**
  48687. * @constructor
  48688. * @param {string} name - The rendering pipeline name
  48689. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48690. * @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 }
  48691. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48692. */
  48693. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  48694. var _this = _super.call(this, scene.getEngine(), name) || this;
  48695. // Members
  48696. /**
  48697. * The PassPostProcess id in the pipeline that contains the original scene color
  48698. * @type {string}
  48699. */
  48700. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  48701. /**
  48702. * The SSAO PostProcess id in the pipeline
  48703. * @type {string}
  48704. */
  48705. _this.SSAORenderEffect = "SSAORenderEffect";
  48706. /**
  48707. * The horizontal blur PostProcess id in the pipeline
  48708. * @type {string}
  48709. */
  48710. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  48711. /**
  48712. * The vertical blur PostProcess id in the pipeline
  48713. * @type {string}
  48714. */
  48715. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  48716. /**
  48717. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  48718. * @type {string}
  48719. */
  48720. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  48721. /**
  48722. * The output strength of the SSAO post-process. Default value is 1.0.
  48723. * @type {number}
  48724. */
  48725. _this.totalStrength = 1.0;
  48726. /**
  48727. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  48728. * @type {number}
  48729. */
  48730. _this.radius = 0.0001;
  48731. /**
  48732. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  48733. * Must not be equal to fallOff and superior to fallOff.
  48734. * Default value is 0.975
  48735. * @type {number}
  48736. */
  48737. _this.area = 0.0075;
  48738. /**
  48739. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  48740. * Must not be equal to area and inferior to area.
  48741. * Default value is 0.0
  48742. * @type {number}
  48743. */
  48744. _this.fallOff = 0.000001;
  48745. /**
  48746. * The base color of the SSAO post-process
  48747. * The final result is "base + ssao" between [0, 1]
  48748. * @type {number}
  48749. */
  48750. _this.base = 0.5;
  48751. _this._firstUpdate = true;
  48752. _this._scene = scene;
  48753. // Set up assets
  48754. _this._createRandomTexture();
  48755. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  48756. var ssaoRatio = ratio.ssaoRatio || ratio;
  48757. var combineRatio = ratio.combineRatio || ratio;
  48758. _this._ratio = {
  48759. ssaoRatio: ssaoRatio,
  48760. combineRatio: combineRatio
  48761. };
  48762. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48763. _this._createSSAOPostProcess(ssaoRatio);
  48764. _this._createBlurPostProcess(ssaoRatio);
  48765. _this._createSSAOCombinePostProcess(combineRatio);
  48766. // Set up pipeline
  48767. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  48768. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  48769. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  48770. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  48771. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  48772. // Finish
  48773. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48774. if (cameras)
  48775. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48776. return _this;
  48777. }
  48778. // Public Methods
  48779. /**
  48780. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  48781. */
  48782. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  48783. if (disableDepthRender === void 0) { disableDepthRender = false; }
  48784. for (var i = 0; i < this._scene.cameras.length; i++) {
  48785. var camera = this._scene.cameras[i];
  48786. this._originalColorPostProcess.dispose(camera);
  48787. this._ssaoPostProcess.dispose(camera);
  48788. this._blurHPostProcess.dispose(camera);
  48789. this._blurVPostProcess.dispose(camera);
  48790. this._ssaoCombinePostProcess.dispose(camera);
  48791. }
  48792. this._randomTexture.dispose();
  48793. if (disableDepthRender)
  48794. this._scene.disableDepthRenderer();
  48795. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48796. _super.prototype.dispose.call(this);
  48797. };
  48798. // Private Methods
  48799. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  48800. var _this = this;
  48801. /*
  48802. var samplerOffsets = [
  48803. -8.0, -6.0, -4.0, -2.0,
  48804. 0.0,
  48805. 2.0, 4.0, 6.0, 8.0
  48806. ];
  48807. */
  48808. var samples = 16;
  48809. var samplerOffsets = [];
  48810. for (var i = -8; i < 8; i++) {
  48811. samplerOffsets.push(i * 2);
  48812. }
  48813. 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");
  48814. this._blurHPostProcess.onApply = function (effect) {
  48815. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  48816. effect.setTexture("depthSampler", _this._depthTexture);
  48817. if (_this._firstUpdate) {
  48818. effect.setArray("samplerOffsets", samplerOffsets);
  48819. }
  48820. };
  48821. 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");
  48822. this._blurVPostProcess.onApply = function (effect) {
  48823. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  48824. effect.setTexture("depthSampler", _this._depthTexture);
  48825. if (_this._firstUpdate) {
  48826. effect.setArray("samplerOffsets", samplerOffsets);
  48827. _this._firstUpdate = false;
  48828. }
  48829. };
  48830. };
  48831. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  48832. var _this = this;
  48833. var numSamples = 16;
  48834. var sampleSphere = [
  48835. 0.5381, 0.1856, -0.4319,
  48836. 0.1379, 0.2486, 0.4430,
  48837. 0.3371, 0.5679, -0.0057,
  48838. -0.6999, -0.0451, -0.0019,
  48839. 0.0689, -0.1598, -0.8547,
  48840. 0.0560, 0.0069, -0.1843,
  48841. -0.0146, 0.1402, 0.0762,
  48842. 0.0100, -0.1924, -0.0344,
  48843. -0.3577, -0.5301, -0.4358,
  48844. -0.3169, 0.1063, 0.0158,
  48845. 0.0103, -0.5869, 0.0046,
  48846. -0.0897, -0.4940, 0.3287,
  48847. 0.7119, -0.0154, -0.0918,
  48848. -0.0533, 0.0596, -0.5411,
  48849. 0.0352, -0.0631, 0.5460,
  48850. -0.4776, 0.2847, -0.0271
  48851. ];
  48852. var samplesFactor = 1.0 / numSamples;
  48853. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  48854. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  48855. "area", "fallOff", "base", "range", "viewport"
  48856. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  48857. var viewport = new BABYLON.Vector2(0, 0);
  48858. this._ssaoPostProcess.onApply = function (effect) {
  48859. if (_this._firstUpdate) {
  48860. effect.setArray3("sampleSphere", sampleSphere);
  48861. effect.setFloat("samplesFactor", samplesFactor);
  48862. effect.setFloat("randTextureTiles", 4.0);
  48863. }
  48864. effect.setFloat("totalStrength", _this.totalStrength);
  48865. effect.setFloat("radius", _this.radius);
  48866. effect.setFloat("area", _this.area);
  48867. effect.setFloat("fallOff", _this.fallOff);
  48868. effect.setFloat("base", _this.base);
  48869. effect.setTexture("textureSampler", _this._depthTexture);
  48870. effect.setTexture("randomSampler", _this._randomTexture);
  48871. };
  48872. };
  48873. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  48874. var _this = this;
  48875. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48876. this._ssaoCombinePostProcess.onApply = function (effect) {
  48877. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  48878. };
  48879. };
  48880. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  48881. var size = 512;
  48882. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48883. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48884. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48885. var context = this._randomTexture.getContext();
  48886. var rand = function (min, max) {
  48887. return Math.random() * (max - min) + min;
  48888. };
  48889. var randVector = BABYLON.Vector3.Zero();
  48890. for (var x = 0; x < size; x++) {
  48891. for (var y = 0; y < size; y++) {
  48892. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  48893. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  48894. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  48895. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  48896. context.fillRect(x, y, 1, 1);
  48897. }
  48898. }
  48899. this._randomTexture.update(false);
  48900. };
  48901. return SSAORenderingPipeline;
  48902. }(BABYLON.PostProcessRenderPipeline));
  48903. __decorate([
  48904. BABYLON.serialize()
  48905. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  48906. __decorate([
  48907. BABYLON.serialize()
  48908. ], SSAORenderingPipeline.prototype, "radius", void 0);
  48909. __decorate([
  48910. BABYLON.serialize()
  48911. ], SSAORenderingPipeline.prototype, "area", void 0);
  48912. __decorate([
  48913. BABYLON.serialize()
  48914. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  48915. __decorate([
  48916. BABYLON.serialize()
  48917. ], SSAORenderingPipeline.prototype, "base", void 0);
  48918. __decorate([
  48919. BABYLON.serialize()
  48920. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  48921. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  48922. })(BABYLON || (BABYLON = {}));
  48923. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  48924. var BABYLON;
  48925. (function (BABYLON) {
  48926. var SSAO2RenderingPipeline = (function (_super) {
  48927. __extends(SSAO2RenderingPipeline, _super);
  48928. /**
  48929. * @constructor
  48930. * @param {string} name - The rendering pipeline name
  48931. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48932. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  48933. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48934. */
  48935. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  48936. var _this = _super.call(this, scene.getEngine(), name) || this;
  48937. // Members
  48938. /**
  48939. * The PassPostProcess id in the pipeline that contains the original scene color
  48940. * @type {string}
  48941. */
  48942. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  48943. /**
  48944. * The SSAO PostProcess id in the pipeline
  48945. * @type {string}
  48946. */
  48947. _this.SSAORenderEffect = "SSAORenderEffect";
  48948. /**
  48949. * The horizontal blur PostProcess id in the pipeline
  48950. * @type {string}
  48951. */
  48952. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  48953. /**
  48954. * The vertical blur PostProcess id in the pipeline
  48955. * @type {string}
  48956. */
  48957. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  48958. /**
  48959. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  48960. * @type {string}
  48961. */
  48962. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  48963. /**
  48964. * The output strength of the SSAO post-process. Default value is 1.0.
  48965. * @type {number}
  48966. */
  48967. _this.totalStrength = 1.0;
  48968. /**
  48969. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  48970. * @type {number}
  48971. */
  48972. _this.maxZ = 100.0;
  48973. /**
  48974. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  48975. * @type {number}
  48976. */
  48977. _this.minZAspect = 0.2;
  48978. /**
  48979. * Number of samples used for the SSAO calculations. Default value is 8
  48980. * @type {number}
  48981. */
  48982. _this._samples = 8;
  48983. /**
  48984. * Are we using bilateral blur ?
  48985. * @type {boolean}
  48986. */
  48987. _this._expensiveBlur = true;
  48988. /**
  48989. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  48990. * @type {number}
  48991. */
  48992. _this.radius = 2.0;
  48993. /**
  48994. * The base color of the SSAO post-process
  48995. * The final result is "base + ssao" between [0, 1]
  48996. * @type {number}
  48997. */
  48998. _this.base = 0.1;
  48999. _this._firstUpdate = true;
  49000. _this._scene = scene;
  49001. if (!_this.isSupported) {
  49002. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  49003. return _this;
  49004. }
  49005. var ssaoRatio = ratio.ssaoRatio || ratio;
  49006. var blurRatio = ratio.blurRatio || ratio;
  49007. _this._ratio = {
  49008. ssaoRatio: ssaoRatio,
  49009. blurRatio: blurRatio
  49010. };
  49011. // Set up assets
  49012. _this._createRandomTexture();
  49013. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  49014. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  49015. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  49016. _this._createSSAOPostProcess(1.0);
  49017. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  49018. _this._createSSAOCombinePostProcess(blurRatio);
  49019. // Set up pipeline
  49020. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  49021. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  49022. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  49023. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  49024. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  49025. // Finish
  49026. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49027. if (cameras)
  49028. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49029. return _this;
  49030. }
  49031. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  49032. get: function () {
  49033. return this._samples;
  49034. },
  49035. set: function (n) {
  49036. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  49037. this._samples = n;
  49038. this._sampleSphere = this._generateHemisphere();
  49039. this._firstUpdate = true;
  49040. },
  49041. enumerable: true,
  49042. configurable: true
  49043. });
  49044. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  49045. get: function () {
  49046. return this._expensiveBlur;
  49047. },
  49048. set: function (b) {
  49049. this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  49050. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  49051. this._expensiveBlur = b;
  49052. this._firstUpdate = true;
  49053. },
  49054. enumerable: true,
  49055. configurable: true
  49056. });
  49057. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  49058. /**
  49059. * Support test.
  49060. * @type {boolean}
  49061. */
  49062. get: function () {
  49063. var engine = BABYLON.Engine.LastCreatedEngine;
  49064. return engine.webGLVersion > 1;
  49065. },
  49066. enumerable: true,
  49067. configurable: true
  49068. });
  49069. // Public Methods
  49070. /**
  49071. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  49072. */
  49073. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  49074. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  49075. for (var i = 0; i < this._scene.cameras.length; i++) {
  49076. var camera = this._scene.cameras[i];
  49077. this._originalColorPostProcess.dispose(camera);
  49078. this._ssaoPostProcess.dispose(camera);
  49079. this._blurHPostProcess.dispose(camera);
  49080. this._blurVPostProcess.dispose(camera);
  49081. this._ssaoCombinePostProcess.dispose(camera);
  49082. }
  49083. this._randomTexture.dispose();
  49084. if (disableGeometryBufferRenderer)
  49085. this._scene.disableGeometryBufferRenderer();
  49086. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49087. _super.prototype.dispose.call(this);
  49088. };
  49089. // Private Methods
  49090. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  49091. var _this = this;
  49092. var samples = 16;
  49093. this._samplerOffsets = [];
  49094. var expensive = this.expensiveBlur;
  49095. for (var i = -8; i < 8; i++) {
  49096. this._samplerOffsets.push(i * 2 + 0.5);
  49097. }
  49098. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  49099. this._blurHPostProcess.onApply = function (effect) {
  49100. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  49101. effect.setFloat("near", _this._scene.activeCamera.minZ);
  49102. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  49103. effect.setFloat("radius", _this.radius);
  49104. effect.setTexture("depthSampler", _this._depthTexture);
  49105. if (_this._firstUpdate) {
  49106. effect.setArray("samplerOffsets", _this._samplerOffsets);
  49107. }
  49108. };
  49109. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  49110. this._blurVPostProcess.onApply = function (effect) {
  49111. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  49112. effect.setFloat("near", _this._scene.activeCamera.minZ);
  49113. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  49114. effect.setFloat("radius", _this.radius);
  49115. effect.setTexture("depthSampler", _this._depthTexture);
  49116. if (_this._firstUpdate) {
  49117. effect.setArray("samplerOffsets", _this._samplerOffsets);
  49118. _this._firstUpdate = false;
  49119. }
  49120. };
  49121. };
  49122. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  49123. var numSamples = this.samples;
  49124. var result = [];
  49125. var vector, scale;
  49126. var rand = function (min, max) {
  49127. return Math.random() * (max - min) + min;
  49128. };
  49129. var lerp = function (start, end, percent) {
  49130. return (start + percent * (end - start));
  49131. };
  49132. var i = 0;
  49133. var normal = new BABYLON.Vector3(0, 0, 1);
  49134. while (i < numSamples) {
  49135. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  49136. vector.normalize();
  49137. scale = i / numSamples;
  49138. scale = lerp(0.1, 1.0, scale * scale);
  49139. vector.scaleInPlace(scale);
  49140. result.push(vector.x, vector.y, vector.z);
  49141. i++;
  49142. }
  49143. return result;
  49144. };
  49145. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  49146. var _this = this;
  49147. var numSamples = this.samples;
  49148. this._sampleSphere = this._generateHemisphere();
  49149. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  49150. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  49151. "base", "range", "projection", "near", "far", "texelSize",
  49152. "xViewport", "yViewport", "maxZ", "minZAspect"
  49153. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  49154. this._ssaoPostProcess.onApply = function (effect) {
  49155. if (_this._firstUpdate) {
  49156. effect.setArray3("sampleSphere", _this._sampleSphere);
  49157. effect.setFloat("randTextureTiles", 4.0);
  49158. }
  49159. effect.setFloat("samplesFactor", 1 / _this.samples);
  49160. effect.setFloat("totalStrength", _this.totalStrength);
  49161. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  49162. effect.setFloat("radius", _this.radius);
  49163. effect.setFloat("maxZ", _this.maxZ);
  49164. effect.setFloat("minZAspect", _this.minZAspect);
  49165. effect.setFloat("base", _this.base);
  49166. effect.setFloat("near", _this._scene.activeCamera.minZ);
  49167. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  49168. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.activeCamera.minZ * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  49169. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.activeCamera.minZ);
  49170. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  49171. effect.setTexture("textureSampler", _this._depthTexture);
  49172. effect.setTexture("normalSampler", _this._normalTexture);
  49173. effect.setTexture("randomSampler", _this._randomTexture);
  49174. };
  49175. };
  49176. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  49177. var _this = this;
  49178. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49179. this._ssaoCombinePostProcess.onApply = function (effect) {
  49180. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  49181. };
  49182. };
  49183. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  49184. var size = 512;
  49185. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  49186. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49187. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49188. var context = this._randomTexture.getContext();
  49189. var rand = function (min, max) {
  49190. return Math.random() * (max - min) + min;
  49191. };
  49192. var randVector = BABYLON.Vector3.Zero();
  49193. for (var x = 0; x < size; x++) {
  49194. for (var y = 0; y < size; y++) {
  49195. randVector.x = rand(0.0, 1.0);
  49196. randVector.y = rand(0.0, 1.0);
  49197. randVector.z = 0.0;
  49198. randVector.normalize();
  49199. randVector.scaleInPlace(255);
  49200. randVector.x = Math.floor(randVector.x);
  49201. randVector.y = Math.floor(randVector.y);
  49202. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  49203. context.fillRect(x, y, 1, 1);
  49204. }
  49205. }
  49206. this._randomTexture.update(false);
  49207. };
  49208. return SSAO2RenderingPipeline;
  49209. }(BABYLON.PostProcessRenderPipeline));
  49210. __decorate([
  49211. BABYLON.serialize()
  49212. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  49213. __decorate([
  49214. BABYLON.serialize()
  49215. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  49216. __decorate([
  49217. BABYLON.serialize()
  49218. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  49219. __decorate([
  49220. BABYLON.serialize("samples")
  49221. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  49222. __decorate([
  49223. BABYLON.serialize("expensiveBlur")
  49224. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  49225. __decorate([
  49226. BABYLON.serialize()
  49227. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  49228. __decorate([
  49229. BABYLON.serialize()
  49230. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  49231. __decorate([
  49232. BABYLON.serialize()
  49233. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  49234. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  49235. })(BABYLON || (BABYLON = {}));
  49236. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  49237. // BABYLON.JS Chromatic Aberration GLSL Shader
  49238. // Author: Olivier Guyot
  49239. // Separates very slightly R, G and B colors on the edges of the screen
  49240. // Inspired by Francois Tarlier & Martins Upitis
  49241. var BABYLON;
  49242. (function (BABYLON) {
  49243. var LensRenderingPipeline = (function (_super) {
  49244. __extends(LensRenderingPipeline, _super);
  49245. /**
  49246. * @constructor
  49247. *
  49248. * Effect parameters are as follow:
  49249. * {
  49250. * chromatic_aberration: number; // from 0 to x (1 for realism)
  49251. * edge_blur: number; // from 0 to x (1 for realism)
  49252. * distortion: number; // from 0 to x (1 for realism)
  49253. * grain_amount: number; // from 0 to 1
  49254. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  49255. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  49256. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  49257. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  49258. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  49259. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  49260. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  49261. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  49262. * }
  49263. * Note: if an effect parameter is unset, effect is disabled
  49264. *
  49265. * @param {string} name - The rendering pipeline name
  49266. * @param {object} parameters - An object containing all parameters (see above)
  49267. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49268. * @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)
  49269. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49270. */
  49271. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  49272. if (ratio === void 0) { ratio = 1.0; }
  49273. var _this = _super.call(this, scene.getEngine(), name) || this;
  49274. // Lens effects can be of the following:
  49275. // - chromatic aberration (slight shift of RGB colors)
  49276. // - blur on the edge of the lens
  49277. // - lens distortion
  49278. // - depth-of-field blur & highlights enhancing
  49279. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  49280. // - grain effect (noise or custom texture)
  49281. // Two additional texture samplers are needed:
  49282. // - depth map (for depth-of-field)
  49283. // - grain texture
  49284. /**
  49285. * The chromatic aberration PostProcess id in the pipeline
  49286. * @type {string}
  49287. */
  49288. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  49289. /**
  49290. * The highlights enhancing PostProcess id in the pipeline
  49291. * @type {string}
  49292. */
  49293. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  49294. /**
  49295. * The depth-of-field PostProcess id in the pipeline
  49296. * @type {string}
  49297. */
  49298. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  49299. _this._scene = scene;
  49300. // Fetch texture samplers
  49301. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  49302. if (parameters.grain_texture) {
  49303. _this._grainTexture = parameters.grain_texture;
  49304. }
  49305. else {
  49306. _this._createGrainTexture();
  49307. }
  49308. // save parameters
  49309. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  49310. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  49311. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  49312. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  49313. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  49314. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  49315. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  49316. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  49317. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  49318. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  49319. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  49320. // Create effects
  49321. _this._createChromaticAberrationPostProcess(ratio);
  49322. _this._createHighlightsPostProcess(ratio);
  49323. _this._createDepthOfFieldPostProcess(ratio / 4);
  49324. // Set up pipeline
  49325. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  49326. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  49327. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  49328. if (_this._highlightsGain === -1) {
  49329. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  49330. }
  49331. // Finish
  49332. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49333. if (cameras) {
  49334. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49335. }
  49336. return _this;
  49337. }
  49338. // public methods (self explanatory)
  49339. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  49340. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  49341. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  49342. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  49343. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  49344. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  49345. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  49346. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  49347. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  49348. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  49349. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  49350. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  49351. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  49352. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  49353. };
  49354. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  49355. this._highlightsPostProcess.updateEffect();
  49356. };
  49357. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  49358. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  49359. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  49360. this._highlightsGain = amount;
  49361. };
  49362. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  49363. if (this._highlightsGain === -1) {
  49364. this._highlightsGain = 1.0;
  49365. }
  49366. this._highlightsThreshold = amount;
  49367. };
  49368. LensRenderingPipeline.prototype.disableHighlights = function () {
  49369. this._highlightsGain = -1;
  49370. };
  49371. /**
  49372. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  49373. */
  49374. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  49375. if (disableDepthRender === void 0) { disableDepthRender = false; }
  49376. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49377. this._chromaticAberrationPostProcess = undefined;
  49378. this._highlightsPostProcess = undefined;
  49379. this._depthOfFieldPostProcess = undefined;
  49380. this._grainTexture.dispose();
  49381. if (disableDepthRender)
  49382. this._scene.disableDepthRenderer();
  49383. };
  49384. // colors shifting and distortion
  49385. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  49386. var _this = this;
  49387. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  49388. [], // samplers
  49389. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49390. this._chromaticAberrationPostProcess.onApply = function (effect) {
  49391. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  49392. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  49393. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  49394. };
  49395. };
  49396. // highlights enhancing
  49397. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  49398. var _this = this;
  49399. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  49400. [], // samplers
  49401. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  49402. this._highlightsPostProcess.onApply = function (effect) {
  49403. effect.setFloat('gain', _this._highlightsGain);
  49404. effect.setFloat('threshold', _this._highlightsThreshold);
  49405. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  49406. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  49407. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  49408. };
  49409. };
  49410. // colors shifting and distortion
  49411. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  49412. var _this = this;
  49413. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  49414. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  49415. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  49416. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49417. this._depthOfFieldPostProcess.onApply = function (effect) {
  49418. effect.setTexture("depthSampler", _this._depthTexture);
  49419. effect.setTexture("grainSampler", _this._grainTexture);
  49420. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  49421. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  49422. effect.setFloat('grain_amount', _this._grainAmount);
  49423. effect.setBool('blur_noise', _this._blurNoise);
  49424. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  49425. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  49426. effect.setFloat('distortion', _this._distortion);
  49427. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  49428. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  49429. effect.setFloat('aperture', _this._dofAperture);
  49430. effect.setFloat('darken', _this._dofDarken);
  49431. effect.setFloat('edge_blur', _this._edgeBlur);
  49432. effect.setBool('highlights', (_this._highlightsGain !== -1));
  49433. effect.setFloat('near', _this._scene.activeCamera.minZ);
  49434. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  49435. };
  49436. };
  49437. // creates a black and white random noise texture, 512x512
  49438. LensRenderingPipeline.prototype._createGrainTexture = function () {
  49439. var size = 512;
  49440. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49441. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49442. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49443. var context = this._grainTexture.getContext();
  49444. var rand = function (min, max) {
  49445. return Math.random() * (max - min) + min;
  49446. };
  49447. var value;
  49448. for (var x = 0; x < size; x++) {
  49449. for (var y = 0; y < size; y++) {
  49450. value = Math.floor(rand(0.42, 0.58) * 255);
  49451. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  49452. context.fillRect(x, y, 1, 1);
  49453. }
  49454. }
  49455. this._grainTexture.update(false);
  49456. };
  49457. return LensRenderingPipeline;
  49458. }(BABYLON.PostProcessRenderPipeline));
  49459. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  49460. })(BABYLON || (BABYLON = {}));
  49461. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  49462. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  49463. var BABYLON;
  49464. (function (BABYLON) {
  49465. var StandardRenderingPipeline = (function (_super) {
  49466. __extends(StandardRenderingPipeline, _super);
  49467. /**
  49468. * @constructor
  49469. * @param {string} name - The rendering pipeline name
  49470. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49471. * @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)
  49472. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  49473. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49474. */
  49475. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  49476. if (originalPostProcess === void 0) { originalPostProcess = null; }
  49477. var _this = _super.call(this, scene.getEngine(), name) || this;
  49478. _this.downSampleX4PostProcess = null;
  49479. _this.brightPassPostProcess = null;
  49480. _this.gaussianBlurHPostProcesses = [];
  49481. _this.gaussianBlurVPostProcesses = [];
  49482. _this.textureAdderPostProcess = null;
  49483. _this.luminancePostProcess = null;
  49484. _this.luminanceDownSamplePostProcesses = [];
  49485. _this.hdrPostProcess = null;
  49486. _this.textureAdderFinalPostProcess = null;
  49487. _this.lensFlareFinalPostProcess = null;
  49488. _this.hdrFinalPostProcess = null;
  49489. _this.lensFlarePostProcess = null;
  49490. _this.lensFlareComposePostProcess = null;
  49491. _this.motionBlurPostProcess = null;
  49492. _this.depthOfFieldPostProcess = null;
  49493. // Values
  49494. _this.brightThreshold = 1.0;
  49495. _this.blurWidth = 2.0;
  49496. _this.horizontalBlur = false;
  49497. _this.gaussianCoefficient = 0.25;
  49498. _this.gaussianMean = 1.0;
  49499. _this.gaussianStandardDeviation = 1.0;
  49500. _this.exposure = 1.0;
  49501. _this.lensTexture = null;
  49502. _this.hdrMinimumLuminance = 1.0;
  49503. _this.hdrDecreaseRate = 0.5;
  49504. _this.hdrIncreaseRate = 0.5;
  49505. _this.lensColorTexture = null;
  49506. _this.lensFlareStrength = 20.0;
  49507. _this.lensFlareGhostDispersal = 1.4;
  49508. _this.lensFlareHaloWidth = 0.7;
  49509. _this.lensFlareDistortionStrength = 16.0;
  49510. _this.lensStarTexture = null;
  49511. _this.lensFlareDirtTexture = null;
  49512. _this.depthOfFieldDistance = 10.0;
  49513. _this.depthOfFieldBlurWidth = 2.0;
  49514. _this.motionStrength = 1.0;
  49515. // IAnimatable
  49516. _this.animations = [];
  49517. _this._depthRenderer = null;
  49518. _this._currentDepthOfFieldSource = null;
  49519. _this._currentHDRSource = null;
  49520. _this._hdrCurrentLuminance = 1.0;
  49521. _this._motionBlurSamples = 64;
  49522. // Getters and setters
  49523. _this._depthOfFieldEnabled = true;
  49524. _this._lensFlareEnabled = true;
  49525. _this._hdrEnabled = true;
  49526. _this._motionBlurEnabled = true;
  49527. _this._cameras = cameras || [];
  49528. // Initialize
  49529. _this._scene = scene;
  49530. // Misc
  49531. var floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49532. // Create pass post-process
  49533. if (!originalPostProcess) {
  49534. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", floatTextureType);
  49535. }
  49536. else {
  49537. _this.originalPostProcess = originalPostProcess;
  49538. }
  49539. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  49540. // Create down sample X4 post-process
  49541. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  49542. // Create bright pass post-process
  49543. _this._createBrightPassPostProcess(scene, ratio / 2);
  49544. // Create gaussian blur post-processes (down sampling blurs)
  49545. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  49546. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  49547. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  49548. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  49549. // Create texture adder post-process
  49550. _this._createTextureAdderPostProcess(scene, ratio);
  49551. // Create depth-of-field source post-process
  49552. _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);
  49553. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  49554. // Create lens flare post-process
  49555. _this._createLensFlarePostProcess(scene, ratio);
  49556. // Create depth-of-field source post-process post lens-flare and disable it now
  49557. _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);
  49558. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  49559. // Create luminance
  49560. _this._createLuminancePostProcesses(scene, floatTextureType);
  49561. // Create HDR
  49562. _this._createHdrPostProcess(scene, ratio);
  49563. // Create depth-of-field source post-process post hdr and disable it now
  49564. _this.hdrFinalPostProcess = new BABYLON.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  49565. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  49566. // Create gaussian blur used by depth-of-field
  49567. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  49568. // Create depth-of-field post-process
  49569. _this._createDepthOfFieldPostProcess(scene, ratio);
  49570. // Create motion blur post-process
  49571. _this._createMotionBlurPostProcess(scene, ratio);
  49572. // Finish
  49573. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49574. if (cameras !== null) {
  49575. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49576. }
  49577. // Deactivate
  49578. _this.LensFlareEnabled = false;
  49579. _this.DepthOfFieldEnabled = false;
  49580. _this.HDREnabled = false;
  49581. _this.MotionBlurEnabled = false;
  49582. return _this;
  49583. }
  49584. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  49585. get: function () {
  49586. return this._depthOfFieldEnabled;
  49587. },
  49588. set: function (enabled) {
  49589. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  49590. if (enabled && !this._depthOfFieldEnabled) {
  49591. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  49592. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  49593. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  49594. this._depthRenderer = this._scene.enableDepthRenderer();
  49595. }
  49596. else if (!enabled && this._depthOfFieldEnabled) {
  49597. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  49598. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  49599. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  49600. }
  49601. this._depthOfFieldEnabled = enabled;
  49602. },
  49603. enumerable: true,
  49604. configurable: true
  49605. });
  49606. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  49607. get: function () {
  49608. return this._lensFlareEnabled;
  49609. },
  49610. set: function (enabled) {
  49611. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  49612. if (enabled && !this._lensFlareEnabled) {
  49613. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  49614. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  49615. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  49616. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  49617. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  49618. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  49619. }
  49620. else if (!enabled && this._lensFlareEnabled) {
  49621. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  49622. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  49623. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  49624. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  49625. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  49626. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  49627. }
  49628. this._lensFlareEnabled = enabled;
  49629. },
  49630. enumerable: true,
  49631. configurable: true
  49632. });
  49633. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  49634. get: function () {
  49635. return this._hdrEnabled;
  49636. },
  49637. set: function (enabled) {
  49638. if (enabled && !this._hdrEnabled) {
  49639. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  49640. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  49641. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  49642. }
  49643. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  49644. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  49645. }
  49646. else if (!enabled && this._hdrEnabled) {
  49647. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  49648. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  49649. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  49650. }
  49651. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  49652. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  49653. }
  49654. this._hdrEnabled = enabled;
  49655. },
  49656. enumerable: true,
  49657. configurable: true
  49658. });
  49659. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  49660. get: function () {
  49661. return this._motionBlurEnabled;
  49662. },
  49663. set: function (enabled) {
  49664. if (enabled && !this._motionBlurEnabled) {
  49665. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRMotionBlur", this._scene.cameras);
  49666. this._depthRenderer = this._scene.enableDepthRenderer();
  49667. }
  49668. else if (!enabled && this._motionBlurEnabled) {
  49669. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRMotionBlur", this._scene.cameras);
  49670. }
  49671. this._motionBlurEnabled = enabled;
  49672. },
  49673. enumerable: true,
  49674. configurable: true
  49675. });
  49676. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  49677. get: function () {
  49678. return this._motionBlurSamples;
  49679. },
  49680. set: function (samples) {
  49681. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  49682. this._motionBlurSamples = samples;
  49683. },
  49684. enumerable: true,
  49685. configurable: true
  49686. });
  49687. // Down Sample X4 Post-Processs
  49688. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  49689. var _this = this;
  49690. var downSampleX4Offsets = new Array(32);
  49691. 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);
  49692. this.downSampleX4PostProcess.onApply = function (effect) {
  49693. var id = 0;
  49694. for (var i = -2; i < 2; i++) {
  49695. for (var j = -2; j < 2; j++) {
  49696. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  49697. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  49698. id += 2;
  49699. }
  49700. }
  49701. effect.setArray2("dsOffsets", downSampleX4Offsets);
  49702. };
  49703. // Add to pipeline
  49704. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  49705. };
  49706. // Brightpass Post-Process
  49707. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  49708. var _this = this;
  49709. var brightOffsets = new Array(8);
  49710. 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);
  49711. this.brightPassPostProcess.onApply = function (effect) {
  49712. var sU = (1.0 / _this.brightPassPostProcess.width);
  49713. var sV = (1.0 / _this.brightPassPostProcess.height);
  49714. brightOffsets[0] = -0.5 * sU;
  49715. brightOffsets[1] = 0.5 * sV;
  49716. brightOffsets[2] = 0.5 * sU;
  49717. brightOffsets[3] = 0.5 * sV;
  49718. brightOffsets[4] = -0.5 * sU;
  49719. brightOffsets[5] = -0.5 * sV;
  49720. brightOffsets[6] = 0.5 * sU;
  49721. brightOffsets[7] = -0.5 * sV;
  49722. effect.setArray2("dsOffsets", brightOffsets);
  49723. effect.setFloat("brightThreshold", _this.brightThreshold);
  49724. };
  49725. // Add to pipeline
  49726. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  49727. };
  49728. // Create gaussian blur H&V post-processes
  49729. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  49730. var _this = this;
  49731. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  49732. var blurOffsets = new Array(9);
  49733. var blurWeights = new Array(9);
  49734. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  49735. var callback = function (height) {
  49736. return function (effect) {
  49737. // Weights
  49738. var x = 0.0;
  49739. for (var i = 0; i < 9; i++) {
  49740. x = (i - 4.0) / 4.0;
  49741. blurWeights[i] =
  49742. _this.gaussianCoefficient
  49743. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  49744. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  49745. }
  49746. var lastOutputDimensions = {
  49747. width: scene.getEngine().getRenderWidth(),
  49748. height: scene.getEngine().getRenderHeight()
  49749. };
  49750. for (var i = 0; i < 9; i++) {
  49751. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  49752. blurOffsets[i] = value;
  49753. }
  49754. effect.setArray("blurOffsets", blurOffsets);
  49755. effect.setArray("blurWeights", blurWeights);
  49756. if (height) {
  49757. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  49758. }
  49759. else {
  49760. effect.setFloat("blurWidth", _this[blurWidthKey]);
  49761. }
  49762. };
  49763. };
  49764. // Create horizontal gaussian blur post-processes
  49765. 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);
  49766. gaussianBlurHPostProcess.onApply = callback(false);
  49767. // Create vertical gaussian blur post-process
  49768. 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);
  49769. gaussianBlurVPostProcess.onApply = callback(true);
  49770. // Add to pipeline
  49771. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  49772. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  49773. // Finish
  49774. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  49775. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  49776. };
  49777. // Create texture adder post-process
  49778. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  49779. var _this = this;
  49780. 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);
  49781. this.textureAdderPostProcess.onApply = function (effect) {
  49782. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  49783. effect.setTexture("lensSampler", _this.lensTexture);
  49784. effect.setFloat("exposure", _this.exposure);
  49785. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  49786. _this._currentHDRSource = _this.textureAdderFinalPostProcess;
  49787. };
  49788. // Add to pipeline
  49789. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  49790. };
  49791. // Create luminance
  49792. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  49793. var _this = this;
  49794. // Create luminance
  49795. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  49796. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  49797. var offsets = [];
  49798. this.luminancePostProcess.onApply = function (effect) {
  49799. var sU = (1.0 / _this.luminancePostProcess.width);
  49800. var sV = (1.0 / _this.luminancePostProcess.height);
  49801. offsets[0] = -0.5 * sU;
  49802. offsets[1] = 0.5 * sV;
  49803. offsets[2] = 0.5 * sU;
  49804. offsets[3] = 0.5 * sV;
  49805. offsets[4] = -0.5 * sU;
  49806. offsets[5] = -0.5 * sV;
  49807. offsets[6] = 0.5 * sU;
  49808. offsets[7] = -0.5 * sV;
  49809. effect.setArray2("lumOffsets", offsets);
  49810. };
  49811. // Add to pipeline
  49812. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  49813. // Create down sample luminance
  49814. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  49815. var size = Math.pow(3, i);
  49816. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  49817. if (i === 0) {
  49818. defines += "#define FINAL_DOWN_SAMPLER";
  49819. }
  49820. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  49821. this.luminanceDownSamplePostProcesses.push(postProcess);
  49822. }
  49823. // Create callbacks and add effects
  49824. var lastLuminance = this.luminancePostProcess;
  49825. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  49826. var downSampleOffsets = new Array(18);
  49827. pp.onApply = function (effect) {
  49828. var id = 0;
  49829. for (var x = -1; x < 2; x++) {
  49830. for (var y = -1; y < 2; y++) {
  49831. downSampleOffsets[id] = x / lastLuminance.width;
  49832. downSampleOffsets[id + 1] = y / lastLuminance.height;
  49833. id += 2;
  49834. }
  49835. }
  49836. effect.setArray2("dsOffsets", downSampleOffsets);
  49837. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  49838. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  49839. lastLuminance = _this.luminancePostProcess;
  49840. }
  49841. else {
  49842. lastLuminance = pp;
  49843. }
  49844. };
  49845. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  49846. pp.onAfterRender = function (effect) {
  49847. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  49848. 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);
  49849. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  49850. };
  49851. }
  49852. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  49853. });
  49854. };
  49855. // Create HDR post-process
  49856. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  49857. var _this = this;
  49858. this.hdrPostProcess = new BABYLON.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  49859. var outputLiminance = 1;
  49860. var time = 0;
  49861. var lastTime = 0;
  49862. this.hdrPostProcess.onApply = function (effect) {
  49863. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentHDRSource);
  49864. time += scene.getEngine().getDeltaTime();
  49865. if (outputLiminance < 0) {
  49866. outputLiminance = _this._hdrCurrentLuminance;
  49867. }
  49868. else {
  49869. var dt = (lastTime - time) / 1000.0;
  49870. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  49871. outputLiminance += _this.hdrDecreaseRate * dt;
  49872. }
  49873. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  49874. outputLiminance -= _this.hdrIncreaseRate * dt;
  49875. }
  49876. else {
  49877. outputLiminance = _this._hdrCurrentLuminance;
  49878. }
  49879. }
  49880. outputLiminance = BABYLON.MathTools.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  49881. effect.setFloat("averageLuminance", outputLiminance);
  49882. lastTime = time;
  49883. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  49884. };
  49885. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  49886. };
  49887. // Create lens flare post-process
  49888. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  49889. var _this = this;
  49890. 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);
  49891. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  49892. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  49893. 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);
  49894. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  49895. var resolution = new BABYLON.Vector2(0, 0);
  49896. // Lens flare
  49897. this.lensFlarePostProcess.onApply = function (effect) {
  49898. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  49899. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  49900. effect.setFloat("strength", _this.lensFlareStrength);
  49901. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  49902. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  49903. // Shift
  49904. resolution.x = _this.lensFlarePostProcess.width;
  49905. resolution.y = _this.lensFlarePostProcess.height;
  49906. effect.setVector2("resolution", resolution);
  49907. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  49908. };
  49909. // Compose
  49910. 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);
  49911. 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);
  49912. this.lensFlareComposePostProcess.onApply = function (effect) {
  49913. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  49914. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  49915. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  49916. // Lens start rotation matrix
  49917. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  49918. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  49919. 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));
  49920. camRot *= 4.0;
  49921. 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);
  49922. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  49923. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  49924. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  49925. _this._currentHDRSource = _this.lensFlareFinalPostProcess;
  49926. };
  49927. };
  49928. // Create depth-of-field post-process
  49929. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  49930. var _this = this;
  49931. 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);
  49932. this.depthOfFieldPostProcess.onApply = function (effect) {
  49933. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  49934. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  49935. effect.setFloat("distance", _this.depthOfFieldDistance);
  49936. };
  49937. // Add to pipeline
  49938. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  49939. };
  49940. // Create motion blur post-process
  49941. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  49942. var _this = this;
  49943. this.motionBlurPostProcess = new BABYLON.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  49944. var motionScale = 0;
  49945. var prevViewProjection = BABYLON.Matrix.Identity();
  49946. var invViewProjection = BABYLON.Matrix.Identity();
  49947. var viewProjection = BABYLON.Matrix.Identity();
  49948. var screenSize = BABYLON.Vector2.Zero();
  49949. this.motionBlurPostProcess.onApply = function (effect) {
  49950. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  49951. viewProjection.invertToRef(invViewProjection);
  49952. effect.setMatrix("inverseViewProjection", invViewProjection);
  49953. effect.setMatrix("prevViewProjection", prevViewProjection);
  49954. prevViewProjection = viewProjection;
  49955. screenSize.x = _this.motionBlurPostProcess.width;
  49956. screenSize.y = _this.motionBlurPostProcess.height;
  49957. effect.setVector2("screenSize", screenSize);
  49958. motionScale = scene.getEngine().getFps() / 60.0;
  49959. effect.setFloat("motionScale", motionScale);
  49960. effect.setFloat("motionStrength", _this.motionStrength);
  49961. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  49962. };
  49963. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  49964. };
  49965. // Dispose
  49966. StandardRenderingPipeline.prototype.dispose = function () {
  49967. for (var i = 0; i < this._cameras.length; i++) {
  49968. var camera = this._cameras[i];
  49969. this.originalPostProcess.dispose(camera);
  49970. this.downSampleX4PostProcess.dispose(camera);
  49971. this.brightPassPostProcess.dispose(camera);
  49972. this.textureAdderPostProcess.dispose(camera);
  49973. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  49974. this.gaussianBlurHPostProcesses[j].dispose(camera);
  49975. }
  49976. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  49977. this.gaussianBlurVPostProcesses[j].dispose(camera);
  49978. }
  49979. this.textureAdderFinalPostProcess.dispose(camera);
  49980. this.lensFlarePostProcess.dispose(camera);
  49981. this.lensFlareComposePostProcess.dispose(camera);
  49982. this.depthOfFieldPostProcess.dispose(camera);
  49983. this.motionBlurPostProcess.dispose(camera);
  49984. }
  49985. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  49986. _super.prototype.dispose.call(this);
  49987. };
  49988. // Serialize rendering pipeline
  49989. StandardRenderingPipeline.prototype.serialize = function () {
  49990. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  49991. serializationObject.customType = "StandardRenderingPipeline";
  49992. return serializationObject;
  49993. };
  49994. // Parse serialized pipeline
  49995. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  49996. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  49997. };
  49998. return StandardRenderingPipeline;
  49999. }(BABYLON.PostProcessRenderPipeline));
  50000. // Luminance steps
  50001. StandardRenderingPipeline.LuminanceSteps = 6;
  50002. __decorate([
  50003. BABYLON.serialize()
  50004. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  50005. __decorate([
  50006. BABYLON.serialize()
  50007. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  50008. __decorate([
  50009. BABYLON.serialize()
  50010. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  50011. __decorate([
  50012. BABYLON.serialize()
  50013. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  50014. __decorate([
  50015. BABYLON.serialize()
  50016. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  50017. __decorate([
  50018. BABYLON.serialize()
  50019. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  50020. __decorate([
  50021. BABYLON.serialize()
  50022. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  50023. __decorate([
  50024. BABYLON.serializeAsTexture("lensTexture")
  50025. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  50026. __decorate([
  50027. BABYLON.serialize()
  50028. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  50029. __decorate([
  50030. BABYLON.serialize()
  50031. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  50032. __decorate([
  50033. BABYLON.serialize()
  50034. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  50035. __decorate([
  50036. BABYLON.serializeAsTexture("lensColorTexture")
  50037. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  50038. __decorate([
  50039. BABYLON.serialize()
  50040. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  50041. __decorate([
  50042. BABYLON.serialize()
  50043. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  50044. __decorate([
  50045. BABYLON.serialize()
  50046. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  50047. __decorate([
  50048. BABYLON.serialize()
  50049. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  50050. __decorate([
  50051. BABYLON.serializeAsTexture("lensStarTexture")
  50052. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  50053. __decorate([
  50054. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  50055. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  50056. __decorate([
  50057. BABYLON.serialize()
  50058. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  50059. __decorate([
  50060. BABYLON.serialize()
  50061. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  50062. __decorate([
  50063. BABYLON.serialize()
  50064. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  50065. __decorate([
  50066. BABYLON.serialize()
  50067. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  50068. __decorate([
  50069. BABYLON.serialize()
  50070. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  50071. __decorate([
  50072. BABYLON.serialize()
  50073. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  50074. __decorate([
  50075. BABYLON.serialize()
  50076. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  50077. __decorate([
  50078. BABYLON.serialize()
  50079. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  50080. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  50081. })(BABYLON || (BABYLON = {}));
  50082. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  50083. var BABYLON;
  50084. (function (BABYLON) {
  50085. var GeometryBufferRenderer = (function () {
  50086. function GeometryBufferRenderer(scene, ratio) {
  50087. if (ratio === void 0) { ratio = 1; }
  50088. var _this = this;
  50089. this._viewMatrix = BABYLON.Matrix.Zero();
  50090. this._projectionMatrix = BABYLON.Matrix.Zero();
  50091. this._transformMatrix = BABYLON.Matrix.Zero();
  50092. this._worldViewProjection = BABYLON.Matrix.Zero();
  50093. this._scene = scene;
  50094. var engine = scene.getEngine();
  50095. // Render target
  50096. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, 2, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  50097. if (!this.isSupported) {
  50098. return null;
  50099. }
  50100. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50101. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50102. this._multiRenderTarget.refreshRate = 1;
  50103. this._multiRenderTarget.renderParticles = false;
  50104. this._multiRenderTarget.renderList = null;
  50105. // set default depth value to 1.0 (far away)
  50106. this._multiRenderTarget.onClearObservable.add(function (engine) {
  50107. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  50108. });
  50109. // Custom render function
  50110. var renderSubMesh = function (subMesh) {
  50111. var mesh = subMesh.getRenderingMesh();
  50112. var scene = _this._scene;
  50113. var engine = scene.getEngine();
  50114. // Culling
  50115. engine.setState(subMesh.getMaterial().backFaceCulling);
  50116. // Managing instances
  50117. var batch = mesh._getInstancesRenderList(subMesh._id);
  50118. if (batch.mustReturn) {
  50119. return;
  50120. }
  50121. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  50122. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  50123. engine.enableEffect(_this._effect);
  50124. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  50125. var material = subMesh.getMaterial();
  50126. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50127. _this._effect.setMatrix("view", scene.getViewMatrix());
  50128. // Alpha test
  50129. if (material && material.needAlphaTesting()) {
  50130. var alphaTexture = material.getAlphaTestTexture();
  50131. _this._effect.setTexture("diffuseSampler", alphaTexture);
  50132. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50133. }
  50134. // Bones
  50135. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50136. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50137. }
  50138. // Draw
  50139. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  50140. }
  50141. };
  50142. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  50143. var index;
  50144. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50145. renderSubMesh(opaqueSubMeshes.data[index]);
  50146. }
  50147. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50148. renderSubMesh(alphaTestSubMeshes.data[index]);
  50149. }
  50150. };
  50151. }
  50152. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  50153. set: function (meshes) {
  50154. this._multiRenderTarget.renderList = meshes;
  50155. },
  50156. enumerable: true,
  50157. configurable: true
  50158. });
  50159. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  50160. get: function () {
  50161. return this._multiRenderTarget.isSupported;
  50162. },
  50163. enumerable: true,
  50164. configurable: true
  50165. });
  50166. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  50167. var material = subMesh.getMaterial();
  50168. if (material && material.disableDepthWrite) {
  50169. return false;
  50170. }
  50171. var defines = [];
  50172. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  50173. var mesh = subMesh.getMesh();
  50174. var scene = mesh.getScene();
  50175. // Alpha test
  50176. if (material && material.needAlphaTesting()) {
  50177. defines.push("#define ALPHATEST");
  50178. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50179. attribs.push(BABYLON.VertexBuffer.UVKind);
  50180. defines.push("#define UV1");
  50181. }
  50182. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50183. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50184. defines.push("#define UV2");
  50185. }
  50186. }
  50187. // Bones
  50188. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50189. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50190. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50191. if (mesh.numBoneInfluencers > 4) {
  50192. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50193. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50194. }
  50195. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50196. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50197. }
  50198. else {
  50199. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50200. }
  50201. // Instances
  50202. if (useInstances) {
  50203. defines.push("#define INSTANCES");
  50204. attribs.push("world0");
  50205. attribs.push("world1");
  50206. attribs.push("world2");
  50207. attribs.push("world3");
  50208. }
  50209. // Get correct effect
  50210. var join = defines.join("\n");
  50211. if (this._cachedDefines !== join) {
  50212. this._cachedDefines = join;
  50213. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  50214. }
  50215. return this._effect.isReady();
  50216. };
  50217. GeometryBufferRenderer.prototype.getGBuffer = function () {
  50218. return this._multiRenderTarget;
  50219. };
  50220. // Methods
  50221. GeometryBufferRenderer.prototype.dispose = function () {
  50222. this.getGBuffer().dispose();
  50223. };
  50224. return GeometryBufferRenderer;
  50225. }());
  50226. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  50227. })(BABYLON || (BABYLON = {}));
  50228. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  50229. var BABYLON;
  50230. (function (BABYLON) {
  50231. var RefractionPostProcess = (function (_super) {
  50232. __extends(RefractionPostProcess, _super);
  50233. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  50234. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  50235. _this.color = color;
  50236. _this.depth = depth;
  50237. _this.colorLevel = colorLevel;
  50238. _this.onActivateObservable.add(function (cam) {
  50239. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  50240. });
  50241. _this.onApplyObservable.add(function (effect) {
  50242. effect.setColor3("baseColor", _this.color);
  50243. effect.setFloat("depth", _this.depth);
  50244. effect.setFloat("colorLevel", _this.colorLevel);
  50245. effect.setTexture("refractionSampler", _this._refRexture);
  50246. });
  50247. return _this;
  50248. }
  50249. // Methods
  50250. RefractionPostProcess.prototype.dispose = function (camera) {
  50251. if (this._refRexture) {
  50252. this._refRexture.dispose();
  50253. }
  50254. _super.prototype.dispose.call(this, camera);
  50255. };
  50256. return RefractionPostProcess;
  50257. }(BABYLON.PostProcess));
  50258. BABYLON.RefractionPostProcess = RefractionPostProcess;
  50259. })(BABYLON || (BABYLON = {}));
  50260. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  50261. var BABYLON;
  50262. (function (BABYLON) {
  50263. var BlackAndWhitePostProcess = (function (_super) {
  50264. __extends(BlackAndWhitePostProcess, _super);
  50265. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  50266. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  50267. }
  50268. return BlackAndWhitePostProcess;
  50269. }(BABYLON.PostProcess));
  50270. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  50271. })(BABYLON || (BABYLON = {}));
  50272. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  50273. var BABYLON;
  50274. (function (BABYLON) {
  50275. var ConvolutionPostProcess = (function (_super) {
  50276. __extends(ConvolutionPostProcess, _super);
  50277. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  50278. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  50279. _this.kernel = kernel;
  50280. _this.onApply = function (effect) {
  50281. effect.setFloat2("screenSize", _this.width, _this.height);
  50282. effect.setArray("kernel", _this.kernel);
  50283. };
  50284. return _this;
  50285. }
  50286. return ConvolutionPostProcess;
  50287. }(BABYLON.PostProcess));
  50288. // Statics
  50289. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  50290. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  50291. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  50292. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  50293. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  50294. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  50295. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  50296. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  50297. })(BABYLON || (BABYLON = {}));
  50298. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  50299. var BABYLON;
  50300. (function (BABYLON) {
  50301. var FilterPostProcess = (function (_super) {
  50302. __extends(FilterPostProcess, _super);
  50303. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  50304. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  50305. _this.kernelMatrix = kernelMatrix;
  50306. _this.onApply = function (effect) {
  50307. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  50308. };
  50309. return _this;
  50310. }
  50311. return FilterPostProcess;
  50312. }(BABYLON.PostProcess));
  50313. BABYLON.FilterPostProcess = FilterPostProcess;
  50314. })(BABYLON || (BABYLON = {}));
  50315. //# sourceMappingURL=babylon.filterPostProcess.js.map
  50316. var BABYLON;
  50317. (function (BABYLON) {
  50318. var FxaaPostProcess = (function (_super) {
  50319. __extends(FxaaPostProcess, _super);
  50320. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50321. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50322. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType) || this;
  50323. _this.onSizeChangedObservable.add(function () {
  50324. _this.texelWidth = 1.0 / _this.width;
  50325. _this.texelHeight = 1.0 / _this.height;
  50326. });
  50327. _this.onApplyObservable.add(function (effect) {
  50328. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  50329. });
  50330. return _this;
  50331. }
  50332. return FxaaPostProcess;
  50333. }(BABYLON.PostProcess));
  50334. BABYLON.FxaaPostProcess = FxaaPostProcess;
  50335. })(BABYLON || (BABYLON = {}));
  50336. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  50337. var BABYLON;
  50338. (function (BABYLON) {
  50339. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  50340. var VolumetricLightScatteringPostProcess = (function (_super) {
  50341. __extends(VolumetricLightScatteringPostProcess, _super);
  50342. /**
  50343. * @constructor
  50344. * @param {string} name - The post-process name
  50345. * @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)
  50346. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  50347. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  50348. * @param {number} samples - The post-process quality, default 100
  50349. * @param {number} samplingMode - The post-process filtering mode
  50350. * @param {BABYLON.Engine} engine - The babylon engine
  50351. * @param {boolean} reusable - If the post-process is reusable
  50352. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  50353. */
  50354. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  50355. if (samples === void 0) { samples = 100; }
  50356. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50357. 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;
  50358. _this._screenCoordinates = BABYLON.Vector2.Zero();
  50359. /**
  50360. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  50361. * @type {Vector3}
  50362. */
  50363. _this.customMeshPosition = BABYLON.Vector3.Zero();
  50364. /**
  50365. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  50366. * @type {boolean}
  50367. */
  50368. _this.useCustomMeshPosition = false;
  50369. /**
  50370. * If the post-process should inverse the light scattering direction
  50371. * @type {boolean}
  50372. */
  50373. _this.invert = true;
  50374. /**
  50375. * Array containing the excluded meshes not rendered in the internal pass
  50376. */
  50377. _this.excludedMeshes = new Array();
  50378. /**
  50379. * Controls the overall intensity of the post-process
  50380. * @type {number}
  50381. */
  50382. _this.exposure = 0.3;
  50383. /**
  50384. * Dissipates each sample's contribution in range [0, 1]
  50385. * @type {number}
  50386. */
  50387. _this.decay = 0.96815;
  50388. /**
  50389. * Controls the overall intensity of each sample
  50390. * @type {number}
  50391. */
  50392. _this.weight = 0.58767;
  50393. /**
  50394. * Controls the density of each sample
  50395. * @type {number}
  50396. */
  50397. _this.density = 0.926;
  50398. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  50399. var engine = scene.getEngine();
  50400. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  50401. // Configure mesh
  50402. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  50403. // Configure
  50404. _this._createPass(scene, ratio.passRatio || ratio);
  50405. _this.onActivate = function (camera) {
  50406. if (!_this.isSupported) {
  50407. _this.dispose(camera);
  50408. }
  50409. _this.onActivate = null;
  50410. };
  50411. _this.onApplyObservable.add(function (effect) {
  50412. _this._updateMeshScreenCoordinates(scene);
  50413. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  50414. effect.setFloat("exposure", _this.exposure);
  50415. effect.setFloat("decay", _this.decay);
  50416. effect.setFloat("weight", _this.weight);
  50417. effect.setFloat("density", _this.density);
  50418. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  50419. });
  50420. return _this;
  50421. }
  50422. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  50423. get: function () {
  50424. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  50425. return false;
  50426. },
  50427. set: function (useDiffuseColor) {
  50428. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  50429. },
  50430. enumerable: true,
  50431. configurable: true
  50432. });
  50433. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  50434. var mesh = subMesh.getMesh();
  50435. // Render this.mesh as default
  50436. if (mesh === this.mesh) {
  50437. return mesh.material.isReady(mesh);
  50438. }
  50439. var defines = [];
  50440. var attribs = [BABYLON.VertexBuffer.PositionKind];
  50441. var material = subMesh.getMaterial();
  50442. var needUV = false;
  50443. // Alpha test
  50444. if (material) {
  50445. if (material.needAlphaTesting()) {
  50446. defines.push("#define ALPHATEST");
  50447. }
  50448. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50449. attribs.push(BABYLON.VertexBuffer.UVKind);
  50450. defines.push("#define UV1");
  50451. }
  50452. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50453. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50454. defines.push("#define UV2");
  50455. }
  50456. }
  50457. // Bones
  50458. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50459. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50460. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50461. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50462. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50463. }
  50464. else {
  50465. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50466. }
  50467. // Instances
  50468. if (useInstances) {
  50469. defines.push("#define INSTANCES");
  50470. attribs.push("world0");
  50471. attribs.push("world1");
  50472. attribs.push("world2");
  50473. attribs.push("world3");
  50474. }
  50475. // Get correct effect
  50476. var join = defines.join("\n");
  50477. if (this._cachedDefines !== join) {
  50478. this._cachedDefines = join;
  50479. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  50480. }
  50481. return this._volumetricLightScatteringPass.isReady();
  50482. };
  50483. /**
  50484. * Sets the new light position for light scattering effect
  50485. * @param {BABYLON.Vector3} The new custom light position
  50486. */
  50487. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  50488. this.customMeshPosition = position;
  50489. };
  50490. /**
  50491. * Returns the light position for light scattering effect
  50492. * @return {BABYLON.Vector3} The custom light position
  50493. */
  50494. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  50495. return this.customMeshPosition;
  50496. };
  50497. /**
  50498. * Disposes the internal assets and detaches the post-process from the camera
  50499. */
  50500. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  50501. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  50502. if (rttIndex !== -1) {
  50503. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  50504. }
  50505. this._volumetricLightScatteringRTT.dispose();
  50506. _super.prototype.dispose.call(this, camera);
  50507. };
  50508. /**
  50509. * Returns the render target texture used by the post-process
  50510. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  50511. */
  50512. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  50513. return this._volumetricLightScatteringRTT;
  50514. };
  50515. // Private methods
  50516. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  50517. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  50518. return true;
  50519. }
  50520. return false;
  50521. };
  50522. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  50523. var _this = this;
  50524. var engine = scene.getEngine();
  50525. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  50526. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50527. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50528. this._volumetricLightScatteringRTT.renderList = null;
  50529. this._volumetricLightScatteringRTT.renderParticles = false;
  50530. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  50531. // Custom render function for submeshes
  50532. var renderSubMesh = function (subMesh) {
  50533. var mesh = subMesh.getRenderingMesh();
  50534. if (_this._meshExcluded(mesh)) {
  50535. return;
  50536. }
  50537. var scene = mesh.getScene();
  50538. var engine = scene.getEngine();
  50539. // Culling
  50540. engine.setState(subMesh.getMaterial().backFaceCulling);
  50541. // Managing instances
  50542. var batch = mesh._getInstancesRenderList(subMesh._id);
  50543. if (batch.mustReturn) {
  50544. return;
  50545. }
  50546. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  50547. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  50548. var effect = _this._volumetricLightScatteringPass;
  50549. if (mesh === _this.mesh) {
  50550. if (subMesh.effect) {
  50551. effect = subMesh.effect;
  50552. }
  50553. else {
  50554. effect = subMesh.getMaterial().getEffect();
  50555. }
  50556. }
  50557. engine.enableEffect(effect);
  50558. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  50559. if (mesh === _this.mesh) {
  50560. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  50561. }
  50562. else {
  50563. var material = subMesh.getMaterial();
  50564. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  50565. // Alpha test
  50566. if (material && material.needAlphaTesting()) {
  50567. var alphaTexture = material.getAlphaTestTexture();
  50568. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  50569. if (alphaTexture) {
  50570. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50571. }
  50572. }
  50573. // Bones
  50574. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50575. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50576. }
  50577. }
  50578. // Draw
  50579. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  50580. }
  50581. };
  50582. // Render target texture callbacks
  50583. var savedSceneClearColor;
  50584. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  50585. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  50586. savedSceneClearColor = scene.clearColor;
  50587. scene.clearColor = sceneClearColor;
  50588. });
  50589. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  50590. scene.clearColor = savedSceneClearColor;
  50591. });
  50592. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  50593. var engine = scene.getEngine();
  50594. var index;
  50595. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50596. renderSubMesh(opaqueSubMeshes.data[index]);
  50597. }
  50598. engine.setAlphaTesting(true);
  50599. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50600. renderSubMesh(alphaTestSubMeshes.data[index]);
  50601. }
  50602. engine.setAlphaTesting(false);
  50603. if (transparentSubMeshes.length) {
  50604. // Sort sub meshes
  50605. for (index = 0; index < transparentSubMeshes.length; index++) {
  50606. var submesh = transparentSubMeshes.data[index];
  50607. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  50608. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  50609. }
  50610. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  50611. sortedArray.sort(function (a, b) {
  50612. // Alpha index first
  50613. if (a._alphaIndex > b._alphaIndex) {
  50614. return 1;
  50615. }
  50616. if (a._alphaIndex < b._alphaIndex) {
  50617. return -1;
  50618. }
  50619. // Then distance to camera
  50620. if (a._distanceToCamera < b._distanceToCamera) {
  50621. return 1;
  50622. }
  50623. if (a._distanceToCamera > b._distanceToCamera) {
  50624. return -1;
  50625. }
  50626. return 0;
  50627. });
  50628. // Render sub meshes
  50629. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50630. for (index = 0; index < sortedArray.length; index++) {
  50631. renderSubMesh(sortedArray[index]);
  50632. }
  50633. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50634. }
  50635. };
  50636. };
  50637. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  50638. var transform = scene.getTransformMatrix();
  50639. var meshPosition;
  50640. if (this.useCustomMeshPosition) {
  50641. meshPosition = this.customMeshPosition;
  50642. }
  50643. else if (this.attachedNode) {
  50644. meshPosition = this.attachedNode.position;
  50645. }
  50646. else {
  50647. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  50648. }
  50649. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  50650. this._screenCoordinates.x = pos.x / this._viewPort.width;
  50651. this._screenCoordinates.y = pos.y / this._viewPort.height;
  50652. if (this.invert)
  50653. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  50654. };
  50655. // Static methods
  50656. /**
  50657. * Creates a default mesh for the Volumeric Light Scattering post-process
  50658. * @param {string} The mesh name
  50659. * @param {BABYLON.Scene} The scene where to create the mesh
  50660. * @return {BABYLON.Mesh} the default mesh
  50661. */
  50662. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  50663. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  50664. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  50665. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  50666. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  50667. mesh.material = material;
  50668. return mesh;
  50669. };
  50670. return VolumetricLightScatteringPostProcess;
  50671. }(BABYLON.PostProcess));
  50672. __decorate([
  50673. BABYLON.serializeAsVector3()
  50674. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  50675. __decorate([
  50676. BABYLON.serialize()
  50677. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  50678. __decorate([
  50679. BABYLON.serialize()
  50680. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  50681. __decorate([
  50682. BABYLON.serializeAsMeshReference()
  50683. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  50684. __decorate([
  50685. BABYLON.serialize()
  50686. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  50687. __decorate([
  50688. BABYLON.serialize()
  50689. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  50690. __decorate([
  50691. BABYLON.serialize()
  50692. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  50693. __decorate([
  50694. BABYLON.serialize()
  50695. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  50696. __decorate([
  50697. BABYLON.serialize()
  50698. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  50699. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  50700. })(BABYLON || (BABYLON = {}));
  50701. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  50702. //
  50703. // This post-process allows the modification of rendered colors by using
  50704. // a 'look-up table' (LUT). This effect is also called Color Grading.
  50705. //
  50706. // The object needs to be provided an url to a texture containing the color
  50707. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  50708. // Use an image editing software to tweak the LUT to match your needs.
  50709. //
  50710. // For an example of a color LUT, see here:
  50711. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  50712. // For explanations on color grading, see here:
  50713. // http://udn.epicgames.com/Three/ColorGrading.html
  50714. //
  50715. var BABYLON;
  50716. (function (BABYLON) {
  50717. var ColorCorrectionPostProcess = (function (_super) {
  50718. __extends(ColorCorrectionPostProcess, _super);
  50719. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  50720. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  50721. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  50722. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  50723. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50724. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50725. _this.onApply = function (effect) {
  50726. effect.setTexture("colorTable", _this._colorTableTexture);
  50727. };
  50728. return _this;
  50729. }
  50730. return ColorCorrectionPostProcess;
  50731. }(BABYLON.PostProcess));
  50732. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  50733. })(BABYLON || (BABYLON = {}));
  50734. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  50735. var BABYLON;
  50736. (function (BABYLON) {
  50737. var TonemappingOperator;
  50738. (function (TonemappingOperator) {
  50739. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  50740. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  50741. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  50742. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  50743. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  50744. ;
  50745. var TonemapPostProcess = (function (_super) {
  50746. __extends(TonemapPostProcess, _super);
  50747. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  50748. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50749. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50750. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  50751. _this._operator = _operator;
  50752. _this.exposureAdjustment = exposureAdjustment;
  50753. var defines = "#define ";
  50754. if (_this._operator === TonemappingOperator.Hable)
  50755. defines += "HABLE_TONEMAPPING";
  50756. else if (_this._operator === TonemappingOperator.Reinhard)
  50757. defines += "REINHARD_TONEMAPPING";
  50758. else if (_this._operator === TonemappingOperator.HejiDawson)
  50759. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  50760. else if (_this._operator === TonemappingOperator.Photographic)
  50761. defines += "PHOTOGRAPHIC_TONEMAPPING";
  50762. //sadly a second call to create the effect.
  50763. _this.updateEffect(defines);
  50764. _this.onApply = function (effect) {
  50765. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  50766. };
  50767. return _this;
  50768. }
  50769. return TonemapPostProcess;
  50770. }(BABYLON.PostProcess));
  50771. BABYLON.TonemapPostProcess = TonemapPostProcess;
  50772. })(BABYLON || (BABYLON = {}));
  50773. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  50774. var BABYLON;
  50775. (function (BABYLON) {
  50776. var DisplayPassPostProcess = (function (_super) {
  50777. __extends(DisplayPassPostProcess, _super);
  50778. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  50779. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  50780. }
  50781. return DisplayPassPostProcess;
  50782. }(BABYLON.PostProcess));
  50783. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  50784. })(BABYLON || (BABYLON = {}));
  50785. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  50786. var BABYLON;
  50787. (function (BABYLON) {
  50788. var HighlightsPostProcess = (function (_super) {
  50789. __extends(HighlightsPostProcess, _super);
  50790. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50791. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50792. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  50793. }
  50794. return HighlightsPostProcess;
  50795. }(BABYLON.PostProcess));
  50796. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  50797. })(BABYLON || (BABYLON = {}));
  50798. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  50799. var BABYLON;
  50800. (function (BABYLON) {
  50801. var ImageProcessingPostProcess = (function (_super) {
  50802. __extends(ImageProcessingPostProcess, _super);
  50803. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50804. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50805. var _this = _super.call(this, name, "imageProcessing", [
  50806. 'contrast',
  50807. 'vignetteSettings1',
  50808. 'vignetteSettings2',
  50809. 'cameraExposureLinear',
  50810. 'vCameraColorCurveNegative',
  50811. 'vCameraColorCurveNeutral',
  50812. 'vCameraColorCurvePositive',
  50813. 'colorTransformSettings'
  50814. ], ["txColorTransform"], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  50815. _this.colorGradingWeight = 1.0;
  50816. _this.colorCurves = new BABYLON.ColorCurves();
  50817. _this.vignetteStretch = 0;
  50818. _this.vignetteCentreX = 0;
  50819. _this.vignetteCentreY = 0;
  50820. _this.vignetteWeight = 1.5;
  50821. _this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  50822. _this._vignetteBlendMode = ImageProcessingPostProcess.VIGNETTEMODE_MULTIPLY;
  50823. _this.cameraContrast = 1.0;
  50824. _this.cameraExposureValue = 1.5;
  50825. _this._cameraToneMappingEnabled = true;
  50826. _this._updateParameters();
  50827. _this.onApply = function (effect) {
  50828. var aspectRatio = _this.aspectRatio;
  50829. // Color
  50830. BABYLON.ColorCurves.Bind(_this.colorCurves, effect);
  50831. // Vignette
  50832. var vignetteScaleY = Math.tan(_this.getCamera().fov * 0.5);
  50833. var vignetteScaleX = vignetteScaleY * aspectRatio;
  50834. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  50835. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, _this.vignetteStretch);
  50836. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, _this.vignetteStretch);
  50837. effect.setFloat4('vignetteSettings1', vignetteScaleX, vignetteScaleY, -vignetteScaleX * _this.vignetteCentreX, -vignetteScaleY * _this.vignetteCentreY);
  50838. var vignettePower = -2.0 * _this.vignetteWeight;
  50839. effect.setFloat4('vignetteSettings2', _this.vignetteColor.r, _this.vignetteColor.g, _this.vignetteColor.b, vignettePower);
  50840. // Contrast and exposure
  50841. effect.setFloat('contrast', _this.cameraContrast);
  50842. effect.setFloat('cameraExposureLinear', Math.pow(2.0, -_this.cameraExposureValue) * Math.PI);
  50843. // Color transform settings
  50844. if (_this._colorGradingTexture) {
  50845. effect.setTexture('txColorTransform', _this.colorGradingTexture);
  50846. var textureSize = _this.colorGradingTexture.getSize().height;
  50847. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  50848. 0.5 / textureSize, // textureOffset
  50849. textureSize, // textureSize
  50850. _this.colorGradingWeight // weight
  50851. );
  50852. }
  50853. };
  50854. return _this;
  50855. }
  50856. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  50857. get: function () {
  50858. return this._colorGradingTexture;
  50859. },
  50860. set: function (value) {
  50861. if (this._colorGradingTexture === value) {
  50862. return;
  50863. }
  50864. this._colorGradingTexture = value;
  50865. this._updateParameters();
  50866. },
  50867. enumerable: true,
  50868. configurable: true
  50869. });
  50870. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  50871. get: function () {
  50872. return this._vignetteBlendMode;
  50873. },
  50874. set: function (value) {
  50875. if (this._vignetteBlendMode === value) {
  50876. return;
  50877. }
  50878. this._vignetteBlendMode = value;
  50879. this._updateParameters();
  50880. },
  50881. enumerable: true,
  50882. configurable: true
  50883. });
  50884. Object.defineProperty(ImageProcessingPostProcess.prototype, "cameraToneMappingEnabled", {
  50885. get: function () {
  50886. return this._cameraToneMappingEnabled;
  50887. },
  50888. set: function (value) {
  50889. if (this._cameraToneMappingEnabled === value) {
  50890. return;
  50891. }
  50892. this._cameraToneMappingEnabled = value;
  50893. this._updateParameters();
  50894. },
  50895. enumerable: true,
  50896. configurable: true
  50897. });
  50898. ImageProcessingPostProcess.prototype._updateParameters = function () {
  50899. var defines = "";
  50900. if (this.colorGradingTexture) {
  50901. defines = "#define COLORGRADING\r\n";
  50902. }
  50903. if (this.vignetteBlendMode === ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY) {
  50904. defines += "#define VIGNETTEBLENDMODEMULTIPLY\r\n";
  50905. }
  50906. else {
  50907. defines += "#define VIGNETTEBLENDMODEOPAQUE\r\n";
  50908. }
  50909. if (this.cameraToneMappingEnabled) {
  50910. defines += "#define TONEMAPPING\r\n";
  50911. }
  50912. this.updateEffect(defines);
  50913. };
  50914. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_MULTIPLY", {
  50915. get: function () {
  50916. return ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY;
  50917. },
  50918. enumerable: true,
  50919. configurable: true
  50920. });
  50921. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_OPAQUE", {
  50922. get: function () {
  50923. return ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE;
  50924. },
  50925. enumerable: true,
  50926. configurable: true
  50927. });
  50928. return ImageProcessingPostProcess;
  50929. }(BABYLON.PostProcess));
  50930. // Statics
  50931. ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY = 0;
  50932. ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE = 1;
  50933. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  50934. })(BABYLON || (BABYLON = {}));
  50935. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  50936. var BABYLON;
  50937. (function (BABYLON) {
  50938. var BlurPostProcess = (function (_super) {
  50939. __extends(BlurPostProcess, _super);
  50940. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  50941. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50942. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50943. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  50944. _this.direction = direction;
  50945. _this.onApplyObservable.add(function (effect) {
  50946. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  50947. });
  50948. _this.kernel = kernel;
  50949. return _this;
  50950. }
  50951. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  50952. /**
  50953. * Gets the length in pixels of the blur sample region
  50954. */
  50955. get: function () {
  50956. return this._idealKernel;
  50957. },
  50958. /**
  50959. * Sets the length in pixels of the blur sample region
  50960. */
  50961. set: function (v) {
  50962. v = Math.max(v, 1);
  50963. this._idealKernel = v;
  50964. this._kernel = this._nearestBestKernel(v);
  50965. this._updateParameters();
  50966. },
  50967. enumerable: true,
  50968. configurable: true
  50969. });
  50970. BlurPostProcess.prototype._updateParameters = function () {
  50971. // Generate sampling offsets and weights
  50972. var N = this._kernel;
  50973. var centerIndex = (N - 1) / 2;
  50974. // Generate Gaussian sampling weights over kernel
  50975. var offsets = [];
  50976. var weights = [];
  50977. var totalWeight = 0;
  50978. for (var i = 0; i < N; i++) {
  50979. var u = i / (N - 1);
  50980. var w = this._gaussianWeight(u * 2.0 - 1);
  50981. offsets[i] = (i - centerIndex);
  50982. weights[i] = w;
  50983. totalWeight += w;
  50984. }
  50985. // Normalize weights
  50986. for (var i = 0; i < weights.length; i++) {
  50987. weights[i] /= totalWeight;
  50988. }
  50989. // Optimize: combine samples to take advantage of hardware linear sampling
  50990. // Walk from left to center, combining pairs (symmetrically)
  50991. var linearSamplingWeights = [];
  50992. var linearSamplingOffsets = [];
  50993. var linearSamplingMap = [];
  50994. for (var i = 0; i <= centerIndex; i += 2) {
  50995. var j = Math.min(i + 1, Math.floor(centerIndex));
  50996. var singleCenterSample = i === j;
  50997. if (singleCenterSample) {
  50998. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  50999. }
  51000. else {
  51001. var sharedCell = j === centerIndex;
  51002. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  51003. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  51004. if (offsetLinear === 0) {
  51005. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  51006. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  51007. }
  51008. else {
  51009. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  51010. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  51011. }
  51012. }
  51013. }
  51014. for (var i = 0; i < linearSamplingMap.length; i++) {
  51015. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  51016. linearSamplingWeights[i] = linearSamplingMap[i].w;
  51017. }
  51018. // Replace with optimized
  51019. offsets = linearSamplingOffsets;
  51020. weights = linearSamplingWeights;
  51021. // Generate shaders
  51022. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  51023. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  51024. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  51025. var defines = "";
  51026. for (var i = 0; i < varyingCount; i++) {
  51027. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  51028. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  51029. }
  51030. var depCount = 0;
  51031. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  51032. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  51033. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  51034. depCount++;
  51035. }
  51036. this._indexParameters.varyingCount = varyingCount;
  51037. this._indexParameters.depCount = depCount;
  51038. this.updateEffect(defines);
  51039. };
  51040. /**
  51041. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  51042. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  51043. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  51044. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  51045. * The gaps between physical kernels are compensated for in the weighting of the samples
  51046. * @param idealKernel Ideal blur kernel.
  51047. * @return Nearest best kernel.
  51048. */
  51049. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  51050. var v = Math.round(idealKernel);
  51051. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  51052. var k = _a[_i];
  51053. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  51054. return Math.max(k, 3);
  51055. }
  51056. }
  51057. return Math.max(v, 3);
  51058. };
  51059. /**
  51060. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  51061. * @param x The point on the Gaussian distribution to sample.
  51062. * @return the value of the Gaussian function at x.
  51063. */
  51064. BlurPostProcess.prototype._gaussianWeight = function (x) {
  51065. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  51066. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  51067. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  51068. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  51069. // truncated at around 1.3% of peak strength.
  51070. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  51071. var sigma = (1 / 3);
  51072. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  51073. var exponent = -((x * x) / (2.0 * sigma * sigma));
  51074. var weight = (1.0 / denominator) * Math.exp(exponent);
  51075. return weight;
  51076. };
  51077. /**
  51078. * Generates a string that can be used as a floating point number in GLSL.
  51079. * @param x Value to print.
  51080. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  51081. * @return GLSL float string.
  51082. */
  51083. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  51084. if (decimalFigures === void 0) { decimalFigures = 8; }
  51085. return x.toFixed(decimalFigures).replace(/0+$/, '');
  51086. };
  51087. return BlurPostProcess;
  51088. }(BABYLON.PostProcess));
  51089. BABYLON.BlurPostProcess = BlurPostProcess;
  51090. })(BABYLON || (BABYLON = {}));
  51091. //# sourceMappingURL=babylon.blurPostProcess.js.map
  51092. /// <reference path="..\babylon.node.ts" />
  51093. var BABYLON;
  51094. (function (BABYLON) {
  51095. var Bone = (function (_super) {
  51096. __extends(Bone, _super);
  51097. function Bone(name, skeleton, parentBone, matrix, restPose) {
  51098. var _this = _super.call(this, name, skeleton.getScene()) || this;
  51099. _this.name = name;
  51100. _this.children = new Array();
  51101. _this.animations = new Array();
  51102. _this._worldTransform = new BABYLON.Matrix();
  51103. _this._absoluteTransform = new BABYLON.Matrix();
  51104. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  51105. _this._scaleMatrix = BABYLON.Matrix.Identity();
  51106. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  51107. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  51108. _this._scalingDeterminant = 1;
  51109. _this._skeleton = skeleton;
  51110. _this._localMatrix = matrix;
  51111. _this._baseMatrix = matrix.clone();
  51112. _this._restPose = restPose ? restPose : matrix.clone();
  51113. skeleton.bones.push(_this);
  51114. if (parentBone) {
  51115. _this._parent = parentBone;
  51116. parentBone.children.push(_this);
  51117. }
  51118. else {
  51119. _this._parent = null;
  51120. }
  51121. _this._updateDifferenceMatrix();
  51122. if (_this.getAbsoluteTransform().determinant() < 0) {
  51123. _this._scalingDeterminant *= -1;
  51124. }
  51125. return _this;
  51126. }
  51127. Object.defineProperty(Bone.prototype, "_matrix", {
  51128. get: function () {
  51129. return this._localMatrix;
  51130. },
  51131. set: function (val) {
  51132. if (this._localMatrix) {
  51133. this._localMatrix.copyFrom(val);
  51134. }
  51135. else {
  51136. this._localMatrix = val;
  51137. }
  51138. },
  51139. enumerable: true,
  51140. configurable: true
  51141. });
  51142. // Members
  51143. Bone.prototype.getParent = function () {
  51144. return this._parent;
  51145. };
  51146. Bone.prototype.getLocalMatrix = function () {
  51147. return this._localMatrix;
  51148. };
  51149. Bone.prototype.getBaseMatrix = function () {
  51150. return this._baseMatrix;
  51151. };
  51152. Bone.prototype.getRestPose = function () {
  51153. return this._restPose;
  51154. };
  51155. Bone.prototype.returnToRest = function () {
  51156. this.updateMatrix(this._restPose.clone());
  51157. };
  51158. Bone.prototype.getWorldMatrix = function () {
  51159. return this._worldTransform;
  51160. };
  51161. Bone.prototype.getInvertedAbsoluteTransform = function () {
  51162. return this._invertedAbsoluteTransform;
  51163. };
  51164. Bone.prototype.getAbsoluteTransform = function () {
  51165. return this._absoluteTransform;
  51166. };
  51167. Object.defineProperty(Bone.prototype, "position", {
  51168. // Properties (matches AbstractMesh properties)
  51169. get: function () {
  51170. return this.getPosition();
  51171. },
  51172. set: function (newPosition) {
  51173. this.setPosition(newPosition);
  51174. },
  51175. enumerable: true,
  51176. configurable: true
  51177. });
  51178. Object.defineProperty(Bone.prototype, "rotation", {
  51179. get: function () {
  51180. return this.getRotation();
  51181. },
  51182. set: function (newRotation) {
  51183. this.setRotation(newRotation);
  51184. },
  51185. enumerable: true,
  51186. configurable: true
  51187. });
  51188. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  51189. get: function () {
  51190. return this.getRotationQuaternion();
  51191. },
  51192. set: function (newRotation) {
  51193. this.setRotationQuaternion(newRotation);
  51194. },
  51195. enumerable: true,
  51196. configurable: true
  51197. });
  51198. Object.defineProperty(Bone.prototype, "scaling", {
  51199. get: function () {
  51200. return this.getScale();
  51201. },
  51202. set: function (newScaling) {
  51203. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  51204. },
  51205. enumerable: true,
  51206. configurable: true
  51207. });
  51208. // Methods
  51209. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  51210. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  51211. this._baseMatrix = matrix.clone();
  51212. this._localMatrix = matrix.clone();
  51213. this._skeleton._markAsDirty();
  51214. if (updateDifferenceMatrix) {
  51215. this._updateDifferenceMatrix();
  51216. }
  51217. };
  51218. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  51219. if (!rootMatrix) {
  51220. rootMatrix = this._baseMatrix;
  51221. }
  51222. if (this._parent) {
  51223. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  51224. }
  51225. else {
  51226. this._absoluteTransform.copyFrom(rootMatrix);
  51227. }
  51228. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  51229. for (var index = 0; index < this.children.length; index++) {
  51230. this.children[index]._updateDifferenceMatrix();
  51231. }
  51232. };
  51233. Bone.prototype.markAsDirty = function () {
  51234. this._currentRenderId++;
  51235. this._skeleton._markAsDirty();
  51236. };
  51237. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  51238. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  51239. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  51240. // all animation may be coming from a library skeleton, so may need to create animation
  51241. if (this.animations.length === 0) {
  51242. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  51243. this.animations[0].setKeys([]);
  51244. }
  51245. // get animation info / verify there is such a range from the source bone
  51246. var sourceRange = source.animations[0].getRange(rangeName);
  51247. if (!sourceRange) {
  51248. return false;
  51249. }
  51250. var from = sourceRange.from;
  51251. var to = sourceRange.to;
  51252. var sourceKeys = source.animations[0].getKeys();
  51253. // rescaling prep
  51254. var sourceBoneLength = source.length;
  51255. var sourceParent = source.getParent();
  51256. var parent = this.getParent();
  51257. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  51258. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  51259. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  51260. var destKeys = this.animations[0].getKeys();
  51261. // loop vars declaration
  51262. var orig;
  51263. var origTranslation;
  51264. var mat;
  51265. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  51266. orig = sourceKeys[key];
  51267. if (orig.frame >= from && orig.frame <= to) {
  51268. if (rescaleAsRequired) {
  51269. mat = orig.value.clone();
  51270. // scale based on parent ratio, when bone has parent
  51271. if (parentScalingReqd) {
  51272. origTranslation = mat.getTranslation();
  51273. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  51274. // scale based on skeleton dimension ratio when root bone, and value is passed
  51275. }
  51276. else if (dimensionsScalingReqd) {
  51277. origTranslation = mat.getTranslation();
  51278. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  51279. // use original when root bone, and no data for skelDimensionsRatio
  51280. }
  51281. else {
  51282. mat = orig.value;
  51283. }
  51284. }
  51285. else {
  51286. mat = orig.value;
  51287. }
  51288. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  51289. }
  51290. }
  51291. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  51292. return true;
  51293. };
  51294. /**
  51295. * Translate the bone in local or world space.
  51296. * @param vec The amount to translate the bone.
  51297. * @param space The space that the translation is in.
  51298. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51299. */
  51300. Bone.prototype.translate = function (vec, space, mesh) {
  51301. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51302. var lm = this.getLocalMatrix();
  51303. if (space == BABYLON.Space.LOCAL) {
  51304. lm.m[12] += vec.x;
  51305. lm.m[13] += vec.y;
  51306. lm.m[14] += vec.z;
  51307. }
  51308. else {
  51309. var wm;
  51310. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  51311. if (mesh) {
  51312. wm = mesh.getWorldMatrix();
  51313. }
  51314. this._skeleton.computeAbsoluteTransforms();
  51315. var tmat = Bone._tmpMats[0];
  51316. var tvec = Bone._tmpVecs[0];
  51317. if (mesh) {
  51318. tmat.copyFrom(this._parent.getAbsoluteTransform());
  51319. tmat.multiplyToRef(wm, tmat);
  51320. }
  51321. else {
  51322. tmat.copyFrom(this._parent.getAbsoluteTransform());
  51323. }
  51324. tmat.m[12] = 0;
  51325. tmat.m[13] = 0;
  51326. tmat.m[14] = 0;
  51327. tmat.invert();
  51328. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  51329. lm.m[12] += tvec.x;
  51330. lm.m[13] += tvec.y;
  51331. lm.m[14] += tvec.z;
  51332. }
  51333. this.markAsDirty();
  51334. };
  51335. /**
  51336. * Set the postion of the bone in local or world space.
  51337. * @param position The position to set the bone.
  51338. * @param space The space that the position is in.
  51339. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51340. */
  51341. Bone.prototype.setPosition = function (position, space, mesh) {
  51342. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51343. var lm = this.getLocalMatrix();
  51344. if (space == BABYLON.Space.LOCAL) {
  51345. lm.m[12] = position.x;
  51346. lm.m[13] = position.y;
  51347. lm.m[14] = position.z;
  51348. }
  51349. else {
  51350. var wm;
  51351. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  51352. if (mesh) {
  51353. wm = mesh.getWorldMatrix();
  51354. }
  51355. this._skeleton.computeAbsoluteTransforms();
  51356. var tmat = Bone._tmpMats[0];
  51357. var vec = Bone._tmpVecs[0];
  51358. if (mesh) {
  51359. tmat.copyFrom(this._parent.getAbsoluteTransform());
  51360. tmat.multiplyToRef(wm, tmat);
  51361. }
  51362. else {
  51363. tmat.copyFrom(this._parent.getAbsoluteTransform());
  51364. }
  51365. tmat.invert();
  51366. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  51367. lm.m[12] = vec.x;
  51368. lm.m[13] = vec.y;
  51369. lm.m[14] = vec.z;
  51370. }
  51371. this.markAsDirty();
  51372. };
  51373. /**
  51374. * Set the absolute postion of the bone (world space).
  51375. * @param position The position to set the bone.
  51376. * @param mesh The mesh that this bone is attached to.
  51377. */
  51378. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  51379. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  51380. };
  51381. /**
  51382. * Set the scale of the bone on the x, y and z axes.
  51383. * @param x The scale of the bone on the x axis.
  51384. * @param x The scale of the bone on the y axis.
  51385. * @param z The scale of the bone on the z axis.
  51386. * @param scaleChildren Set this to true if children of the bone should be scaled.
  51387. */
  51388. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  51389. if (scaleChildren === void 0) { scaleChildren = false; }
  51390. if (this.animations[0] && !this.animations[0].isStopped()) {
  51391. if (!scaleChildren) {
  51392. this._negateScaleChildren.x = 1 / x;
  51393. this._negateScaleChildren.y = 1 / y;
  51394. this._negateScaleChildren.z = 1 / z;
  51395. }
  51396. this._syncScaleVector();
  51397. }
  51398. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  51399. };
  51400. /**
  51401. * Scale the bone on the x, y and z axes.
  51402. * @param x The amount to scale the bone on the x axis.
  51403. * @param x The amount to scale the bone on the y axis.
  51404. * @param z The amount to scale the bone on the z axis.
  51405. * @param scaleChildren Set this to true if children of the bone should be scaled.
  51406. */
  51407. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  51408. if (scaleChildren === void 0) { scaleChildren = false; }
  51409. var locMat = this.getLocalMatrix();
  51410. var origLocMat = Bone._tmpMats[0];
  51411. origLocMat.copyFrom(locMat);
  51412. var origLocMatInv = Bone._tmpMats[1];
  51413. origLocMatInv.copyFrom(origLocMat);
  51414. origLocMatInv.invert();
  51415. var scaleMat = Bone._tmpMats[2];
  51416. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  51417. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  51418. this._scaleVector.x *= x;
  51419. this._scaleVector.y *= y;
  51420. this._scaleVector.z *= z;
  51421. locMat.multiplyToRef(origLocMatInv, locMat);
  51422. locMat.multiplyToRef(scaleMat, locMat);
  51423. locMat.multiplyToRef(origLocMat, locMat);
  51424. var parent = this.getParent();
  51425. if (parent) {
  51426. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  51427. }
  51428. else {
  51429. this.getAbsoluteTransform().copyFrom(locMat);
  51430. }
  51431. var len = this.children.length;
  51432. scaleMat.invert();
  51433. for (var i = 0; i < len; i++) {
  51434. var child = this.children[i];
  51435. var cm = child.getLocalMatrix();
  51436. cm.multiplyToRef(scaleMat, cm);
  51437. var lm = child.getLocalMatrix();
  51438. lm.m[12] *= x;
  51439. lm.m[13] *= y;
  51440. lm.m[14] *= z;
  51441. }
  51442. this.computeAbsoluteTransforms();
  51443. if (scaleChildren) {
  51444. for (var i = 0; i < len; i++) {
  51445. this.children[i].scale(x, y, z, scaleChildren);
  51446. }
  51447. }
  51448. this.markAsDirty();
  51449. };
  51450. /**
  51451. * Set the yaw, pitch, and roll of the bone in local or world space.
  51452. * @param yaw The rotation of the bone on the y axis.
  51453. * @param pitch The rotation of the bone on the x axis.
  51454. * @param roll The rotation of the bone on the z axis.
  51455. * @param space The space that the axes of rotation are in.
  51456. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51457. */
  51458. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  51459. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51460. var rotMat = Bone._tmpMats[0];
  51461. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  51462. var rotMatInv = Bone._tmpMats[1];
  51463. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  51464. rotMatInv.multiplyToRef(rotMat, rotMat);
  51465. this._rotateWithMatrix(rotMat, space, mesh);
  51466. };
  51467. /**
  51468. * Rotate the bone on an axis in local or world space.
  51469. * @param axis The axis to rotate the bone on.
  51470. * @param amount The amount to rotate the bone.
  51471. * @param space The space that the axis is in.
  51472. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51473. */
  51474. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  51475. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51476. var rmat = Bone._tmpMats[0];
  51477. rmat.m[12] = 0;
  51478. rmat.m[13] = 0;
  51479. rmat.m[14] = 0;
  51480. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  51481. this._rotateWithMatrix(rmat, space, mesh);
  51482. };
  51483. /**
  51484. * Set the rotation of the bone to a particular axis angle in local or world space.
  51485. * @param axis The axis to rotate the bone on.
  51486. * @param angle The angle that the bone should be rotated to.
  51487. * @param space The space that the axis is in.
  51488. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51489. */
  51490. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  51491. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51492. var rotMat = Bone._tmpMats[0];
  51493. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  51494. var rotMatInv = Bone._tmpMats[1];
  51495. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  51496. rotMatInv.multiplyToRef(rotMat, rotMat);
  51497. this._rotateWithMatrix(rotMat, space, mesh);
  51498. };
  51499. /**
  51500. * Set the euler rotation of the bone in local of world space.
  51501. * @param rotation The euler rotation that the bone should be set to.
  51502. * @param space The space that the rotation is in.
  51503. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51504. */
  51505. Bone.prototype.setRotation = function (rotation, space, mesh) {
  51506. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51507. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  51508. };
  51509. /**
  51510. * Set the quaternion rotation of the bone in local of world space.
  51511. * @param quat The quaternion rotation that the bone should be set to.
  51512. * @param space The space that the rotation is in.
  51513. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51514. */
  51515. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  51516. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51517. var rotMatInv = Bone._tmpMats[0];
  51518. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  51519. var rotMat = Bone._tmpMats[1];
  51520. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  51521. rotMatInv.multiplyToRef(rotMat, rotMat);
  51522. this._rotateWithMatrix(rotMat, space, mesh);
  51523. };
  51524. /**
  51525. * Set the rotation matrix of the bone in local of world space.
  51526. * @param rotMat The rotation matrix that the bone should be set to.
  51527. * @param space The space that the rotation is in.
  51528. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51529. */
  51530. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  51531. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51532. var rotMatInv = Bone._tmpMats[0];
  51533. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  51534. var rotMat2 = Bone._tmpMats[1];
  51535. rotMat2.copyFrom(rotMat);
  51536. rotMatInv.multiplyToRef(rotMat, rotMat2);
  51537. this._rotateWithMatrix(rotMat2, space, mesh);
  51538. };
  51539. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  51540. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51541. var lmat = this.getLocalMatrix();
  51542. var lx = lmat.m[12];
  51543. var ly = lmat.m[13];
  51544. var lz = lmat.m[14];
  51545. var parent = this.getParent();
  51546. var parentScale = Bone._tmpMats[3];
  51547. var parentScaleInv = Bone._tmpMats[4];
  51548. if (parent) {
  51549. if (space == BABYLON.Space.WORLD) {
  51550. if (mesh) {
  51551. parentScale.copyFrom(mesh.getWorldMatrix());
  51552. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  51553. }
  51554. else {
  51555. parentScale.copyFrom(parent.getAbsoluteTransform());
  51556. }
  51557. }
  51558. else {
  51559. parentScale = parent._scaleMatrix;
  51560. }
  51561. parentScaleInv.copyFrom(parentScale);
  51562. parentScaleInv.invert();
  51563. lmat.multiplyToRef(parentScale, lmat);
  51564. lmat.multiplyToRef(rmat, lmat);
  51565. lmat.multiplyToRef(parentScaleInv, lmat);
  51566. }
  51567. else {
  51568. if (space == BABYLON.Space.WORLD && mesh) {
  51569. parentScale.copyFrom(mesh.getWorldMatrix());
  51570. parentScaleInv.copyFrom(parentScale);
  51571. parentScaleInv.invert();
  51572. lmat.multiplyToRef(parentScale, lmat);
  51573. lmat.multiplyToRef(rmat, lmat);
  51574. lmat.multiplyToRef(parentScaleInv, lmat);
  51575. }
  51576. else {
  51577. lmat.multiplyToRef(rmat, lmat);
  51578. }
  51579. }
  51580. lmat.m[12] = lx;
  51581. lmat.m[13] = ly;
  51582. lmat.m[14] = lz;
  51583. this.computeAbsoluteTransforms();
  51584. this.markAsDirty();
  51585. };
  51586. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  51587. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51588. if (space == BABYLON.Space.WORLD) {
  51589. var scaleMatrix = Bone._tmpMats[2];
  51590. scaleMatrix.copyFrom(this._scaleMatrix);
  51591. rotMatInv.copyFrom(this.getAbsoluteTransform());
  51592. if (mesh) {
  51593. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  51594. var meshScale = Bone._tmpMats[3];
  51595. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  51596. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  51597. }
  51598. rotMatInv.invert();
  51599. scaleMatrix.m[0] *= this._scalingDeterminant;
  51600. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  51601. }
  51602. else {
  51603. rotMatInv.copyFrom(this.getLocalMatrix());
  51604. rotMatInv.invert();
  51605. var scaleMatrix = Bone._tmpMats[2];
  51606. scaleMatrix.copyFrom(this._scaleMatrix);
  51607. if (this._parent) {
  51608. var pscaleMatrix = Bone._tmpMats[3];
  51609. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  51610. pscaleMatrix.invert();
  51611. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  51612. }
  51613. else {
  51614. scaleMatrix.m[0] *= this._scalingDeterminant;
  51615. }
  51616. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  51617. }
  51618. };
  51619. /**
  51620. * Get the scale of the bone
  51621. * @returns the scale of the bone
  51622. */
  51623. Bone.prototype.getScale = function () {
  51624. return this._scaleVector.clone();
  51625. };
  51626. /**
  51627. * Copy the scale of the bone to a vector3.
  51628. * @param result The vector3 to copy the scale to
  51629. */
  51630. Bone.prototype.getScaleToRef = function (result) {
  51631. result.copyFrom(this._scaleVector);
  51632. };
  51633. /**
  51634. * Get the position of the bone in local or world space.
  51635. * @param space The space that the returned position is in.
  51636. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51637. * @returns The position of the bone
  51638. */
  51639. Bone.prototype.getPosition = function (space, mesh) {
  51640. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51641. var pos = BABYLON.Vector3.Zero();
  51642. this.getPositionToRef(space, mesh, pos);
  51643. return pos;
  51644. };
  51645. /**
  51646. * Copy the position of the bone to a vector3 in local or world space.
  51647. * @param space The space that the returned position is in.
  51648. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51649. * @param result The vector3 to copy the position to.
  51650. */
  51651. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  51652. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51653. if (space == BABYLON.Space.LOCAL) {
  51654. var lm = this.getLocalMatrix();
  51655. result.x = lm.m[12];
  51656. result.y = lm.m[13];
  51657. result.z = lm.m[14];
  51658. }
  51659. else {
  51660. var wm;
  51661. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  51662. if (mesh) {
  51663. wm = mesh.getWorldMatrix();
  51664. }
  51665. this._skeleton.computeAbsoluteTransforms();
  51666. var tmat = Bone._tmpMats[0];
  51667. if (mesh) {
  51668. tmat.copyFrom(this.getAbsoluteTransform());
  51669. tmat.multiplyToRef(wm, tmat);
  51670. }
  51671. else {
  51672. tmat = this.getAbsoluteTransform();
  51673. }
  51674. result.x = tmat.m[12];
  51675. result.y = tmat.m[13];
  51676. result.z = tmat.m[14];
  51677. }
  51678. };
  51679. /**
  51680. * Get the absolute position of the bone (world space).
  51681. * @param mesh The mesh that this bone is attached to.
  51682. * @returns The absolute position of the bone
  51683. */
  51684. Bone.prototype.getAbsolutePosition = function (mesh) {
  51685. var pos = BABYLON.Vector3.Zero();
  51686. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  51687. return pos;
  51688. };
  51689. /**
  51690. * Copy the absolute position of the bone (world space) to the result param.
  51691. * @param mesh The mesh that this bone is attached to.
  51692. * @param result The vector3 to copy the absolute position to.
  51693. */
  51694. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  51695. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  51696. };
  51697. /**
  51698. * Compute the absolute transforms of this bone and its children.
  51699. */
  51700. Bone.prototype.computeAbsoluteTransforms = function () {
  51701. if (this._parent) {
  51702. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  51703. }
  51704. else {
  51705. this._absoluteTransform.copyFrom(this._localMatrix);
  51706. var poseMatrix = this._skeleton.getPoseMatrix();
  51707. if (poseMatrix) {
  51708. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  51709. }
  51710. }
  51711. var children = this.children;
  51712. var len = children.length;
  51713. for (var i = 0; i < len; i++) {
  51714. children[i].computeAbsoluteTransforms();
  51715. }
  51716. };
  51717. Bone.prototype._syncScaleVector = function () {
  51718. var lm = this.getLocalMatrix();
  51719. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  51720. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  51721. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  51722. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  51723. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  51724. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  51725. this._scaleVector.x = xs * Math.sqrt(xsq);
  51726. this._scaleVector.y = ys * Math.sqrt(ysq);
  51727. this._scaleVector.z = zs * Math.sqrt(zsq);
  51728. if (this._parent) {
  51729. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  51730. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  51731. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  51732. }
  51733. 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);
  51734. };
  51735. /**
  51736. * Get the world direction from an axis that is in the local space of the bone.
  51737. * @param localAxis The local direction that is used to compute the world direction.
  51738. * @param mesh The mesh that this bone is attached to.
  51739. * @returns The world direction
  51740. */
  51741. Bone.prototype.getDirection = function (localAxis, mesh) {
  51742. var result = BABYLON.Vector3.Zero();
  51743. this.getDirectionToRef(localAxis, mesh, result);
  51744. return result;
  51745. };
  51746. /**
  51747. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  51748. * @param localAxis The local direction that is used to compute the world direction.
  51749. * @param mesh The mesh that this bone is attached to.
  51750. * @param result The vector3 that the world direction will be copied to.
  51751. */
  51752. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  51753. var wm;
  51754. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  51755. if (mesh) {
  51756. wm = mesh.getWorldMatrix();
  51757. }
  51758. this._skeleton.computeAbsoluteTransforms();
  51759. var mat = Bone._tmpMats[0];
  51760. mat.copyFrom(this.getAbsoluteTransform());
  51761. if (mesh) {
  51762. mat.multiplyToRef(wm, mat);
  51763. }
  51764. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  51765. result.normalize();
  51766. };
  51767. /**
  51768. * Get the euler rotation of the bone in local or world space.
  51769. * @param space The space that the rotation should be in.
  51770. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51771. * @returns The euler rotation
  51772. */
  51773. Bone.prototype.getRotation = function (space, mesh) {
  51774. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51775. var result = BABYLON.Vector3.Zero();
  51776. this.getRotationToRef(space, mesh, result);
  51777. return result;
  51778. };
  51779. /**
  51780. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  51781. * @param space The space that the rotation should be in.
  51782. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51783. * @param result The vector3 that the rotation should be copied to.
  51784. */
  51785. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  51786. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51787. var quat = Bone._tmpQuat;
  51788. this.getRotationQuaternionToRef(space, mesh, quat);
  51789. quat.toEulerAnglesToRef(result);
  51790. };
  51791. /**
  51792. * Get the quaternion rotation of the bone in either local or world space.
  51793. * @param space The space that the rotation should be in.
  51794. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51795. * @returns The quaternion rotation
  51796. */
  51797. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  51798. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51799. var result = BABYLON.Quaternion.Identity();
  51800. this.getRotationQuaternionToRef(space, mesh, result);
  51801. return result;
  51802. };
  51803. /**
  51804. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  51805. * @param space The space that the rotation should be in.
  51806. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51807. * @param result The quaternion that the rotation should be copied to.
  51808. */
  51809. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  51810. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51811. if (space == BABYLON.Space.LOCAL) {
  51812. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  51813. }
  51814. else {
  51815. var mat = Bone._tmpMats[0];
  51816. var amat = this.getAbsoluteTransform();
  51817. if (mesh) {
  51818. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  51819. }
  51820. else {
  51821. mat.copyFrom(amat);
  51822. }
  51823. mat.m[0] *= this._scalingDeterminant;
  51824. mat.m[1] *= this._scalingDeterminant;
  51825. mat.m[2] *= this._scalingDeterminant;
  51826. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  51827. }
  51828. };
  51829. /**
  51830. * Get the rotation matrix of the bone in local or world space.
  51831. * @param space The space that the rotation should be in.
  51832. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51833. * @returns The rotation matrix
  51834. */
  51835. Bone.prototype.getRotationMatrix = function (space, mesh) {
  51836. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51837. var result = BABYLON.Matrix.Identity();
  51838. this.getRotationMatrixToRef(space, mesh, result);
  51839. return result;
  51840. };
  51841. /**
  51842. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  51843. * @param space The space that the rotation should be in.
  51844. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  51845. * @param result The quaternion that the rotation should be copied to.
  51846. */
  51847. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  51848. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  51849. if (space == BABYLON.Space.LOCAL) {
  51850. this.getLocalMatrix().getRotationMatrixToRef(result);
  51851. }
  51852. else {
  51853. var mat = Bone._tmpMats[0];
  51854. var amat = this.getAbsoluteTransform();
  51855. if (mesh) {
  51856. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  51857. }
  51858. else {
  51859. mat.copyFrom(amat);
  51860. }
  51861. mat.m[0] *= this._scalingDeterminant;
  51862. mat.m[1] *= this._scalingDeterminant;
  51863. mat.m[2] *= this._scalingDeterminant;
  51864. mat.getRotationMatrixToRef(result);
  51865. }
  51866. };
  51867. /**
  51868. * Get the world position of a point that is in the local space of the bone.
  51869. * @param position The local position
  51870. * @param mesh The mesh that this bone is attached to.
  51871. * @returns The world position
  51872. */
  51873. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  51874. var result = BABYLON.Vector3.Zero();
  51875. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  51876. return result;
  51877. };
  51878. /**
  51879. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  51880. * @param position The local position
  51881. * @param mesh The mesh that this bone is attached to.
  51882. * @param result The vector3 that the world position should be copied to.
  51883. */
  51884. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  51885. var wm;
  51886. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  51887. if (mesh) {
  51888. wm = mesh.getWorldMatrix();
  51889. }
  51890. this._skeleton.computeAbsoluteTransforms();
  51891. var tmat = Bone._tmpMats[0];
  51892. if (mesh) {
  51893. tmat.copyFrom(this.getAbsoluteTransform());
  51894. tmat.multiplyToRef(wm, tmat);
  51895. }
  51896. else {
  51897. tmat = this.getAbsoluteTransform();
  51898. }
  51899. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  51900. };
  51901. /**
  51902. * Get the local position of a point that is in world space.
  51903. * @param position The world position
  51904. * @param mesh The mesh that this bone is attached to.
  51905. * @returns The local position
  51906. */
  51907. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  51908. var result = BABYLON.Vector3.Zero();
  51909. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  51910. return result;
  51911. };
  51912. /**
  51913. * Get the local position of a point that is in world space and copy it to the result param.
  51914. * @param position The world position
  51915. * @param mesh The mesh that this bone is attached to.
  51916. * @param result The vector3 that the local position should be copied to.
  51917. */
  51918. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  51919. var wm;
  51920. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  51921. if (mesh) {
  51922. wm = mesh.getWorldMatrix();
  51923. }
  51924. this._skeleton.computeAbsoluteTransforms();
  51925. var tmat = Bone._tmpMats[0];
  51926. tmat.copyFrom(this.getAbsoluteTransform());
  51927. if (mesh) {
  51928. tmat.multiplyToRef(wm, tmat);
  51929. }
  51930. tmat.invert();
  51931. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  51932. };
  51933. return Bone;
  51934. }(BABYLON.Node));
  51935. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51936. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  51937. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  51938. BABYLON.Bone = Bone;
  51939. })(BABYLON || (BABYLON = {}));
  51940. //# sourceMappingURL=babylon.bone.js.map
  51941. var BABYLON;
  51942. (function (BABYLON) {
  51943. var BoneIKController = (function () {
  51944. function BoneIKController(mesh, bone, options) {
  51945. this.targetPosition = BABYLON.Vector3.Zero();
  51946. this.poleTargetPosition = BABYLON.Vector3.Zero();
  51947. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  51948. this.poleAngle = 0;
  51949. this.slerpAmount = 1;
  51950. this._bone1Quat = BABYLON.Quaternion.Identity();
  51951. this._bone1Mat = BABYLON.Matrix.Identity();
  51952. this._bone2Ang = Math.PI;
  51953. this._maxAngle = Math.PI;
  51954. this._rightHandedSystem = false;
  51955. this._bendAxis = BABYLON.Vector3.Right();
  51956. this._slerping = false;
  51957. this._adjustRoll = 0;
  51958. this._bone2 = bone;
  51959. this._bone1 = bone.getParent();
  51960. this.mesh = mesh;
  51961. var bonePos = bone.getPosition();
  51962. if (bone.getAbsoluteTransform().determinant() > 0) {
  51963. this._rightHandedSystem = true;
  51964. this._bendAxis.x = 0;
  51965. this._bendAxis.y = 0;
  51966. this._bendAxis.z = -1;
  51967. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  51968. this._adjustRoll = Math.PI * .5;
  51969. this._bendAxis.z = 1;
  51970. }
  51971. }
  51972. if (this._bone1.length) {
  51973. var boneScale1 = this._bone1.getScale();
  51974. var boneScale2 = this._bone2.getScale();
  51975. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  51976. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  51977. }
  51978. else if (this._bone1.children[0]) {
  51979. mesh.computeWorldMatrix(true);
  51980. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  51981. var pos2 = this._bone2.getAbsolutePosition(mesh);
  51982. var pos3 = this._bone1.getAbsolutePosition(mesh);
  51983. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  51984. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  51985. }
  51986. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  51987. this.maxAngle = Math.PI;
  51988. if (options) {
  51989. if (options.targetMesh) {
  51990. this.targetMesh = options.targetMesh;
  51991. this.targetMesh.computeWorldMatrix(true);
  51992. }
  51993. if (options.poleTargetMesh) {
  51994. this.poleTargetMesh = options.poleTargetMesh;
  51995. this.poleTargetMesh.computeWorldMatrix(true);
  51996. }
  51997. else if (options.poleTargetBone) {
  51998. this.poleTargetBone = options.poleTargetBone;
  51999. }
  52000. else if (this._bone1.getParent()) {
  52001. this.poleTargetBone = this._bone1.getParent();
  52002. }
  52003. if (options.poleTargetLocalOffset) {
  52004. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  52005. }
  52006. if (options.poleAngle) {
  52007. this.poleAngle = options.poleAngle;
  52008. }
  52009. if (options.bendAxis) {
  52010. this._bendAxis.copyFrom(options.bendAxis);
  52011. }
  52012. if (options.maxAngle) {
  52013. this.maxAngle = options.maxAngle;
  52014. }
  52015. if (options.slerpAmount) {
  52016. this.slerpAmount = options.slerpAmount;
  52017. }
  52018. }
  52019. }
  52020. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  52021. get: function () {
  52022. return this._maxAngle;
  52023. },
  52024. set: function (value) {
  52025. this._setMaxAngle(value);
  52026. },
  52027. enumerable: true,
  52028. configurable: true
  52029. });
  52030. BoneIKController.prototype._setMaxAngle = function (ang) {
  52031. if (ang < 0) {
  52032. ang = 0;
  52033. }
  52034. if (ang > Math.PI || ang == undefined) {
  52035. ang = Math.PI;
  52036. }
  52037. this._maxAngle = ang;
  52038. var a = this._bone1Length;
  52039. var b = this._bone2Length;
  52040. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  52041. };
  52042. BoneIKController.prototype.update = function () {
  52043. var bone1 = this._bone1;
  52044. var target = this.targetPosition;
  52045. var poleTarget = this.poleTargetPosition;
  52046. var mat1 = BoneIKController._tmpMats[0];
  52047. var mat2 = BoneIKController._tmpMats[1];
  52048. if (this.targetMesh) {
  52049. target.copyFrom(this.targetMesh.getAbsolutePosition());
  52050. }
  52051. if (this.poleTargetBone) {
  52052. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  52053. }
  52054. else if (this.poleTargetMesh) {
  52055. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  52056. }
  52057. var bonePos = BoneIKController._tmpVecs[0];
  52058. var zaxis = BoneIKController._tmpVecs[1];
  52059. var xaxis = BoneIKController._tmpVecs[2];
  52060. var yaxis = BoneIKController._tmpVecs[3];
  52061. var upAxis = BoneIKController._tmpVecs[4];
  52062. var _tmpQuat = BoneIKController._tmpQuat;
  52063. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  52064. poleTarget.subtractToRef(bonePos, upAxis);
  52065. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  52066. upAxis.y = 1;
  52067. }
  52068. else {
  52069. upAxis.normalize();
  52070. }
  52071. target.subtractToRef(bonePos, yaxis);
  52072. yaxis.normalize();
  52073. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  52074. zaxis.normalize();
  52075. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  52076. xaxis.normalize();
  52077. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  52078. var a = this._bone1Length;
  52079. var b = this._bone2Length;
  52080. var c = BABYLON.Vector3.Distance(bonePos, target);
  52081. if (this._maxReach > 0) {
  52082. c = Math.min(this._maxReach, c);
  52083. }
  52084. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  52085. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  52086. if (acosa > 1) {
  52087. acosa = 1;
  52088. }
  52089. if (acosb > 1) {
  52090. acosb = 1;
  52091. }
  52092. if (acosa < -1) {
  52093. acosa = -1;
  52094. }
  52095. if (acosb < -1) {
  52096. acosb = -1;
  52097. }
  52098. var angA = Math.acos(acosa);
  52099. var angB = Math.acos(acosb);
  52100. var angC = -angA - angB;
  52101. if (this._rightHandedSystem) {
  52102. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  52103. mat2.multiplyToRef(mat1, mat1);
  52104. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  52105. mat2.multiplyToRef(mat1, mat1);
  52106. }
  52107. else {
  52108. var _tmpVec = BoneIKController._tmpVecs[5];
  52109. _tmpVec.copyFrom(this._bendAxis);
  52110. _tmpVec.x *= -1;
  52111. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  52112. mat2.multiplyToRef(mat1, mat1);
  52113. }
  52114. if (this.poleAngle) {
  52115. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  52116. mat1.multiplyToRef(mat2, mat1);
  52117. }
  52118. if (this.slerpAmount < 1) {
  52119. if (!this._slerping) {
  52120. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  52121. }
  52122. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  52123. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  52124. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  52125. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  52126. this._slerping = true;
  52127. }
  52128. else {
  52129. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  52130. this._bone1Mat.copyFrom(mat1);
  52131. this._slerping = false;
  52132. }
  52133. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  52134. this._bone2Ang = angC;
  52135. };
  52136. return BoneIKController;
  52137. }());
  52138. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52139. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  52140. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  52141. BABYLON.BoneIKController = BoneIKController;
  52142. })(BABYLON || (BABYLON = {}));
  52143. //# sourceMappingURL=babylon.boneIKController.js.map
  52144. var BABYLON;
  52145. (function (BABYLON) {
  52146. var BoneLookController = (function () {
  52147. /**
  52148. * Create a BoneLookController
  52149. * @param mesh the mesh that the bone belongs to
  52150. * @param bone the bone that will be looking to the target
  52151. * @param target the target Vector3 to look at
  52152. * @param settings optional settings:
  52153. * - maxYaw: the maximum angle the bone will yaw to
  52154. * - minYaw: the minimum angle the bone will yaw to
  52155. * - maxPitch: the maximum angle the bone will pitch to
  52156. * - minPitch: the minimum angle the bone will yaw to
  52157. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  52158. * - upAxis: the up axis of the coordinate system
  52159. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  52160. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  52161. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  52162. * - adjustYaw: used to make an adjustment to the yaw of the bone
  52163. * - adjustPitch: used to make an adjustment to the pitch of the bone
  52164. * - adjustRoll: used to make an adjustment to the roll of the bone
  52165. **/
  52166. function BoneLookController(mesh, bone, target, options) {
  52167. /**
  52168. * The up axis of the coordinate system that is used when the bone is rotated.
  52169. */
  52170. this.upAxis = BABYLON.Vector3.Up();
  52171. /**
  52172. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  52173. */
  52174. this.upAxisSpace = BABYLON.Space.LOCAL;
  52175. /**
  52176. * Used to make an adjustment to the yaw of the bone.
  52177. */
  52178. this.adjustYaw = 0;
  52179. /**
  52180. * Used to make an adjustment to the pitch of the bone.
  52181. */
  52182. this.adjustPitch = 0;
  52183. /**
  52184. * Used to make an adjustment to the roll of the bone.
  52185. */
  52186. this.adjustRoll = 0;
  52187. /**
  52188. * 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).
  52189. */
  52190. this.slerpAmount = 1;
  52191. this._boneQuat = BABYLON.Quaternion.Identity();
  52192. this._slerping = false;
  52193. this._firstFrameSkipped = false;
  52194. this._fowardAxis = BABYLON.Vector3.Forward();
  52195. this.mesh = mesh;
  52196. this.bone = bone;
  52197. this.target = target;
  52198. if (options) {
  52199. if (options.adjustYaw) {
  52200. this.adjustYaw = options.adjustYaw;
  52201. }
  52202. if (options.adjustPitch) {
  52203. this.adjustPitch = options.adjustPitch;
  52204. }
  52205. if (options.adjustRoll) {
  52206. this.adjustRoll = options.adjustRoll;
  52207. }
  52208. if (options.maxYaw != null) {
  52209. this.maxYaw = options.maxYaw;
  52210. }
  52211. else {
  52212. this.maxYaw = Math.PI;
  52213. }
  52214. if (options.minYaw != null) {
  52215. this.minYaw = options.minYaw;
  52216. }
  52217. else {
  52218. this.minYaw = -Math.PI;
  52219. }
  52220. if (options.maxPitch != null) {
  52221. this.maxPitch = options.maxPitch;
  52222. }
  52223. else {
  52224. this.maxPitch = Math.PI;
  52225. }
  52226. if (options.minPitch != null) {
  52227. this.minPitch = options.minPitch;
  52228. }
  52229. else {
  52230. this.minPitch = -Math.PI;
  52231. }
  52232. if (options.slerpAmount != null) {
  52233. this.slerpAmount = options.slerpAmount;
  52234. }
  52235. if (options.upAxis != null) {
  52236. this.upAxis = options.upAxis;
  52237. }
  52238. if (options.upAxisSpace != null) {
  52239. this.upAxisSpace = options.upAxisSpace;
  52240. }
  52241. if (options.yawAxis != null || options.pitchAxis != null) {
  52242. var newYawAxis = BABYLON.Axis.Y;
  52243. var newPitchAxis = BABYLON.Axis.X;
  52244. if (options.yawAxis != null) {
  52245. newYawAxis = options.yawAxis.clone();
  52246. newYawAxis.normalize();
  52247. }
  52248. if (options.pitchAxis != null) {
  52249. newPitchAxis = options.pitchAxis.clone();
  52250. newPitchAxis.normalize();
  52251. }
  52252. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  52253. this._transformYawPitch = BABYLON.Matrix.Identity();
  52254. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  52255. this._transformYawPitchInv = this._transformYawPitch.clone();
  52256. this._transformYawPitch.invert();
  52257. }
  52258. }
  52259. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  52260. this.upAxisSpace = BABYLON.Space.LOCAL;
  52261. }
  52262. }
  52263. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  52264. /**
  52265. * Get/set the minimum yaw angle that the bone can look to.
  52266. */
  52267. get: function () {
  52268. return this._minYaw;
  52269. },
  52270. set: function (value) {
  52271. this._minYaw = value;
  52272. this._minYawSin = Math.sin(value);
  52273. this._minYawCos = Math.cos(value);
  52274. if (this._maxYaw != null) {
  52275. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  52276. this._yawRange = this._maxYaw - this._minYaw;
  52277. }
  52278. },
  52279. enumerable: true,
  52280. configurable: true
  52281. });
  52282. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  52283. /**
  52284. * Get/set the maximum yaw angle that the bone can look to.
  52285. */
  52286. get: function () {
  52287. return this._maxYaw;
  52288. },
  52289. set: function (value) {
  52290. this._maxYaw = value;
  52291. this._maxYawSin = Math.sin(value);
  52292. this._maxYawCos = Math.cos(value);
  52293. if (this._minYaw != null) {
  52294. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  52295. this._yawRange = this._maxYaw - this._minYaw;
  52296. }
  52297. },
  52298. enumerable: true,
  52299. configurable: true
  52300. });
  52301. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  52302. /**
  52303. * Get/set the minimum pitch angle that the bone can look to.
  52304. */
  52305. get: function () {
  52306. return this._minPitch;
  52307. },
  52308. set: function (value) {
  52309. this._minPitch = value;
  52310. this._minPitchTan = Math.tan(value);
  52311. },
  52312. enumerable: true,
  52313. configurable: true
  52314. });
  52315. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  52316. /**
  52317. * Get/set the maximum pitch angle that the bone can look to.
  52318. */
  52319. get: function () {
  52320. return this._maxPitch;
  52321. },
  52322. set: function (value) {
  52323. this._maxPitch = value;
  52324. this._maxPitchTan = Math.tan(value);
  52325. },
  52326. enumerable: true,
  52327. configurable: true
  52328. });
  52329. /**
  52330. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  52331. */
  52332. BoneLookController.prototype.update = function () {
  52333. //skip the first frame when slerping so that the mesh rotation is correct
  52334. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  52335. this._firstFrameSkipped = true;
  52336. return;
  52337. }
  52338. var bone = this.bone;
  52339. var bonePos = BoneLookController._tmpVecs[0];
  52340. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  52341. var target = this.target;
  52342. var _tmpMat1 = BoneLookController._tmpMats[0];
  52343. var _tmpMat2 = BoneLookController._tmpMats[1];
  52344. var mesh = this.mesh;
  52345. var parentBone = bone.getParent();
  52346. var upAxis = BoneLookController._tmpVecs[1];
  52347. upAxis.copyFrom(this.upAxis);
  52348. if (this.upAxisSpace == BABYLON.Space.BONE) {
  52349. if (this._transformYawPitch) {
  52350. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  52351. }
  52352. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  52353. }
  52354. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  52355. mesh.getDirectionToRef(upAxis, upAxis);
  52356. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  52357. upAxis.normalize();
  52358. }
  52359. }
  52360. var checkYaw = false;
  52361. var checkPitch = false;
  52362. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  52363. checkYaw = true;
  52364. }
  52365. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  52366. checkPitch = true;
  52367. }
  52368. if (checkYaw || checkPitch) {
  52369. var spaceMat = BoneLookController._tmpMats[2];
  52370. var spaceMatInv = BoneLookController._tmpMats[3];
  52371. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  52372. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  52373. }
  52374. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  52375. spaceMat.copyFrom(mesh.getWorldMatrix());
  52376. }
  52377. else {
  52378. var forwardAxis = BoneLookController._tmpVecs[2];
  52379. forwardAxis.copyFrom(this._fowardAxis);
  52380. if (this._transformYawPitch) {
  52381. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  52382. }
  52383. if (parentBone) {
  52384. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  52385. }
  52386. else {
  52387. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  52388. }
  52389. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  52390. rightAxis.normalize();
  52391. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  52392. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  52393. }
  52394. spaceMat.invertToRef(spaceMatInv);
  52395. var xzlen;
  52396. if (checkPitch) {
  52397. var localTarget = BoneLookController._tmpVecs[3];
  52398. target.subtractToRef(bonePos, localTarget);
  52399. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  52400. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  52401. var pitch = Math.atan2(localTarget.y, xzlen);
  52402. var newPitch = pitch;
  52403. if (pitch > this._maxPitch) {
  52404. localTarget.y = this._maxPitchTan * xzlen;
  52405. newPitch = this._maxPitch;
  52406. }
  52407. else if (pitch < this._minPitch) {
  52408. localTarget.y = this._minPitchTan * xzlen;
  52409. newPitch = this._minPitch;
  52410. }
  52411. if (pitch != newPitch) {
  52412. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  52413. localTarget.addInPlace(bonePos);
  52414. target = localTarget;
  52415. }
  52416. }
  52417. if (checkYaw) {
  52418. var localTarget = BoneLookController._tmpVecs[4];
  52419. target.subtractToRef(bonePos, localTarget);
  52420. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  52421. var yaw = Math.atan2(localTarget.x, localTarget.z);
  52422. var newYaw = yaw;
  52423. if (yaw > this._maxYaw || yaw < this._minYaw) {
  52424. if (xzlen == null) {
  52425. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  52426. }
  52427. if (this._yawRange > Math.PI) {
  52428. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  52429. localTarget.z = this._maxYawCos * xzlen;
  52430. localTarget.x = this._maxYawSin * xzlen;
  52431. newYaw = this._maxYaw;
  52432. }
  52433. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  52434. localTarget.z = this._minYawCos * xzlen;
  52435. localTarget.x = this._minYawSin * xzlen;
  52436. newYaw = this._minYaw;
  52437. }
  52438. }
  52439. else {
  52440. if (yaw > this._maxYaw) {
  52441. localTarget.z = this._maxYawCos * xzlen;
  52442. localTarget.x = this._maxYawSin * xzlen;
  52443. newYaw = this._maxYaw;
  52444. }
  52445. else if (yaw < this._minYaw) {
  52446. localTarget.z = this._minYawCos * xzlen;
  52447. localTarget.x = this._minYawSin * xzlen;
  52448. newYaw = this._minYaw;
  52449. }
  52450. }
  52451. }
  52452. if (this._slerping && this._yawRange > Math.PI) {
  52453. //are we going to be crossing into the min/max region?
  52454. var boneFwd = BoneLookController._tmpVecs[8];
  52455. boneFwd.copyFrom(BABYLON.Axis.Z);
  52456. if (this._transformYawPitch) {
  52457. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  52458. }
  52459. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  52460. this._boneQuat.toRotationMatrix(boneRotMat);
  52461. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  52462. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  52463. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  52464. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  52465. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  52466. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  52467. if (angBtwTar > angBtwMidYaw) {
  52468. if (xzlen == null) {
  52469. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  52470. }
  52471. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  52472. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  52473. if (angBtwMin < angBtwMax) {
  52474. newYaw = boneYaw + Math.PI * .75;
  52475. localTarget.z = Math.cos(newYaw) * xzlen;
  52476. localTarget.x = Math.sin(newYaw) * xzlen;
  52477. }
  52478. else {
  52479. newYaw = boneYaw - Math.PI * .75;
  52480. localTarget.z = Math.cos(newYaw) * xzlen;
  52481. localTarget.x = Math.sin(newYaw) * xzlen;
  52482. }
  52483. }
  52484. }
  52485. if (yaw != newYaw) {
  52486. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  52487. localTarget.addInPlace(bonePos);
  52488. target = localTarget;
  52489. }
  52490. }
  52491. }
  52492. var zaxis = BoneLookController._tmpVecs[5];
  52493. var xaxis = BoneLookController._tmpVecs[6];
  52494. var yaxis = BoneLookController._tmpVecs[7];
  52495. var _tmpQuat = BoneLookController._tmpQuat;
  52496. target.subtractToRef(bonePos, zaxis);
  52497. zaxis.normalize();
  52498. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  52499. xaxis.normalize();
  52500. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  52501. yaxis.normalize();
  52502. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  52503. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  52504. return;
  52505. }
  52506. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  52507. return;
  52508. }
  52509. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  52510. return;
  52511. }
  52512. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  52513. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  52514. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  52515. }
  52516. if (this.slerpAmount < 1) {
  52517. if (!this._slerping) {
  52518. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  52519. }
  52520. if (this._transformYawPitch) {
  52521. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  52522. }
  52523. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  52524. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  52525. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  52526. this._slerping = true;
  52527. }
  52528. else {
  52529. if (this._transformYawPitch) {
  52530. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  52531. }
  52532. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  52533. this._slerping = false;
  52534. }
  52535. };
  52536. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  52537. var angDiff = ang2 - ang1;
  52538. angDiff %= Math.PI * 2;
  52539. if (angDiff > Math.PI) {
  52540. angDiff -= Math.PI * 2;
  52541. }
  52542. else if (angDiff < -Math.PI) {
  52543. angDiff += Math.PI * 2;
  52544. }
  52545. return angDiff;
  52546. };
  52547. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  52548. ang1 %= (2 * Math.PI);
  52549. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  52550. ang2 %= (2 * Math.PI);
  52551. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  52552. var ab = 0;
  52553. if (ang1 < ang2) {
  52554. ab = ang2 - ang1;
  52555. }
  52556. else {
  52557. ab = ang1 - ang2;
  52558. }
  52559. if (ab > Math.PI) {
  52560. ab = Math.PI * 2 - ab;
  52561. }
  52562. return ab;
  52563. };
  52564. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  52565. ang %= (2 * Math.PI);
  52566. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  52567. ang1 %= (2 * Math.PI);
  52568. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  52569. ang2 %= (2 * Math.PI);
  52570. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  52571. if (ang1 < ang2) {
  52572. if (ang > ang1 && ang < ang2) {
  52573. return true;
  52574. }
  52575. }
  52576. else {
  52577. if (ang > ang2 && ang < ang1) {
  52578. return true;
  52579. }
  52580. }
  52581. return false;
  52582. };
  52583. return BoneLookController;
  52584. }());
  52585. 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()];
  52586. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  52587. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  52588. BABYLON.BoneLookController = BoneLookController;
  52589. })(BABYLON || (BABYLON = {}));
  52590. //# sourceMappingURL=babylon.boneLookController.js.map
  52591. var BABYLON;
  52592. (function (BABYLON) {
  52593. var Skeleton = (function () {
  52594. function Skeleton(name, id, scene) {
  52595. this.name = name;
  52596. this.id = id;
  52597. this.bones = new Array();
  52598. this.needInitialSkinMatrix = false;
  52599. this._isDirty = true;
  52600. this._meshesWithPoseMatrix = new Array();
  52601. this._identity = BABYLON.Matrix.Identity();
  52602. this._ranges = {};
  52603. this._lastAbsoluteTransformsUpdateId = -1;
  52604. // Events
  52605. /**
  52606. * An event triggered before computing the skeleton's matrices
  52607. * @type {BABYLON.Observable}
  52608. */
  52609. this.onBeforeComputeObservable = new BABYLON.Observable();
  52610. this.bones = [];
  52611. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52612. scene.skeletons.push(this);
  52613. //make sure it will recalculate the matrix next time prepare is called.
  52614. this._isDirty = true;
  52615. }
  52616. // Members
  52617. Skeleton.prototype.getTransformMatrices = function (mesh) {
  52618. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  52619. return mesh._bonesTransformMatrices;
  52620. }
  52621. if (!this._transformMatrices) {
  52622. this.prepare();
  52623. }
  52624. return this._transformMatrices;
  52625. };
  52626. Skeleton.prototype.getScene = function () {
  52627. return this._scene;
  52628. };
  52629. // Methods
  52630. /**
  52631. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  52632. */
  52633. Skeleton.prototype.toString = function (fullDetails) {
  52634. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  52635. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  52636. if (fullDetails) {
  52637. ret += ", Ranges: {";
  52638. var first = true;
  52639. for (var name_1 in this._ranges) {
  52640. if (first) {
  52641. ret += ", ";
  52642. first = false;
  52643. }
  52644. ret += name_1;
  52645. }
  52646. ret += "}";
  52647. }
  52648. return ret;
  52649. };
  52650. /**
  52651. * Get bone's index searching by name
  52652. * @param {string} name is bone's name to search for
  52653. * @return {number} Indice of the bone. Returns -1 if not found
  52654. */
  52655. Skeleton.prototype.getBoneIndexByName = function (name) {
  52656. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  52657. if (this.bones[boneIndex].name === name) {
  52658. return boneIndex;
  52659. }
  52660. }
  52661. return -1;
  52662. };
  52663. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  52664. // check name not already in use
  52665. if (!this._ranges[name]) {
  52666. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  52667. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  52668. if (this.bones[i].animations[0]) {
  52669. this.bones[i].animations[0].createRange(name, from, to);
  52670. }
  52671. }
  52672. }
  52673. };
  52674. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  52675. if (deleteFrames === void 0) { deleteFrames = true; }
  52676. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  52677. if (this.bones[i].animations[0]) {
  52678. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  52679. }
  52680. }
  52681. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  52682. };
  52683. Skeleton.prototype.getAnimationRange = function (name) {
  52684. return this._ranges[name];
  52685. };
  52686. /**
  52687. * Returns as an Array, all AnimationRanges defined on this skeleton
  52688. */
  52689. Skeleton.prototype.getAnimationRanges = function () {
  52690. var animationRanges = [];
  52691. var name;
  52692. var i = 0;
  52693. for (name in this._ranges) {
  52694. animationRanges[i] = this._ranges[name];
  52695. i++;
  52696. }
  52697. return animationRanges;
  52698. };
  52699. /**
  52700. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  52701. */
  52702. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  52703. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  52704. if (this._ranges[name] || !source.getAnimationRange(name)) {
  52705. return false;
  52706. }
  52707. var ret = true;
  52708. var frameOffset = this._getHighestAnimationFrame() + 1;
  52709. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  52710. var boneDict = {};
  52711. var sourceBones = source.bones;
  52712. var nBones;
  52713. var i;
  52714. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  52715. boneDict[sourceBones[i].name] = sourceBones[i];
  52716. }
  52717. if (this.bones.length !== sourceBones.length) {
  52718. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  52719. ret = false;
  52720. }
  52721. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  52722. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  52723. var boneName = this.bones[i].name;
  52724. var sourceBone = boneDict[boneName];
  52725. if (sourceBone) {
  52726. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  52727. }
  52728. else {
  52729. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  52730. ret = false;
  52731. }
  52732. }
  52733. // do not call createAnimationRange(), since it also is done to bones, which was already done
  52734. var range = source.getAnimationRange(name);
  52735. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  52736. return ret;
  52737. };
  52738. Skeleton.prototype.returnToRest = function () {
  52739. for (var index = 0; index < this.bones.length; index++) {
  52740. this.bones[index].returnToRest();
  52741. }
  52742. };
  52743. Skeleton.prototype._getHighestAnimationFrame = function () {
  52744. var ret = 0;
  52745. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  52746. if (this.bones[i].animations[0]) {
  52747. var highest = this.bones[i].animations[0].getHighestFrame();
  52748. if (ret < highest) {
  52749. ret = highest;
  52750. }
  52751. }
  52752. }
  52753. return ret;
  52754. };
  52755. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  52756. var range = this.getAnimationRange(name);
  52757. if (!range) {
  52758. return null;
  52759. }
  52760. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  52761. };
  52762. Skeleton.prototype._markAsDirty = function () {
  52763. this._isDirty = true;
  52764. };
  52765. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  52766. this._meshesWithPoseMatrix.push(mesh);
  52767. };
  52768. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  52769. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  52770. if (index > -1) {
  52771. this._meshesWithPoseMatrix.splice(index, 1);
  52772. }
  52773. };
  52774. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  52775. this.onBeforeComputeObservable.notifyObservers(this);
  52776. for (var index = 0; index < this.bones.length; index++) {
  52777. var bone = this.bones[index];
  52778. var parentBone = bone.getParent();
  52779. if (parentBone) {
  52780. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  52781. }
  52782. else {
  52783. if (initialSkinMatrix) {
  52784. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  52785. }
  52786. else {
  52787. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  52788. }
  52789. }
  52790. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  52791. }
  52792. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  52793. };
  52794. Skeleton.prototype.prepare = function () {
  52795. if (!this._isDirty) {
  52796. return;
  52797. }
  52798. if (this.needInitialSkinMatrix) {
  52799. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  52800. var mesh = this._meshesWithPoseMatrix[index];
  52801. var poseMatrix = mesh.getPoseMatrix();
  52802. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  52803. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  52804. }
  52805. if (this._synchronizedWithMesh !== mesh) {
  52806. this._synchronizedWithMesh = mesh;
  52807. // Prepare bones
  52808. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  52809. var bone = this.bones[boneIndex];
  52810. if (!bone.getParent()) {
  52811. var matrix = bone.getBaseMatrix();
  52812. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  52813. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  52814. }
  52815. }
  52816. }
  52817. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  52818. }
  52819. }
  52820. else {
  52821. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  52822. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  52823. }
  52824. this._computeTransformMatrices(this._transformMatrices, null);
  52825. }
  52826. this._isDirty = false;
  52827. this._scene._activeBones.addCount(this.bones.length, false);
  52828. };
  52829. Skeleton.prototype.getAnimatables = function () {
  52830. if (!this._animatables || this._animatables.length !== this.bones.length) {
  52831. this._animatables = [];
  52832. for (var index = 0; index < this.bones.length; index++) {
  52833. this._animatables.push(this.bones[index]);
  52834. }
  52835. }
  52836. return this._animatables;
  52837. };
  52838. Skeleton.prototype.clone = function (name, id) {
  52839. var result = new Skeleton(name, id || name, this._scene);
  52840. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  52841. for (var index = 0; index < this.bones.length; index++) {
  52842. var source = this.bones[index];
  52843. var parentBone = null;
  52844. if (source.getParent()) {
  52845. var parentIndex = this.bones.indexOf(source.getParent());
  52846. parentBone = result.bones[parentIndex];
  52847. }
  52848. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  52849. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  52850. }
  52851. if (this._ranges) {
  52852. result._ranges = {};
  52853. for (var rangeName in this._ranges) {
  52854. result._ranges[rangeName] = this._ranges[rangeName].clone();
  52855. }
  52856. }
  52857. this._isDirty = true;
  52858. return result;
  52859. };
  52860. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  52861. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  52862. this.bones.forEach(function (bone) {
  52863. bone.animations.forEach(function (animation) {
  52864. animation.enableBlending = true;
  52865. animation.blendingSpeed = blendingSpeed;
  52866. });
  52867. });
  52868. };
  52869. Skeleton.prototype.dispose = function () {
  52870. this._meshesWithPoseMatrix = [];
  52871. // Animations
  52872. this.getScene().stopAnimation(this);
  52873. // Remove from scene
  52874. this.getScene().removeSkeleton(this);
  52875. };
  52876. Skeleton.prototype.serialize = function () {
  52877. var serializationObject = {};
  52878. serializationObject.name = this.name;
  52879. serializationObject.id = this.id;
  52880. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  52881. serializationObject.bones = [];
  52882. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  52883. for (var index = 0; index < this.bones.length; index++) {
  52884. var bone = this.bones[index];
  52885. var serializedBone = {
  52886. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  52887. name: bone.name,
  52888. matrix: bone.getBaseMatrix().toArray(),
  52889. rest: bone.getRestPose().toArray()
  52890. };
  52891. serializationObject.bones.push(serializedBone);
  52892. if (bone.length) {
  52893. serializedBone.length = bone.length;
  52894. }
  52895. if (bone.animations && bone.animations.length > 0) {
  52896. serializedBone.animation = bone.animations[0].serialize();
  52897. }
  52898. serializationObject.ranges = [];
  52899. for (var name in this._ranges) {
  52900. var range = {};
  52901. range.name = name;
  52902. range.from = this._ranges[name].from;
  52903. range.to = this._ranges[name].to;
  52904. serializationObject.ranges.push(range);
  52905. }
  52906. }
  52907. return serializationObject;
  52908. };
  52909. Skeleton.Parse = function (parsedSkeleton, scene) {
  52910. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  52911. if (parsedSkeleton.dimensionsAtRest) {
  52912. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  52913. }
  52914. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  52915. var index;
  52916. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  52917. var parsedBone = parsedSkeleton.bones[index];
  52918. var parentBone = null;
  52919. if (parsedBone.parentBoneIndex > -1) {
  52920. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  52921. }
  52922. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  52923. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  52924. if (parsedBone.length) {
  52925. bone.length = parsedBone.length;
  52926. }
  52927. if (parsedBone.animation) {
  52928. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  52929. }
  52930. }
  52931. // placed after bones, so createAnimationRange can cascade down
  52932. if (parsedSkeleton.ranges) {
  52933. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  52934. var data = parsedSkeleton.ranges[index];
  52935. skeleton.createAnimationRange(data.name, data.from, data.to);
  52936. }
  52937. }
  52938. return skeleton;
  52939. };
  52940. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  52941. if (forceUpdate === void 0) { forceUpdate = false; }
  52942. var renderId = this._scene.getRenderId();
  52943. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  52944. this.bones[0].computeAbsoluteTransforms();
  52945. this._lastAbsoluteTransformsUpdateId = renderId;
  52946. }
  52947. };
  52948. Skeleton.prototype.getPoseMatrix = function () {
  52949. var poseMatrix;
  52950. if (this._meshesWithPoseMatrix.length > 0) {
  52951. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  52952. }
  52953. return poseMatrix;
  52954. };
  52955. return Skeleton;
  52956. }());
  52957. BABYLON.Skeleton = Skeleton;
  52958. })(BABYLON || (BABYLON = {}));
  52959. //# sourceMappingURL=babylon.skeleton.js.map
  52960. var BABYLON;
  52961. (function (BABYLON) {
  52962. var Internals;
  52963. (function (Internals) {
  52964. var FileFaceOrientation = (function () {
  52965. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  52966. this.name = name;
  52967. this.worldAxisForNormal = worldAxisForNormal;
  52968. this.worldAxisForFileX = worldAxisForFileX;
  52969. this.worldAxisForFileY = worldAxisForFileY;
  52970. }
  52971. return FileFaceOrientation;
  52972. }());
  52973. ;
  52974. /**
  52975. * Helper class dealing with the extraction of spherical polynomial dataArray
  52976. * from a cube map.
  52977. */
  52978. var CubeMapToSphericalPolynomialTools = (function () {
  52979. function CubeMapToSphericalPolynomialTools() {
  52980. }
  52981. /**
  52982. * Converts a cubemap to the according Spherical Polynomial data.
  52983. * This extracts the first 3 orders only as they are the only one used in the lighting.
  52984. *
  52985. * @param cubeInfo The Cube map to extract the information from.
  52986. * @return The Spherical Polynomial data.
  52987. */
  52988. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  52989. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  52990. var totalSolidAngle = 0.0;
  52991. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  52992. var du = 2.0 / cubeInfo.size;
  52993. var dv = du;
  52994. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  52995. var minUV = du * 0.5 - 1.0;
  52996. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52997. var fileFace = this.FileFaces[faceIndex];
  52998. var dataArray = cubeInfo[fileFace.name];
  52999. var v = minUV;
  53000. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  53001. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  53002. // Because SP is still linear, so summation is fine in that basis.
  53003. for (var y = 0; y < cubeInfo.size; y++) {
  53004. var u = minUV;
  53005. for (var x = 0; x < cubeInfo.size; x++) {
  53006. // World direction (not normalised)
  53007. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  53008. worldDirection.normalize();
  53009. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  53010. if (1) {
  53011. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  53012. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  53013. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  53014. var color = new BABYLON.Color3(r, g, b);
  53015. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53016. }
  53017. else {
  53018. if (faceIndex == 0) {
  53019. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53020. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53021. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53022. }
  53023. else if (faceIndex == 1) {
  53024. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53025. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53026. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53027. }
  53028. else if (faceIndex == 2) {
  53029. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53030. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53031. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53032. }
  53033. else if (faceIndex == 3) {
  53034. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53035. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53036. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53037. }
  53038. else if (faceIndex == 4) {
  53039. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53040. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53041. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53042. }
  53043. else if (faceIndex == 5) {
  53044. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53045. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53046. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53047. }
  53048. 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]);
  53049. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53050. }
  53051. totalSolidAngle += deltaSolidAngle;
  53052. u += du;
  53053. }
  53054. v += dv;
  53055. }
  53056. }
  53057. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  53058. var correction = correctSolidAngle / totalSolidAngle;
  53059. sphericalHarmonics.scale(correction);
  53060. // Additionally scale by pi -- audit needed
  53061. sphericalHarmonics.scale(1.0 / Math.PI);
  53062. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  53063. };
  53064. return CubeMapToSphericalPolynomialTools;
  53065. }());
  53066. CubeMapToSphericalPolynomialTools.FileFaces = [
  53067. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  53068. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  53069. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  53070. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  53071. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  53072. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  53073. ];
  53074. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  53075. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53076. })(BABYLON || (BABYLON = {}));
  53077. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  53078. var BABYLON;
  53079. (function (BABYLON) {
  53080. var Internals;
  53081. (function (Internals) {
  53082. /**
  53083. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  53084. */
  53085. var PanoramaToCubeMapTools = (function () {
  53086. function PanoramaToCubeMapTools() {
  53087. }
  53088. /**
  53089. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  53090. *
  53091. * @param float32Array The source data.
  53092. * @param inputWidth The width of the input panorama.
  53093. * @param inputhHeight The height of the input panorama.
  53094. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  53095. * @return The cubemap data
  53096. */
  53097. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  53098. if (!float32Array) {
  53099. throw "ConvertPanoramaToCubemap: input cannot be null";
  53100. }
  53101. if (float32Array.length != inputWidth * inputHeight * 3) {
  53102. throw "ConvertPanoramaToCubemap: input size is wrong";
  53103. }
  53104. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  53105. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  53106. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  53107. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  53108. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  53109. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  53110. return {
  53111. front: textureFront,
  53112. back: textureBack,
  53113. left: textureLeft,
  53114. right: textureRight,
  53115. up: textureUp,
  53116. down: textureDown,
  53117. size: size
  53118. };
  53119. };
  53120. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  53121. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  53122. var textureArray = new Float32Array(buffer);
  53123. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  53124. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  53125. var dy = 1 / texSize;
  53126. var fy = 0;
  53127. for (var y = 0; y < texSize; y++) {
  53128. var xv1 = faceData[0];
  53129. var xv2 = faceData[2];
  53130. for (var x = 0; x < texSize; x++) {
  53131. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  53132. v.normalize();
  53133. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  53134. // 3 channels per pixels
  53135. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  53136. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  53137. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  53138. xv1 = xv1.add(rotDX1);
  53139. xv2 = xv2.add(rotDX2);
  53140. }
  53141. fy += dy;
  53142. }
  53143. return textureArray;
  53144. };
  53145. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  53146. var theta = Math.atan2(vDir.z, vDir.x);
  53147. var phi = Math.acos(vDir.y);
  53148. while (theta < -Math.PI)
  53149. theta += 2 * Math.PI;
  53150. while (theta > Math.PI)
  53151. theta -= 2 * Math.PI;
  53152. var dx = theta / Math.PI;
  53153. var dy = phi / Math.PI;
  53154. // recenter.
  53155. dx = dx * 0.5 + 0.5;
  53156. var px = Math.round(dx * inputWidth);
  53157. if (px < 0)
  53158. px = 0;
  53159. else if (px >= inputWidth)
  53160. px = inputWidth - 1;
  53161. var py = Math.round(dy * inputHeight);
  53162. if (py < 0)
  53163. py = 0;
  53164. else if (py >= inputHeight)
  53165. py = inputHeight - 1;
  53166. var inputY = (inputHeight - py - 1);
  53167. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  53168. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  53169. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  53170. return {
  53171. r: r,
  53172. g: g,
  53173. b: b
  53174. };
  53175. };
  53176. return PanoramaToCubeMapTools;
  53177. }());
  53178. PanoramaToCubeMapTools.FACE_FRONT = [
  53179. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53180. new BABYLON.Vector3(1.0, -1.0, -1.0),
  53181. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  53182. new BABYLON.Vector3(1.0, 1.0, -1.0)
  53183. ];
  53184. PanoramaToCubeMapTools.FACE_BACK = [
  53185. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53186. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53187. new BABYLON.Vector3(1.0, 1.0, 1.0),
  53188. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  53189. ];
  53190. PanoramaToCubeMapTools.FACE_RIGHT = [
  53191. new BABYLON.Vector3(1.0, -1.0, -1.0),
  53192. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53193. new BABYLON.Vector3(1.0, 1.0, -1.0),
  53194. new BABYLON.Vector3(1.0, 1.0, 1.0)
  53195. ];
  53196. PanoramaToCubeMapTools.FACE_LEFT = [
  53197. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53198. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53199. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  53200. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  53201. ];
  53202. PanoramaToCubeMapTools.FACE_DOWN = [
  53203. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  53204. new BABYLON.Vector3(1.0, 1.0, -1.0),
  53205. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  53206. new BABYLON.Vector3(1.0, 1.0, 1.0)
  53207. ];
  53208. PanoramaToCubeMapTools.FACE_UP = [
  53209. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53210. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53211. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53212. new BABYLON.Vector3(1.0, -1.0, -1.0)
  53213. ];
  53214. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  53215. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53216. })(BABYLON || (BABYLON = {}));
  53217. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  53218. var BABYLON;
  53219. (function (BABYLON) {
  53220. var Internals;
  53221. (function (Internals) {
  53222. ;
  53223. /**
  53224. * This groups tools to convert HDR texture to native colors array.
  53225. */
  53226. var HDRTools = (function () {
  53227. function HDRTools() {
  53228. }
  53229. HDRTools.Ldexp = function (mantissa, exponent) {
  53230. if (exponent > 1023) {
  53231. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  53232. }
  53233. if (exponent < -1074) {
  53234. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  53235. }
  53236. return mantissa * Math.pow(2, exponent);
  53237. };
  53238. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  53239. if (exponent > 0) {
  53240. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  53241. float32array[index + 0] = red * exponent;
  53242. float32array[index + 1] = green * exponent;
  53243. float32array[index + 2] = blue * exponent;
  53244. }
  53245. else {
  53246. float32array[index + 0] = 0;
  53247. float32array[index + 1] = 0;
  53248. float32array[index + 2] = 0;
  53249. }
  53250. };
  53251. HDRTools.readStringLine = function (uint8array, startIndex) {
  53252. var line = "";
  53253. var character = "";
  53254. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  53255. character = String.fromCharCode(uint8array[i]);
  53256. if (character == "\n") {
  53257. break;
  53258. }
  53259. line += character;
  53260. }
  53261. return line;
  53262. };
  53263. /**
  53264. * Reads header information from an RGBE texture stored in a native array.
  53265. * More information on this format are available here:
  53266. * https://en.wikipedia.org/wiki/RGBE_image_format
  53267. *
  53268. * @param uint8array The binary file stored in native array.
  53269. * @return The header information.
  53270. */
  53271. HDRTools.RGBE_ReadHeader = function (uint8array) {
  53272. var height = 0;
  53273. var width = 0;
  53274. var line = this.readStringLine(uint8array, 0);
  53275. if (line[0] != '#' || line[1] != '?') {
  53276. throw "Bad HDR Format.";
  53277. }
  53278. var endOfHeader = false;
  53279. var findFormat = false;
  53280. var lineIndex = 0;
  53281. do {
  53282. lineIndex += (line.length + 1);
  53283. line = this.readStringLine(uint8array, lineIndex);
  53284. if (line == "FORMAT=32-bit_rle_rgbe") {
  53285. findFormat = true;
  53286. }
  53287. else if (line.length == 0) {
  53288. endOfHeader = true;
  53289. }
  53290. } while (!endOfHeader);
  53291. if (!findFormat) {
  53292. throw "HDR Bad header format, unsupported FORMAT";
  53293. }
  53294. lineIndex += (line.length + 1);
  53295. line = this.readStringLine(uint8array, lineIndex);
  53296. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  53297. var match = sizeRegexp.exec(line);
  53298. // TODO. Support +Y and -X if needed.
  53299. if (match.length < 3) {
  53300. throw "HDR Bad header format, no size";
  53301. }
  53302. width = parseInt(match[2]);
  53303. height = parseInt(match[1]);
  53304. if (width < 8 || width > 0x7fff) {
  53305. throw "HDR Bad header format, unsupported size";
  53306. }
  53307. lineIndex += (line.length + 1);
  53308. return {
  53309. height: height,
  53310. width: width,
  53311. dataPosition: lineIndex
  53312. };
  53313. };
  53314. /**
  53315. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  53316. * This RGBE texture needs to store the information as a panorama.
  53317. *
  53318. * More information on this format are available here:
  53319. * https://en.wikipedia.org/wiki/RGBE_image_format
  53320. *
  53321. * @param buffer The binary file stored in an array buffer.
  53322. * @param size The expected size of the extracted cubemap.
  53323. * @return The Cube Map information.
  53324. */
  53325. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  53326. var uint8array = new Uint8Array(buffer);
  53327. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  53328. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  53329. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  53330. return cubeMapData;
  53331. };
  53332. /**
  53333. * Returns the pixels data extracted from an RGBE texture.
  53334. * This pixels will be stored left to right up to down in the R G B order in one array.
  53335. *
  53336. * More information on this format are available here:
  53337. * https://en.wikipedia.org/wiki/RGBE_image_format
  53338. *
  53339. * @param uint8array The binary file stored in an array buffer.
  53340. * @param hdrInfo The header information of the file.
  53341. * @return The pixels data in RGB right to left up to down order.
  53342. */
  53343. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  53344. // Keep for multi format supports.
  53345. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  53346. };
  53347. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  53348. var num_scanlines = hdrInfo.height;
  53349. var scanline_width = hdrInfo.width;
  53350. var a, b, c, d, count;
  53351. var dataIndex = hdrInfo.dataPosition;
  53352. var index = 0, endIndex = 0, i = 0;
  53353. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  53354. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  53355. // 3 channels of 4 bytes per pixel in float.
  53356. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  53357. var resultArray = new Float32Array(resultBuffer);
  53358. // read in each successive scanline
  53359. while (num_scanlines > 0) {
  53360. a = uint8array[dataIndex++];
  53361. b = uint8array[dataIndex++];
  53362. c = uint8array[dataIndex++];
  53363. d = uint8array[dataIndex++];
  53364. if (a != 2 || b != 2 || (c & 0x80)) {
  53365. // this file is not run length encoded
  53366. throw "HDR Bad header format, not RLE";
  53367. }
  53368. if (((c << 8) | d) != scanline_width) {
  53369. throw "HDR Bad header format, wrong scan line width";
  53370. }
  53371. index = 0;
  53372. // read each of the four channels for the scanline into the buffer
  53373. for (i = 0; i < 4; i++) {
  53374. endIndex = (i + 1) * scanline_width;
  53375. while (index < endIndex) {
  53376. a = uint8array[dataIndex++];
  53377. b = uint8array[dataIndex++];
  53378. if (a > 128) {
  53379. // a run of the same value
  53380. count = a - 128;
  53381. if ((count == 0) || (count > endIndex - index)) {
  53382. throw "HDR Bad Format, bad scanline data (run)";
  53383. }
  53384. while (count-- > 0) {
  53385. scanLineArray[index++] = b;
  53386. }
  53387. }
  53388. else {
  53389. // a non-run
  53390. count = a;
  53391. if ((count == 0) || (count > endIndex - index)) {
  53392. throw "HDR Bad Format, bad scanline data (non-run)";
  53393. }
  53394. scanLineArray[index++] = b;
  53395. if (--count > 0) {
  53396. for (var j = 0; j < count; j++) {
  53397. scanLineArray[index++] = uint8array[dataIndex++];
  53398. }
  53399. }
  53400. }
  53401. }
  53402. }
  53403. // now convert data from buffer into floats
  53404. for (i = 0; i < scanline_width; i++) {
  53405. a = scanLineArray[i];
  53406. b = scanLineArray[i + scanline_width];
  53407. c = scanLineArray[i + 2 * scanline_width];
  53408. d = scanLineArray[i + 3 * scanline_width];
  53409. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  53410. }
  53411. num_scanlines--;
  53412. }
  53413. return resultArray;
  53414. };
  53415. return HDRTools;
  53416. }());
  53417. Internals.HDRTools = HDRTools;
  53418. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53419. })(BABYLON || (BABYLON = {}));
  53420. //# sourceMappingURL=babylon.hdr.js.map
  53421. //_______________________________________________________________
  53422. // Extracted from CubeMapGen:
  53423. // https://code.google.com/archive/p/cubemapgen/
  53424. //
  53425. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  53426. //_______________________________________________________________
  53427. var BABYLON;
  53428. (function (BABYLON) {
  53429. var Internals;
  53430. (function (Internals) {
  53431. /**
  53432. * The bounding box information used during the conversion process.
  53433. */
  53434. var CMGBoundinBox = (function () {
  53435. function CMGBoundinBox() {
  53436. this.min = new BABYLON.Vector3(0, 0, 0);
  53437. this.max = new BABYLON.Vector3(0, 0, 0);
  53438. this.clear();
  53439. }
  53440. CMGBoundinBox.prototype.clear = function () {
  53441. this.min.x = CMGBoundinBox.MAX;
  53442. this.min.y = CMGBoundinBox.MAX;
  53443. this.min.z = CMGBoundinBox.MAX;
  53444. this.max.x = CMGBoundinBox.MIN;
  53445. this.max.y = CMGBoundinBox.MIN;
  53446. this.max.z = CMGBoundinBox.MIN;
  53447. };
  53448. CMGBoundinBox.prototype.augment = function (x, y, z) {
  53449. this.min.x = Math.min(this.min.x, x);
  53450. this.min.y = Math.min(this.min.y, y);
  53451. this.min.z = Math.min(this.min.z, z);
  53452. this.max.x = Math.max(this.max.x, x);
  53453. this.max.y = Math.max(this.max.y, y);
  53454. this.max.z = Math.max(this.max.z, z);
  53455. };
  53456. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  53457. this.min.x = Math.max(this.min.x, x);
  53458. this.min.y = Math.max(this.min.y, y);
  53459. this.min.z = Math.max(this.min.z, z);
  53460. };
  53461. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  53462. this.max.x = Math.min(this.max.x, x);
  53463. this.max.y = Math.min(this.max.y, y);
  53464. this.max.z = Math.min(this.max.z, z);
  53465. };
  53466. CMGBoundinBox.prototype.empty = function () {
  53467. if ((this.min.x > this.max.y) ||
  53468. (this.min.y > this.max.y) ||
  53469. (this.min.z > this.max.y)) {
  53470. return true;
  53471. }
  53472. else {
  53473. return false;
  53474. }
  53475. };
  53476. return CMGBoundinBox;
  53477. }());
  53478. CMGBoundinBox.MAX = Number.MAX_VALUE;
  53479. CMGBoundinBox.MIN = Number.MIN_VALUE;
  53480. /**
  53481. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  53482. * required by the glossinees of a material.
  53483. *
  53484. * This only supports the cosine drop power as well as Warp fixup generation method.
  53485. *
  53486. * This is using the process from CubeMapGen described here:
  53487. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  53488. */
  53489. var PMREMGenerator = (function () {
  53490. /**
  53491. * Constructor of the generator.
  53492. *
  53493. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  53494. * @param inputSize The size of the cubemap faces
  53495. * @param outputSize The size of the output cubemap faces
  53496. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  53497. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  53498. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  53499. * @param specularPower The max specular level of the desired cubemap
  53500. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  53501. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  53502. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  53503. */
  53504. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  53505. this.input = input;
  53506. this.inputSize = inputSize;
  53507. this.outputSize = outputSize;
  53508. this.maxNumMipLevels = maxNumMipLevels;
  53509. this.numChannels = numChannels;
  53510. this.isFloat = isFloat;
  53511. this.specularPower = specularPower;
  53512. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  53513. this.excludeBase = excludeBase;
  53514. this.fixup = fixup;
  53515. this._outputSurface = [];
  53516. this._numMipLevels = 0;
  53517. }
  53518. /**
  53519. * Launches the filter process and return the result.
  53520. *
  53521. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  53522. */
  53523. PMREMGenerator.prototype.filterCubeMap = function () {
  53524. // Init cubemap processor
  53525. this.init();
  53526. // Filters the cubemap
  53527. this.filterCubeMapMipChain();
  53528. // Returns the filtered mips.
  53529. return this._outputSurface;
  53530. };
  53531. PMREMGenerator.prototype.init = function () {
  53532. var i;
  53533. var j;
  53534. var mipLevelSize;
  53535. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  53536. if (this.maxNumMipLevels == 0) {
  53537. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  53538. }
  53539. //first miplevel size
  53540. mipLevelSize = this.outputSize;
  53541. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  53542. for (j = 0; j < this.maxNumMipLevels; j++) {
  53543. this._outputSurface.length++;
  53544. this._outputSurface[j] = [];
  53545. //Iterate over faces for output images
  53546. for (i = 0; i < 6; i++) {
  53547. this._outputSurface[j].length++;
  53548. // Initializes a new array for the output.
  53549. if (this.isFloat) {
  53550. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  53551. }
  53552. else {
  53553. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  53554. }
  53555. }
  53556. //next mip level is half size
  53557. mipLevelSize >>= 1;
  53558. this._numMipLevels++;
  53559. //terminate if mip chain becomes too small
  53560. if (mipLevelSize == 0) {
  53561. this.maxNumMipLevels = j;
  53562. return;
  53563. }
  53564. }
  53565. };
  53566. //--------------------------------------------------------------------------------------
  53567. //Cube map filtering and mip chain generation.
  53568. // the cube map filtereing is specified using a number of parameters:
  53569. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  53570. // indicates the region of the hemisphere to filter over for each tap.
  53571. //
  53572. // Note that the top mip level is also a filtered version of the original input images
  53573. // as well in order to create mip chains for diffuse environment illumination.
  53574. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  53575. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  53576. //
  53577. // Then the mip angle used to genreate the next level of the mip chain from the first level
  53578. // is a_InitialMipAngle
  53579. //
  53580. // The angle for the subsequent levels of the mip chain are specified by their parents
  53581. // filtering angle and a per-level scale and bias
  53582. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  53583. //
  53584. //--------------------------------------------------------------------------------------
  53585. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  53586. // First, take count of the lighting model to modify SpecularPower
  53587. // 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;
  53588. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  53589. //Cone angle start (for generating subsequent mip levels)
  53590. var currentSpecularPower = this.specularPower;
  53591. //Build filter lookup tables based on the source miplevel size
  53592. this.precomputeFilterLookupTables(this.inputSize);
  53593. // Note that we need to filter the first level before generating mipmap
  53594. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  53595. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  53596. // TODO : Write a function to copy and scale the base mipmap in output
  53597. // I am just lazy here and just put a high specular power value, and do some if.
  53598. if (this.excludeBase && (levelIndex == 0)) {
  53599. // 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).
  53600. currentSpecularPower = 100000.0;
  53601. }
  53602. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  53603. var srcCubeImage = this.input;
  53604. var dstCubeImage = this._outputSurface[levelIndex];
  53605. var dstSize = this.outputSize >> levelIndex;
  53606. // Compute required angle.
  53607. var angle = this.getBaseFilterAngle(currentSpecularPower);
  53608. // filter cube surfaces
  53609. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  53610. // fix seams
  53611. if (this.fixup) {
  53612. this.fixupCubeEdges(dstCubeImage, dstSize);
  53613. }
  53614. // Decrease the specular power to generate the mipmap chain
  53615. // TODO : Use another method for Exclude (see first comment at start of the function
  53616. if (this.excludeBase && (levelIndex == 0)) {
  53617. currentSpecularPower = this.specularPower;
  53618. }
  53619. currentSpecularPower *= this.cosinePowerDropPerMip;
  53620. }
  53621. };
  53622. //--------------------------------------------------------------------------------------
  53623. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  53624. // It allow to optimize the texel to access base on the specular power.
  53625. //--------------------------------------------------------------------------------------
  53626. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  53627. // We want to find the alpha such that:
  53628. // cos(alpha)^cosinePower = epsilon
  53629. // That's: acos(epsilon^(1/cosinePower))
  53630. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  53631. var angle = 180.0;
  53632. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  53633. angle *= 180.0 / Math.PI; // Convert to degree
  53634. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  53635. return angle;
  53636. };
  53637. //--------------------------------------------------------------------------------------
  53638. //Builds the following lookup tables prior to filtering:
  53639. // -normalizer cube map
  53640. // -tap weight lookup table
  53641. //
  53642. //--------------------------------------------------------------------------------------
  53643. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  53644. var srcTexelAngle;
  53645. var iCubeFace;
  53646. //clear pre-existing normalizer cube map
  53647. this._normCubeMap = [];
  53648. //Normalized vectors per cubeface and per-texel solid angle
  53649. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  53650. };
  53651. //--------------------------------------------------------------------------------------
  53652. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  53653. //
  53654. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  53655. //
  53656. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  53657. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  53658. // below
  53659. //--------------------------------------------------------------------------------------
  53660. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  53661. var iCubeFace;
  53662. var u;
  53663. var v;
  53664. //iterate over cube faces
  53665. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  53666. //First three channels for norm cube, and last channel for solid angle
  53667. this._normCubeMap.push(new Float32Array(size * size * 4));
  53668. //fast texture walk, build normalizer cube map
  53669. var facesData = this.input[iCubeFace];
  53670. for (v = 0; v < size; v++) {
  53671. for (u = 0; u < size; u++) {
  53672. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  53673. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  53674. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  53675. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  53676. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  53677. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  53678. }
  53679. }
  53680. }
  53681. };
  53682. //--------------------------------------------------------------------------------------
  53683. // Convert cubemap face texel coordinates and face idx to 3D vector
  53684. // note the U and V coords are integer coords and range from 0 to size-1
  53685. // this routine can be used to generate a normalizer cube map
  53686. //--------------------------------------------------------------------------------------
  53687. // SL BEGIN
  53688. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  53689. var nvcU;
  53690. var nvcV;
  53691. var tempVec;
  53692. // Change from original AMD code
  53693. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  53694. // + 0.5f is for texel center addressing
  53695. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  53696. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  53697. // warp fixup
  53698. if (fixup && size > 1) {
  53699. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  53700. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  53701. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  53702. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  53703. }
  53704. // Get current vector
  53705. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  53706. // U contribution
  53707. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  53708. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  53709. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  53710. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  53711. // V contribution and Sum
  53712. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  53713. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  53714. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  53715. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  53716. //add face axis
  53717. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  53718. PMREMGenerator._vectorTemp.x += faceAxis[0];
  53719. PMREMGenerator._vectorTemp.y += faceAxis[1];
  53720. PMREMGenerator._vectorTemp.z += faceAxis[2];
  53721. //normalize vector
  53722. PMREMGenerator._vectorTemp.normalize();
  53723. return PMREMGenerator._vectorTemp;
  53724. };
  53725. //--------------------------------------------------------------------------------------
  53726. // Convert 3D vector to cubemap face texel coordinates and face idx
  53727. // note the U and V coords are integer coords and range from 0 to size-1
  53728. // this routine can be used to generate a normalizer cube map
  53729. //
  53730. // returns face IDX and texel coords
  53731. //--------------------------------------------------------------------------------------
  53732. // SL BEGIN
  53733. /*
  53734. Mapping Texture Coordinates to Cube Map Faces
  53735. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  53736. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  53737. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  53738. map arrangement in Pixar's RenderMan package.
  53739. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  53740. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  53741. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  53742. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  53743. the major axis direction). The target column in the table below explains how the major axis direction
  53744. maps to the 2D image of a particular cube map target.
  53745. major axis
  53746. direction target sc tc ma
  53747. ---------- --------------------------------- --- --- ---
  53748. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  53749. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  53750. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  53751. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  53752. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  53753. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  53754. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  53755. an updated (s,t) is calculated as follows
  53756. s = ( sc/|ma| + 1 ) / 2
  53757. t = ( tc/|ma| + 1 ) / 2
  53758. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  53759. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  53760. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  53761. */
  53762. // Note this method return U and V in range from 0 to size-1
  53763. // SL END
  53764. // Store the information in vector3 for convenience (faceindex, u, v)
  53765. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  53766. var maxCoord;
  53767. var faceIdx;
  53768. //absolute value 3
  53769. var absX = Math.abs(x);
  53770. var absY = Math.abs(y);
  53771. var absZ = Math.abs(z);
  53772. if (absX >= absY && absX >= absZ) {
  53773. maxCoord = absX;
  53774. if (x >= 0) {
  53775. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  53776. }
  53777. else {
  53778. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  53779. }
  53780. }
  53781. else if (absY >= absX && absY >= absZ) {
  53782. maxCoord = absY;
  53783. if (y >= 0) {
  53784. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  53785. }
  53786. else {
  53787. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  53788. }
  53789. }
  53790. else {
  53791. maxCoord = absZ;
  53792. if (z >= 0) {
  53793. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  53794. }
  53795. else {
  53796. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  53797. }
  53798. }
  53799. //divide through by max coord so face vector lies on cube face
  53800. var scale = 1 / maxCoord;
  53801. x *= scale;
  53802. y *= scale;
  53803. z *= scale;
  53804. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  53805. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  53806. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  53807. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  53808. // Modify original AMD code to return value from 0 to Size - 1
  53809. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  53810. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  53811. PMREMGenerator._vectorTemp.x = faceIdx;
  53812. PMREMGenerator._vectorTemp.y = u;
  53813. PMREMGenerator._vectorTemp.z = v;
  53814. return PMREMGenerator._vectorTemp;
  53815. };
  53816. //--------------------------------------------------------------------------------------
  53817. //Original code from Ignacio CastaÒo
  53818. // This formula is from Manne ÷hrstrˆm's thesis.
  53819. // Take two coordiantes in the range [-1, 1] that define a portion of a
  53820. // cube face and return the area of the projection of that portion on the
  53821. // surface of the sphere.
  53822. //--------------------------------------------------------------------------------------
  53823. PMREMGenerator.prototype.areaElement = function (x, y) {
  53824. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  53825. };
  53826. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  53827. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  53828. // (+ 0.5f is for texel center addressing)
  53829. u = (2.0 * (u + 0.5) / size) - 1.0;
  53830. v = (2.0 * (v + 0.5) / size) - 1.0;
  53831. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  53832. var invResolution = 1.0 / size;
  53833. // U and V are the -1..1 texture coordinate on the current face.
  53834. // Get projected area for this texel
  53835. var x0 = u - invResolution;
  53836. var y0 = v - invResolution;
  53837. var x1 = u + invResolution;
  53838. var y1 = v + invResolution;
  53839. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  53840. return solidAngle;
  53841. };
  53842. //--------------------------------------------------------------------------------------
  53843. //The key to the speed of these filtering routines is to quickly define a per-face
  53844. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  53845. // Later these pixels are selectively processed based on their dot products to see if
  53846. // they reside within the filtering cone.
  53847. //
  53848. //This is done by computing the smallest per-texel angle to get a conservative estimate
  53849. // of the number of texels needed to be covered in width and height order to filter the
  53850. // region. the bounding box for the center taps face is defined first, and if the
  53851. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  53852. // defined next
  53853. //--------------------------------------------------------------------------------------
  53854. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  53855. // note that pixels within these regions may be rejected
  53856. // based on the anlge
  53857. var iCubeFace;
  53858. var u;
  53859. var v;
  53860. // bounding box per face to specify region to process
  53861. var filterExtents = [];
  53862. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  53863. filterExtents.push(new CMGBoundinBox());
  53864. }
  53865. // min angle a src texel can cover (in degrees)
  53866. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  53867. // angle about center tap to define filter cone
  53868. // filter angle is 1/2 the cone angle
  53869. var filterAngle = filterConeAngle / 2.0;
  53870. //ensure filter angle is larger than a texel
  53871. if (filterAngle < srcTexelAngle) {
  53872. filterAngle = srcTexelAngle;
  53873. }
  53874. //ensure filter cone is always smaller than the hemisphere
  53875. if (filterAngle > 90.0) {
  53876. filterAngle = 90.0;
  53877. }
  53878. // the maximum number of texels in 1D the filter cone angle will cover
  53879. // used to determine bounding box size for filter extents
  53880. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  53881. // ensure conservative region always covers at least one texel
  53882. if (filterSize < 1) {
  53883. filterSize = 1;
  53884. }
  53885. // dotProdThresh threshold based on cone angle to determine whether or not taps
  53886. // reside within the cone angle
  53887. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  53888. // process required faces
  53889. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  53890. //iterate over dst cube map face texel
  53891. for (v = 0; v < dstSize; v++) {
  53892. for (u = 0; u < dstSize; u++) {
  53893. //get center tap direction
  53894. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  53895. //clear old per-face filter extents
  53896. this.clearFilterExtents(filterExtents);
  53897. //define per-face filter extents
  53898. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  53899. //perform filtering of src faces using filter extents
  53900. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  53901. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  53902. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  53903. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  53904. }
  53905. }
  53906. }
  53907. };
  53908. //--------------------------------------------------------------------------------------
  53909. //Clear filter extents for the 6 cube map faces
  53910. //--------------------------------------------------------------------------------------
  53911. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  53912. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  53913. filterExtents[iCubeFaces].clear();
  53914. }
  53915. };
  53916. //--------------------------------------------------------------------------------------
  53917. //Define per-face bounding box filter extents
  53918. //
  53919. // These define conservative texel regions in each of the faces the filter can possibly
  53920. // process. When the pixels in the regions are actually processed, the dot product
  53921. // between the tap vector and the center tap vector is used to determine the weight of
  53922. // the tap and whether or not the tap is within the cone.
  53923. //
  53924. //--------------------------------------------------------------------------------------
  53925. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  53926. //neighboring face and bleed over amount, and width of BBOX for
  53927. // left, right, top, and bottom edges of this face
  53928. var bleedOverAmount = [0, 0, 0, 0];
  53929. var bleedOverBBoxMin = [0, 0, 0, 0];
  53930. var bleedOverBBoxMax = [0, 0, 0, 0];
  53931. var neighborFace;
  53932. var neighborEdge;
  53933. var oppositeFaceIdx;
  53934. //get face idx, and u, v info from center tap dir
  53935. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  53936. var faceIdx = result.x;
  53937. var u = result.y;
  53938. var v = result.z;
  53939. //define bbox size within face
  53940. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  53941. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  53942. filterExtents[faceIdx].clampMin(0, 0, 0);
  53943. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  53944. //u and v extent in face corresponding to center tap
  53945. var minU = filterExtents[faceIdx].min.x;
  53946. var minV = filterExtents[faceIdx].min.y;
  53947. var maxU = filterExtents[faceIdx].max.x;
  53948. var maxV = filterExtents[faceIdx].max.y;
  53949. //bleed over amounts for face across u=0 edge (left)
  53950. bleedOverAmount[0] = (bboxSize - u);
  53951. bleedOverBBoxMin[0] = minV;
  53952. bleedOverBBoxMax[0] = maxV;
  53953. //bleed over amounts for face across u=1 edge (right)
  53954. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  53955. bleedOverBBoxMin[1] = minV;
  53956. bleedOverBBoxMax[1] = maxV;
  53957. //bleed over to face across v=0 edge (up)
  53958. bleedOverAmount[2] = (bboxSize - v);
  53959. bleedOverBBoxMin[2] = minU;
  53960. bleedOverBBoxMax[2] = maxU;
  53961. //bleed over to face across v=1 edge (down)
  53962. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  53963. bleedOverBBoxMin[3] = minU;
  53964. bleedOverBBoxMax[3] = maxU;
  53965. //compute bleed over regions in neighboring faces
  53966. for (var i = 0; i < 4; i++) {
  53967. if (bleedOverAmount[i] > 0) {
  53968. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  53969. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  53970. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  53971. // be flipped: the cases are
  53972. // if a left edge mates with a left or bottom edge on the neighbor
  53973. // if a top edge mates with a top or right edge on the neighbor
  53974. // if a right edge mates with a right or top edge on the neighbor
  53975. // if a bottom edge mates with a bottom or left edge on the neighbor
  53976. //Seeing as the edges are enumerated as follows
  53977. // left =0
  53978. // right =1
  53979. // top =2
  53980. // bottom =3
  53981. //
  53982. // so if the edge enums are the same, or the sum of the enums == 3,
  53983. // the bbox needs to be flipped
  53984. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  53985. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  53986. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  53987. }
  53988. //The way the bounding box is extended onto the neighboring face
  53989. // depends on which edge of neighboring face abuts with this one
  53990. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  53991. case PMREMGenerator.CP_EDGE_LEFT:
  53992. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  53993. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  53994. break;
  53995. case PMREMGenerator.CP_EDGE_RIGHT:
  53996. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  53997. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  53998. break;
  53999. case PMREMGenerator.CP_EDGE_TOP:
  54000. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  54001. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  54002. break;
  54003. case PMREMGenerator.CP_EDGE_BOTTOM:
  54004. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  54005. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  54006. break;
  54007. }
  54008. //clamp filter extents in non-center tap faces to remain within surface
  54009. filterExtents[neighborFace].clampMin(0, 0, 0);
  54010. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  54011. }
  54012. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  54013. // from the center tap face, then process the opposite face entirely for now.
  54014. //Note that the cases in which this happens, what usually happens is that
  54015. // more than one edge bleeds onto the opposite face, and the bounding box
  54016. // encompasses the entire cube map face.
  54017. if (bleedOverAmount[i] > srcSize) {
  54018. //determine opposite face
  54019. switch (faceIdx) {
  54020. case PMREMGenerator.CP_FACE_X_POS:
  54021. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  54022. break;
  54023. case PMREMGenerator.CP_FACE_X_NEG:
  54024. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  54025. break;
  54026. case PMREMGenerator.CP_FACE_Y_POS:
  54027. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  54028. break;
  54029. case PMREMGenerator.CP_FACE_Y_NEG:
  54030. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  54031. break;
  54032. case PMREMGenerator.CP_FACE_Z_POS:
  54033. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  54034. break;
  54035. case PMREMGenerator.CP_FACE_Z_NEG:
  54036. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  54037. break;
  54038. default:
  54039. break;
  54040. }
  54041. //just encompass entire face for now
  54042. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  54043. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  54044. }
  54045. }
  54046. };
  54047. //--------------------------------------------------------------------------------------
  54048. //ProcessFilterExtents
  54049. // Process bounding box in each cube face
  54050. //
  54051. //--------------------------------------------------------------------------------------
  54052. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  54053. //accumulators are 64-bit floats in order to have the precision needed
  54054. // over a summation of a large number of pixels
  54055. var dstAccum = [0, 0, 0, 0];
  54056. var weightAccum = 0;
  54057. var k = 0;
  54058. var nSrcChannels = this.numChannels;
  54059. // norm cube map and srcCubeMap have same face width
  54060. var faceWidth = srcSize;
  54061. //amount to add to pointer to move to next scanline in images
  54062. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  54063. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  54064. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  54065. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  54066. // iterate over cubefaces
  54067. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  54068. //if bbox is non empty
  54069. if (!filterExtents[iFaceIdx].empty()) {
  54070. var uStart = filterExtents[iFaceIdx].min.x;
  54071. var vStart = filterExtents[iFaceIdx].min.y;
  54072. var uEnd = filterExtents[iFaceIdx].max.x;
  54073. var vEnd = filterExtents[iFaceIdx].max.y;
  54074. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  54075. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  54076. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  54077. for (var v = vStart; v <= vEnd; v++) {
  54078. var normCubeRowWalk = 0;
  54079. var srcCubeRowWalk = 0;
  54080. for (var u = uStart; u <= uEnd; u++) {
  54081. //pointer to direction in cube map associated with texel
  54082. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  54083. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  54084. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  54085. //check dot product to see if texel is within cone
  54086. var tapDotProd = texelVectX * centerTapDir.x +
  54087. texelVectY * centerTapDir.y +
  54088. texelVectZ * centerTapDir.z;
  54089. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  54090. //solid angle stored in 4th channel of normalizer/solid angle cube map
  54091. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  54092. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  54093. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  54094. // so just adding one to specularpower do the trick.
  54095. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  54096. //iterate over channels
  54097. for (k = 0; k < nSrcChannels; k++) {
  54098. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  54099. srcCubeRowWalk++;
  54100. }
  54101. weightAccum += weight; //accumulate weight
  54102. }
  54103. else {
  54104. //step across source pixel
  54105. srcCubeRowWalk += nSrcChannels;
  54106. }
  54107. normCubeRowWalk += 4; // 4 channels per norm cube map.
  54108. }
  54109. startIndexNormCubeMap += normCubePitch;
  54110. startIndexSrcCubeMap += srcCubePitch;
  54111. }
  54112. }
  54113. }
  54114. //divide through by weights if weight is non zero
  54115. if (weightAccum != 0.0) {
  54116. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  54117. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  54118. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  54119. if (this.numChannels > 3) {
  54120. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  54121. }
  54122. }
  54123. else {
  54124. // otherwise sample nearest
  54125. // get face idx and u, v texel coordinate in face
  54126. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  54127. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  54128. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  54129. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  54130. if (this.numChannels > 3) {
  54131. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  54132. }
  54133. }
  54134. return PMREMGenerator._vectorTemp;
  54135. };
  54136. //--------------------------------------------------------------------------------------
  54137. // Fixup cube edges
  54138. //
  54139. // average texels on cube map faces across the edges
  54140. // WARP/BENT Method Only.
  54141. //--------------------------------------------------------------------------------------
  54142. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  54143. var k;
  54144. var j;
  54145. var i;
  54146. var iFace;
  54147. var iCorner = 0;
  54148. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  54149. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  54150. // note that if functionality to filter across the three texels for each corner, then
  54151. //indexed by corner and face idx. the array contains the face the start points belongs to.
  54152. var cornerPtr = [
  54153. [[], [], []],
  54154. [[], [], []],
  54155. [[], [], []],
  54156. [[], [], []],
  54157. [[], [], []],
  54158. [[], [], []],
  54159. [[], [], []],
  54160. [[], [], []]
  54161. ];
  54162. //if there is no fixup, or fixup width = 0, do nothing
  54163. if (cubeMapSize < 1) {
  54164. return;
  54165. }
  54166. //special case 1x1 cubemap, average face colors
  54167. if (cubeMapSize == 1) {
  54168. //iterate over channels
  54169. for (k = 0; k < this.numChannels; k++) {
  54170. var accum = 0.0;
  54171. //iterate over faces to accumulate face colors
  54172. for (iFace = 0; iFace < 6; iFace++) {
  54173. accum += cubeMap[iFace][k];
  54174. }
  54175. //compute average over 6 face colors
  54176. accum /= 6.0;
  54177. //iterate over faces to distribute face colors
  54178. for (iFace = 0; iFace < 6; iFace++) {
  54179. cubeMap[iFace][k] = accum;
  54180. }
  54181. }
  54182. return;
  54183. }
  54184. //iterate over faces to collect list of corner texel pointers
  54185. for (iFace = 0; iFace < 6; iFace++) {
  54186. //the 4 corner pointers for this face
  54187. faceCornerStartIndicies[0] = [iFace, 0];
  54188. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  54189. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  54190. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  54191. //iterate over face corners to collect cube corner pointers
  54192. for (iCorner = 0; iCorner < 4; iCorner++) {
  54193. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  54194. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  54195. cornerNumPtrs[corner]++;
  54196. }
  54197. }
  54198. //iterate over corners to average across corner tap values
  54199. for (iCorner = 0; iCorner < 8; iCorner++) {
  54200. for (k = 0; k < this.numChannels; k++) {
  54201. var cornerTapAccum = 0.0;
  54202. //iterate over corner texels and average results
  54203. for (i = 0; i < 3; i++) {
  54204. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  54205. }
  54206. //divide by 3 to compute average of corner tap values
  54207. cornerTapAccum *= (1.0 / 3.0);
  54208. //iterate over corner texels and average results
  54209. for (i = 0; i < 3; i++) {
  54210. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  54211. }
  54212. }
  54213. }
  54214. //iterate over the twelve edges of the cube to average across edges
  54215. for (i = 0; i < 12; i++) {
  54216. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  54217. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  54218. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  54219. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  54220. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  54221. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  54222. var edgeWalk = 0;
  54223. var neighborEdgeWalk = 0;
  54224. //Determine walking pointers based on edge type
  54225. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  54226. switch (edge) {
  54227. case PMREMGenerator.CP_EDGE_LEFT:
  54228. // no change to faceEdgeStartPtr
  54229. edgeWalk = this.numChannels * cubeMapSize;
  54230. break;
  54231. case PMREMGenerator.CP_EDGE_RIGHT:
  54232. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54233. edgeWalk = this.numChannels * cubeMapSize;
  54234. break;
  54235. case PMREMGenerator.CP_EDGE_TOP:
  54236. // no change to faceEdgeStartPtr
  54237. edgeWalk = this.numChannels;
  54238. break;
  54239. case PMREMGenerator.CP_EDGE_BOTTOM:
  54240. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  54241. edgeWalk = this.numChannels;
  54242. break;
  54243. }
  54244. //For certain types of edge abutments, the neighbor edge walk needs to
  54245. // be flipped: the cases are
  54246. // if a left edge mates with a left or bottom edge on the neighbor
  54247. // if a top edge mates with a top or right edge on the neighbor
  54248. // if a right edge mates with a right or top edge on the neighbor
  54249. // if a bottom edge mates with a bottom or left edge on the neighbor
  54250. //Seeing as the edges are enumerated as follows
  54251. // left =0
  54252. // right =1
  54253. // top =2
  54254. // bottom =3
  54255. //
  54256. //If the edge enums are the same, or the sum of the enums == 3,
  54257. // the neighbor edge walk needs to be flipped
  54258. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  54259. switch (neighborEdge) {
  54260. case PMREMGenerator.CP_EDGE_LEFT:
  54261. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  54262. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  54263. break;
  54264. case PMREMGenerator.CP_EDGE_RIGHT:
  54265. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  54266. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  54267. break;
  54268. case PMREMGenerator.CP_EDGE_TOP:
  54269. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54270. neighborEdgeWalk = -this.numChannels;
  54271. break;
  54272. case PMREMGenerator.CP_EDGE_BOTTOM:
  54273. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  54274. neighborEdgeWalk = -this.numChannels;
  54275. break;
  54276. }
  54277. }
  54278. else {
  54279. //swapped direction neighbor edge walk
  54280. switch (neighborEdge) {
  54281. case PMREMGenerator.CP_EDGE_LEFT:
  54282. //no change to neighborEdgeStartPtr for this case since it points
  54283. // to the upper left corner already
  54284. neighborEdgeWalk = this.numChannels * cubeMapSize;
  54285. break;
  54286. case PMREMGenerator.CP_EDGE_RIGHT:
  54287. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54288. neighborEdgeWalk = this.numChannels * cubeMapSize;
  54289. break;
  54290. case PMREMGenerator.CP_EDGE_TOP:
  54291. //no change to neighborEdgeStartPtr for this case since it points
  54292. // to the upper left corner already
  54293. neighborEdgeWalk = this.numChannels;
  54294. break;
  54295. case PMREMGenerator.CP_EDGE_BOTTOM:
  54296. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  54297. neighborEdgeWalk = this.numChannels;
  54298. break;
  54299. }
  54300. }
  54301. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  54302. //nearby neighborhood
  54303. //step ahead one texel on edge
  54304. edgeStartIndex += edgeWalk;
  54305. neighborEdgeStartIndex += neighborEdgeWalk;
  54306. // note that this loop does not process the corner texels, since they have already been
  54307. // averaged across faces across earlier
  54308. for (j = 1; j < (cubeMapSize - 1); j++) {
  54309. //for each set of taps along edge, average them
  54310. // and rewrite the results into the edges
  54311. for (k = 0; k < this.numChannels; k++) {
  54312. var edgeTap = cubeMap[face][edgeStartIndex + k];
  54313. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  54314. //compute average of tap intensity values
  54315. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  54316. //propagate average of taps to edge taps
  54317. cubeMap[face][edgeStartIndex + k] = avgTap;
  54318. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  54319. }
  54320. edgeStartIndex += edgeWalk;
  54321. neighborEdgeStartIndex += neighborEdgeWalk;
  54322. }
  54323. }
  54324. };
  54325. return PMREMGenerator;
  54326. }());
  54327. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  54328. PMREMGenerator.CP_UDIR = 0;
  54329. PMREMGenerator.CP_VDIR = 1;
  54330. PMREMGenerator.CP_FACEAXIS = 2;
  54331. //used to index cube faces
  54332. PMREMGenerator.CP_FACE_X_POS = 0;
  54333. PMREMGenerator.CP_FACE_X_NEG = 1;
  54334. PMREMGenerator.CP_FACE_Y_POS = 2;
  54335. PMREMGenerator.CP_FACE_Y_NEG = 3;
  54336. PMREMGenerator.CP_FACE_Z_POS = 4;
  54337. PMREMGenerator.CP_FACE_Z_NEG = 5;
  54338. //used to index image edges
  54339. // NOTE.. the actual number corresponding to the edge is important
  54340. // do not change these, or the code will break
  54341. //
  54342. // CP_EDGE_LEFT is u = 0
  54343. // CP_EDGE_RIGHT is u = width-1
  54344. // CP_EDGE_TOP is v = 0
  54345. // CP_EDGE_BOTTOM is v = height-1
  54346. PMREMGenerator.CP_EDGE_LEFT = 0;
  54347. PMREMGenerator.CP_EDGE_RIGHT = 1;
  54348. PMREMGenerator.CP_EDGE_TOP = 2;
  54349. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  54350. //corners of CUBE map (P or N specifys if it corresponds to the
  54351. // positive or negative direction each of X, Y, and Z
  54352. PMREMGenerator.CP_CORNER_NNN = 0;
  54353. PMREMGenerator.CP_CORNER_NNP = 1;
  54354. PMREMGenerator.CP_CORNER_NPN = 2;
  54355. PMREMGenerator.CP_CORNER_NPP = 3;
  54356. PMREMGenerator.CP_CORNER_PNN = 4;
  54357. PMREMGenerator.CP_CORNER_PNP = 5;
  54358. PMREMGenerator.CP_CORNER_PPN = 6;
  54359. PMREMGenerator.CP_CORNER_PPP = 7;
  54360. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  54361. //3x2 matrices that map cube map indexing vectors in 3d
  54362. // (after face selection and divide through by the
  54363. // _ABSOLUTE VALUE_ of the max coord)
  54364. // into NVC space
  54365. //Note this currently assumes the D3D cube face ordering and orientation
  54366. PMREMGenerator._sgFace2DMapping = [
  54367. //XPOS face
  54368. [[0, 0, -1],
  54369. [0, -1, 0],
  54370. [1, 0, 0]],
  54371. //XNEG face
  54372. [[0, 0, 1],
  54373. [0, -1, 0],
  54374. [-1, 0, 0]],
  54375. //YPOS face
  54376. [[1, 0, 0],
  54377. [0, 0, 1],
  54378. [0, 1, 0]],
  54379. //YNEG face
  54380. [[1, 0, 0],
  54381. [0, 0, -1],
  54382. [0, -1, 0]],
  54383. //ZPOS face
  54384. [[1, 0, 0],
  54385. [0, -1, 0],
  54386. [0, 0, 1]],
  54387. //ZNEG face
  54388. [[-1, 0, 0],
  54389. [0, -1, 0],
  54390. [0, 0, -1]],
  54391. ];
  54392. //------------------------------------------------------------------------------
  54393. // D3D cube map face specification
  54394. // mapping from 3D x,y,z cube map lookup coordinates
  54395. // to 2D within face u,v coordinates
  54396. //
  54397. // --------------------> U direction
  54398. // | (within-face texture space)
  54399. // | _____
  54400. // | | |
  54401. // | | +Y |
  54402. // | _____|_____|_____ _____
  54403. // | | | | | |
  54404. // | | -X | +Z | +X | -Z |
  54405. // | |_____|_____|_____|_____|
  54406. // | | |
  54407. // | | -Y |
  54408. // | |_____|
  54409. // |
  54410. // v V direction
  54411. // (within-face texture space)
  54412. //------------------------------------------------------------------------------
  54413. //Information about neighbors and how texture coorrdinates change across faces
  54414. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  54415. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  54416. //Note this currently assumes the D3D cube face ordering and orientation
  54417. PMREMGenerator._sgCubeNgh = [
  54418. //XPOS face
  54419. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54420. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54421. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54422. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  54423. //XNEG face
  54424. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54425. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  54426. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  54427. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  54428. //YPOS face
  54429. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  54430. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  54431. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  54432. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  54433. //YNEG face
  54434. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  54435. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54436. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54437. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  54438. //ZPOS face
  54439. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54440. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  54441. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54442. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  54443. //ZNEG face
  54444. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54445. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54446. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  54447. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  54448. ];
  54449. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  54450. // this table is used to average over the edges.
  54451. PMREMGenerator._sgCubeEdgeList = [
  54452. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  54453. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54454. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  54455. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54456. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54457. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54458. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  54459. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  54460. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  54461. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54462. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  54463. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  54464. ];
  54465. //Information about which of the 8 cube corners are correspond to the
  54466. // the 4 corners in each cube face
  54467. // the order is upper left, upper right, lower left, lower right
  54468. PMREMGenerator._sgCubeCornerList = [
  54469. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  54470. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  54471. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  54472. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  54473. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  54474. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  54475. ];
  54476. Internals.PMREMGenerator = PMREMGenerator;
  54477. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54478. })(BABYLON || (BABYLON = {}));
  54479. //# sourceMappingURL=babylon.pmremgenerator.js.map
  54480. var BABYLON;
  54481. (function (BABYLON) {
  54482. /**
  54483. * This represents a texture coming from an HDR input.
  54484. *
  54485. * The only supported format is currently panorama picture stored in RGBE format.
  54486. * Example of such files can be found on HDRLib: http://hdrlib.com/
  54487. */
  54488. var HDRCubeTexture = (function (_super) {
  54489. __extends(HDRCubeTexture, _super);
  54490. /**
  54491. * Instantiates an HDRTexture from the following parameters.
  54492. *
  54493. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  54494. * @param scene The scene the texture will be used in
  54495. * @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.
  54496. * @param noMipmap Forces to not generate the mipmap if true
  54497. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  54498. * @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)
  54499. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  54500. */
  54501. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  54502. if (noMipmap === void 0) { noMipmap = false; }
  54503. if (generateHarmonics === void 0) { generateHarmonics = true; }
  54504. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  54505. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  54506. if (onLoad === void 0) { onLoad = null; }
  54507. if (onError === void 0) { onError = null; }
  54508. var _this = _super.call(this, scene) || this;
  54509. _this._useInGammaSpace = false;
  54510. _this._generateHarmonics = true;
  54511. _this._isBABYLONPreprocessed = false;
  54512. _this._onLoad = null;
  54513. _this._onError = null;
  54514. /**
  54515. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  54516. */
  54517. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  54518. /**
  54519. * The spherical polynomial data extracted from the texture.
  54520. */
  54521. _this.sphericalPolynomial = null;
  54522. /**
  54523. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  54524. * This is usefull at run time to apply the good shader.
  54525. */
  54526. _this.isPMREM = false;
  54527. _this._isBlocking = true;
  54528. if (!url) {
  54529. return _this;
  54530. }
  54531. _this.name = url;
  54532. _this.url = url;
  54533. _this.hasAlpha = false;
  54534. _this.isCube = true;
  54535. _this._textureMatrix = BABYLON.Matrix.Identity();
  54536. _this._onLoad = onLoad;
  54537. _this._onError = onError;
  54538. if (size) {
  54539. _this._isBABYLONPreprocessed = false;
  54540. _this._noMipmap = noMipmap;
  54541. _this._size = size;
  54542. _this._useInGammaSpace = useInGammaSpace;
  54543. _this._usePMREMGenerator = usePMREMGenerator &&
  54544. scene.getEngine().getCaps().textureLOD &&
  54545. _this.getScene().getEngine().getCaps().textureFloat &&
  54546. !_this._useInGammaSpace;
  54547. }
  54548. else {
  54549. _this._isBABYLONPreprocessed = true;
  54550. _this._noMipmap = false;
  54551. _this._useInGammaSpace = false;
  54552. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  54553. _this.getScene().getEngine().getCaps().textureFloat &&
  54554. !_this._useInGammaSpace;
  54555. }
  54556. _this.isPMREM = _this._usePMREMGenerator;
  54557. _this._texture = _this._getFromCache(url, _this._noMipmap);
  54558. if (!_this._texture) {
  54559. if (!scene.useDelayedTextureLoading) {
  54560. _this.loadTexture();
  54561. }
  54562. else {
  54563. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  54564. }
  54565. }
  54566. return _this;
  54567. }
  54568. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  54569. /**
  54570. * Gets wether or not the texture is blocking during loading.
  54571. */
  54572. get: function () {
  54573. return this._isBlocking;
  54574. },
  54575. /**
  54576. * Sets wether or not the texture is blocking during loading.
  54577. */
  54578. set: function (value) {
  54579. this._isBlocking = value;
  54580. },
  54581. enumerable: true,
  54582. configurable: true
  54583. });
  54584. /**
  54585. * Occurs when the file is a preprocessed .babylon.hdr file.
  54586. */
  54587. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  54588. var _this = this;
  54589. var mipLevels = 0;
  54590. var floatArrayView = null;
  54591. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  54592. var mips = [];
  54593. var startIndex = 30;
  54594. for (var level = 0; level < mipLevels; level++) {
  54595. mips.push([]);
  54596. // Fill each pixel of the mip level.
  54597. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  54598. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54599. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  54600. mips[level].push(faceData);
  54601. startIndex += faceSize;
  54602. }
  54603. }
  54604. return mips;
  54605. } : null;
  54606. var callback = function (buffer) {
  54607. // Create Native Array Views
  54608. var intArrayView = new Int32Array(buffer);
  54609. floatArrayView = new Float32Array(buffer);
  54610. // Fill header.
  54611. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  54612. _this._size = intArrayView[1]; // CubeMap max mip face size.
  54613. // Update Texture Information.
  54614. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  54615. // Fill polynomial information.
  54616. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  54617. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  54618. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  54619. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  54620. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  54621. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  54622. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  54623. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  54624. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  54625. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  54626. // Fill pixel data.
  54627. mipLevels = intArrayView[29]; // Number of mip levels.
  54628. var startIndex = 30;
  54629. var data = [];
  54630. var faceSize = Math.pow(_this._size, 2) * 3;
  54631. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54632. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  54633. startIndex += faceSize;
  54634. }
  54635. var results = [];
  54636. var byteArray = null;
  54637. // Push each faces.
  54638. for (var k = 0; k < 6; k++) {
  54639. var dataFace = null;
  54640. // If special cases.
  54641. if (!mipmapGenerator) {
  54642. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  54643. dataFace = data[j];
  54644. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  54645. // 3 channels of 1 bytes per pixel in bytes.
  54646. var byteBuffer = new ArrayBuffer(faceSize);
  54647. byteArray = new Uint8Array(byteBuffer);
  54648. }
  54649. for (var i = 0; i < _this._size * _this._size; i++) {
  54650. // Put in gamma space if requested.
  54651. if (_this._useInGammaSpace) {
  54652. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  54653. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  54654. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  54655. }
  54656. // Convert to int texture for fallback.
  54657. if (byteArray) {
  54658. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  54659. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  54660. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  54661. // May use luminance instead if the result is not accurate.
  54662. var max = Math.max(Math.max(r, g), b);
  54663. if (max > 255) {
  54664. var scale = 255 / max;
  54665. r *= scale;
  54666. g *= scale;
  54667. b *= scale;
  54668. }
  54669. byteArray[(i * 3) + 0] = r;
  54670. byteArray[(i * 3) + 1] = g;
  54671. byteArray[(i * 3) + 2] = b;
  54672. }
  54673. }
  54674. }
  54675. else {
  54676. dataFace = data[k];
  54677. }
  54678. // Fill the array accordingly.
  54679. if (byteArray) {
  54680. results.push(byteArray);
  54681. }
  54682. else {
  54683. results.push(dataFace);
  54684. }
  54685. }
  54686. return results;
  54687. };
  54688. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(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);
  54689. };
  54690. /**
  54691. * Occurs when the file is raw .hdr file.
  54692. */
  54693. HDRCubeTexture.prototype.loadHDRTexture = function () {
  54694. var _this = this;
  54695. var callback = function (buffer) {
  54696. // Extract the raw linear data.
  54697. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  54698. // Generate harmonics if needed.
  54699. if (_this._generateHarmonics) {
  54700. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  54701. }
  54702. var results = [];
  54703. var byteArray = null;
  54704. // Push each faces.
  54705. for (var j = 0; j < 6; j++) {
  54706. // Create uintarray fallback.
  54707. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  54708. // 3 channels of 1 bytes per pixel in bytes.
  54709. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  54710. byteArray = new Uint8Array(byteBuffer);
  54711. }
  54712. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  54713. // If special cases.
  54714. if (_this._useInGammaSpace || byteArray) {
  54715. for (var i = 0; i < _this._size * _this._size; i++) {
  54716. // Put in gamma space if requested.
  54717. if (_this._useInGammaSpace) {
  54718. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  54719. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  54720. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  54721. }
  54722. // Convert to int texture for fallback.
  54723. if (byteArray) {
  54724. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  54725. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  54726. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  54727. // May use luminance instead if the result is not accurate.
  54728. var max = Math.max(Math.max(r, g), b);
  54729. if (max > 255) {
  54730. var scale = 255 / max;
  54731. r *= scale;
  54732. g *= scale;
  54733. b *= scale;
  54734. }
  54735. byteArray[(i * 3) + 0] = r;
  54736. byteArray[(i * 3) + 1] = g;
  54737. byteArray[(i * 3) + 2] = b;
  54738. }
  54739. }
  54740. }
  54741. if (byteArray) {
  54742. results.push(byteArray);
  54743. }
  54744. else {
  54745. results.push(dataFace);
  54746. }
  54747. }
  54748. return results;
  54749. };
  54750. var mipmapGenerator = null;
  54751. if (!this._noMipmap &&
  54752. this._usePMREMGenerator) {
  54753. mipmapGenerator = function (data) {
  54754. // Custom setup of the generator matching with the PBR shader values.
  54755. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  54756. return generator.filterCubeMap();
  54757. };
  54758. }
  54759. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(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);
  54760. };
  54761. /**
  54762. * Starts the loading process of the texture.
  54763. */
  54764. HDRCubeTexture.prototype.loadTexture = function () {
  54765. if (this._isBABYLONPreprocessed) {
  54766. this.loadBabylonTexture();
  54767. }
  54768. else {
  54769. this.loadHDRTexture();
  54770. }
  54771. };
  54772. HDRCubeTexture.prototype.clone = function () {
  54773. var size = this._isBABYLONPreprocessed ? null : this._size;
  54774. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  54775. // Base texture
  54776. newTexture.level = this.level;
  54777. newTexture.wrapU = this.wrapU;
  54778. newTexture.wrapV = this.wrapV;
  54779. newTexture.coordinatesIndex = this.coordinatesIndex;
  54780. newTexture.coordinatesMode = this.coordinatesMode;
  54781. return newTexture;
  54782. };
  54783. // Methods
  54784. HDRCubeTexture.prototype.delayLoad = function () {
  54785. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  54786. return;
  54787. }
  54788. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  54789. this._texture = this._getFromCache(this.url, this._noMipmap);
  54790. if (!this._texture) {
  54791. this.loadTexture();
  54792. }
  54793. };
  54794. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  54795. return this._textureMatrix;
  54796. };
  54797. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  54798. var texture = null;
  54799. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  54800. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  54801. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  54802. texture.name = parsedTexture.name;
  54803. texture.hasAlpha = parsedTexture.hasAlpha;
  54804. texture.level = parsedTexture.level;
  54805. texture.coordinatesMode = parsedTexture.coordinatesMode;
  54806. texture.isBlocking = parsedTexture.isBlocking;
  54807. }
  54808. return texture;
  54809. };
  54810. HDRCubeTexture.prototype.serialize = function () {
  54811. if (!this.name) {
  54812. return null;
  54813. }
  54814. var serializationObject = {};
  54815. serializationObject.name = this.name;
  54816. serializationObject.hasAlpha = this.hasAlpha;
  54817. serializationObject.isCube = true;
  54818. serializationObject.level = this.level;
  54819. serializationObject.size = this._size;
  54820. serializationObject.coordinatesMode = this.coordinatesMode;
  54821. serializationObject.useInGammaSpace = this._useInGammaSpace;
  54822. serializationObject.generateHarmonics = this._generateHarmonics;
  54823. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  54824. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  54825. serializationObject.customType = "BABYLON.HDRCubeTexture";
  54826. serializationObject.noMipmap = this._noMipmap;
  54827. serializationObject.isBlocking = this._isBlocking;
  54828. return serializationObject;
  54829. };
  54830. /**
  54831. * Saves as a file the data contained in the texture in a binary format.
  54832. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  54833. * as the spherical used in the lighting.
  54834. * @param url The HDR file url.
  54835. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  54836. * @param onError Method called if any error happens during download.
  54837. * @return The packed binary data.
  54838. */
  54839. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  54840. if (onError === void 0) { onError = null; }
  54841. var callback = function (buffer) {
  54842. var data = new Blob([buffer], { type: 'application/octet-stream' });
  54843. // Returns a URL you can use as a href.
  54844. var objUrl = window.URL.createObjectURL(data);
  54845. // Simulates a link to it and click to dowload.
  54846. var a = document.createElement("a");
  54847. document.body.appendChild(a);
  54848. a.style.display = "none";
  54849. a.href = objUrl;
  54850. a.download = "envmap.babylon.hdr";
  54851. a.click();
  54852. };
  54853. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  54854. };
  54855. /**
  54856. * Serializes the data contained in the texture in a binary format.
  54857. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  54858. * as the spherical used in the lighting.
  54859. * @param url The HDR file url.
  54860. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  54861. * @param onError Method called if any error happens during download.
  54862. * @return The packed binary data.
  54863. */
  54864. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  54865. if (onError === void 0) { onError = null; }
  54866. // Needs the url tho create the texture.
  54867. if (!url) {
  54868. return null;
  54869. }
  54870. // Check Power of two size.
  54871. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  54872. return null;
  54873. }
  54874. var getDataCallback = function (dataBuffer) {
  54875. // Extract the raw linear data.
  54876. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  54877. // Generate harmonics if needed.
  54878. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  54879. // Generate seamless faces
  54880. var mipGeneratorArray = [];
  54881. // Data are known to be in +X +Y +Z -X -Y -Z
  54882. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  54883. mipGeneratorArray.push(cubeData.right); // +X
  54884. mipGeneratorArray.push(cubeData.left); // -X
  54885. mipGeneratorArray.push(cubeData.up); // +Y
  54886. mipGeneratorArray.push(cubeData.down); // -Y
  54887. mipGeneratorArray.push(cubeData.front); // +Z
  54888. mipGeneratorArray.push(cubeData.back); // -Z
  54889. // Custom setup of the generator matching with the PBR shader values.
  54890. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  54891. var mippedData = generator.filterCubeMap();
  54892. // Compute required byte length.
  54893. var byteLength = 1 * 4; // Raw Data Version int32.
  54894. byteLength += 4; // CubeMap max mip face size int32.
  54895. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  54896. // Add data size.
  54897. byteLength += 4; // Number of mip levels int32.
  54898. for (var level = 0; level < mippedData.length; level++) {
  54899. var mipSize = size >> level;
  54900. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  54901. }
  54902. // Prepare binary structure.
  54903. var buffer = new ArrayBuffer(byteLength);
  54904. var intArrayView = new Int32Array(buffer);
  54905. var floatArrayView = new Float32Array(buffer);
  54906. // Fill header.
  54907. intArrayView[0] = 1; // Version 1.
  54908. intArrayView[1] = size; // CubeMap max mip face size.
  54909. // Fill polynomial information.
  54910. sphericalPolynomial.x.toArray(floatArrayView, 2);
  54911. sphericalPolynomial.y.toArray(floatArrayView, 5);
  54912. sphericalPolynomial.z.toArray(floatArrayView, 8);
  54913. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  54914. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  54915. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  54916. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  54917. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  54918. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  54919. // Fill pixel data.
  54920. intArrayView[29] = mippedData.length; // Number of mip levels.
  54921. var startIndex = 30;
  54922. for (var level = 0; level < mippedData.length; level++) {
  54923. // Fill each pixel of the mip level.
  54924. var faceSize = Math.pow(size >> level, 2) * 3;
  54925. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54926. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  54927. startIndex += faceSize;
  54928. }
  54929. }
  54930. // Callback.
  54931. callback(buffer);
  54932. };
  54933. // Download and process.
  54934. BABYLON.Tools.LoadFile(url, function (data) {
  54935. getDataCallback(data);
  54936. }, null, null, true, onError);
  54937. };
  54938. return HDRCubeTexture;
  54939. }(BABYLON.BaseTexture));
  54940. HDRCubeTexture._facesMapping = [
  54941. "right",
  54942. "up",
  54943. "front",
  54944. "left",
  54945. "down",
  54946. "back"
  54947. ];
  54948. BABYLON.HDRCubeTexture = HDRCubeTexture;
  54949. })(BABYLON || (BABYLON = {}));
  54950. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  54951. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  54952. // Huge respect for a such great lib.
  54953. // Earcut license:
  54954. // Copyright (c) 2016, Mapbox
  54955. //
  54956. // Permission to use, copy, modify, and/or distribute this software for any purpose
  54957. // with or without fee is hereby granted, provided that the above copyright notice
  54958. // and this permission notice appear in all copies.
  54959. //
  54960. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  54961. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  54962. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  54963. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  54964. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  54965. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  54966. // THIS SOFTWARE.
  54967. var Earcut;
  54968. (function (Earcut) {
  54969. /**
  54970. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  54971. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  54972. * @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).
  54973. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  54974. */
  54975. function earcut(data, holeIndices, dim) {
  54976. dim = dim || 2;
  54977. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  54978. if (!outerNode)
  54979. return triangles;
  54980. var minX, minY, maxX, maxY, x, y, size;
  54981. if (hasHoles)
  54982. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  54983. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  54984. if (data.length > 80 * dim) {
  54985. minX = maxX = data[0];
  54986. minY = maxY = data[1];
  54987. for (var i = dim; i < outerLen; i += dim) {
  54988. x = data[i];
  54989. y = data[i + 1];
  54990. if (x < minX)
  54991. minX = x;
  54992. if (y < minY)
  54993. minY = y;
  54994. if (x > maxX)
  54995. maxX = x;
  54996. if (y > maxY)
  54997. maxY = y;
  54998. }
  54999. // minX, minY and size are later used to transform coords into integers for z-order calculation
  55000. size = Math.max(maxX - minX, maxY - minY);
  55001. }
  55002. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  55003. return triangles;
  55004. }
  55005. Earcut.earcut = earcut;
  55006. // create a circular doubly linked list from polygon points in the specified winding order
  55007. function linkedList(data, start, end, dim, clockwise) {
  55008. var i, last;
  55009. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  55010. for (i = start; i < end; i += dim)
  55011. last = insertNode(i, data[i], data[i + 1], last);
  55012. }
  55013. else {
  55014. for (i = end - dim; i >= start; i -= dim)
  55015. last = insertNode(i, data[i], data[i + 1], last);
  55016. }
  55017. if (last && equals(last, last.next)) {
  55018. removeNode(last);
  55019. last = last.next;
  55020. }
  55021. return last;
  55022. }
  55023. // eliminate colinear or duplicate points
  55024. function filterPoints(start, end) {
  55025. if (!start)
  55026. return start;
  55027. if (!end)
  55028. end = start;
  55029. var p = start, again;
  55030. do {
  55031. again = false;
  55032. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  55033. removeNode(p);
  55034. p = end = p.prev;
  55035. if (p === p.next)
  55036. return null;
  55037. again = true;
  55038. }
  55039. else {
  55040. p = p.next;
  55041. }
  55042. } while (again || p !== end);
  55043. return end;
  55044. }
  55045. // main ear slicing loop which triangulates a polygon (given as a linked list)
  55046. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  55047. if (!ear)
  55048. return;
  55049. // interlink polygon nodes in z-order
  55050. if (!pass && size)
  55051. indexCurve(ear, minX, minY, size);
  55052. var stop = ear, prev, next;
  55053. // iterate through ears, slicing them one by one
  55054. while (ear.prev !== ear.next) {
  55055. prev = ear.prev;
  55056. next = ear.next;
  55057. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  55058. // cut off the triangle
  55059. triangles.push(prev.i / dim);
  55060. triangles.push(ear.i / dim);
  55061. triangles.push(next.i / dim);
  55062. removeNode(ear);
  55063. // skipping the next vertice leads to less sliver triangles
  55064. ear = next.next;
  55065. stop = next.next;
  55066. continue;
  55067. }
  55068. ear = next;
  55069. // if we looped through the whole remaining polygon and can't find any more ears
  55070. if (ear === stop) {
  55071. // try filtering points and slicing again
  55072. if (!pass) {
  55073. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  55074. // if this didn't work, try curing all small self-intersections locally
  55075. }
  55076. else if (pass === 1) {
  55077. ear = cureLocalIntersections(ear, triangles, dim);
  55078. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  55079. // as a last resort, try splitting the remaining polygon into two
  55080. }
  55081. else if (pass === 2) {
  55082. splitEarcut(ear, triangles, dim, minX, minY, size);
  55083. }
  55084. break;
  55085. }
  55086. }
  55087. }
  55088. // check whether a polygon node forms a valid ear with adjacent nodes
  55089. function isEar(ear) {
  55090. var a = ear.prev, b = ear, c = ear.next;
  55091. if (area(a, b, c) >= 0)
  55092. return false; // reflex, can't be an ear
  55093. // now make sure we don't have other points inside the potential ear
  55094. var p = ear.next.next;
  55095. while (p !== ear.prev) {
  55096. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  55097. area(p.prev, p, p.next) >= 0)
  55098. return false;
  55099. p = p.next;
  55100. }
  55101. return true;
  55102. }
  55103. function isEarHashed(ear, minX, minY, size) {
  55104. var a = ear.prev, b = ear, c = ear.next;
  55105. if (area(a, b, c) >= 0)
  55106. return false; // reflex, can't be an ear
  55107. // triangle bbox; min & max are calculated like this for speed
  55108. 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);
  55109. // z-order range for the current triangle bbox;
  55110. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  55111. // first look for points inside the triangle in increasing z-order
  55112. var p = ear.nextZ;
  55113. while (p && p.z <= maxZ) {
  55114. if (p !== ear.prev &&
  55115. p !== ear.next &&
  55116. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  55117. area(p.prev, p, p.next) >= 0)
  55118. return false;
  55119. p = p.nextZ;
  55120. }
  55121. // then look for points in decreasing z-order
  55122. p = ear.prevZ;
  55123. while (p && p.z >= minZ) {
  55124. if (p !== ear.prev &&
  55125. p !== ear.next &&
  55126. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  55127. area(p.prev, p, p.next) >= 0)
  55128. return false;
  55129. p = p.prevZ;
  55130. }
  55131. return true;
  55132. }
  55133. // go through all polygon nodes and cure small local self-intersections
  55134. function cureLocalIntersections(start, triangles, dim) {
  55135. var p = start;
  55136. do {
  55137. var a = p.prev, b = p.next.next;
  55138. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  55139. triangles.push(a.i / dim);
  55140. triangles.push(p.i / dim);
  55141. triangles.push(b.i / dim);
  55142. // remove two nodes involved
  55143. removeNode(p);
  55144. removeNode(p.next);
  55145. p = start = b;
  55146. }
  55147. p = p.next;
  55148. } while (p !== start);
  55149. return p;
  55150. }
  55151. // try splitting polygon into two and triangulate them independently
  55152. function splitEarcut(start, triangles, dim, minX, minY, size) {
  55153. // look for a valid diagonal that divides the polygon into two
  55154. var a = start;
  55155. do {
  55156. var b = a.next.next;
  55157. while (b !== a.prev) {
  55158. if (a.i !== b.i && isValidDiagonal(a, b)) {
  55159. // split the polygon in two by the diagonal
  55160. var c = splitPolygon(a, b);
  55161. // filter colinear points around the cuts
  55162. a = filterPoints(a, a.next);
  55163. c = filterPoints(c, c.next);
  55164. // run earcut on each half
  55165. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  55166. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  55167. return;
  55168. }
  55169. b = b.next;
  55170. }
  55171. a = a.next;
  55172. } while (a !== start);
  55173. }
  55174. // link every hole into the outer loop, producing a single-ring polygon without holes
  55175. function eliminateHoles(data, holeIndices, outerNode, dim) {
  55176. var queue = [], i, len, start, end, list;
  55177. for (i = 0, len = holeIndices.length; i < len; i++) {
  55178. start = holeIndices[i] * dim;
  55179. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  55180. list = linkedList(data, start, end, dim, false);
  55181. if (list === list.next)
  55182. list.steiner = true;
  55183. queue.push(getLeftmost(list));
  55184. }
  55185. queue.sort(compareX);
  55186. // process holes from left to right
  55187. for (i = 0; i < queue.length; i++) {
  55188. eliminateHole(queue[i], outerNode);
  55189. outerNode = filterPoints(outerNode, outerNode.next);
  55190. }
  55191. return outerNode;
  55192. }
  55193. function compareX(a, b) {
  55194. return a.x - b.x;
  55195. }
  55196. // find a bridge between vertices that connects hole with an outer ring and and link it
  55197. function eliminateHole(hole, outerNode) {
  55198. outerNode = findHoleBridge(hole, outerNode);
  55199. if (outerNode) {
  55200. var b = splitPolygon(outerNode, hole);
  55201. filterPoints(b, b.next);
  55202. }
  55203. }
  55204. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  55205. function findHoleBridge(hole, outerNode) {
  55206. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  55207. // find a segment intersected by a ray from the hole's leftmost point to the left;
  55208. // segment's endpoint with lesser x will be potential connection point
  55209. do {
  55210. if (hy <= p.y && hy >= p.next.y) {
  55211. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  55212. if (x <= hx && x > qx) {
  55213. qx = x;
  55214. if (x === hx) {
  55215. if (hy === p.y)
  55216. return p;
  55217. if (hy === p.next.y)
  55218. return p.next;
  55219. }
  55220. m = p.x < p.next.x ? p : p.next;
  55221. }
  55222. }
  55223. p = p.next;
  55224. } while (p !== outerNode);
  55225. if (!m)
  55226. return null;
  55227. if (hx === qx)
  55228. return m.prev; // hole touches outer segment; pick lower endpoint
  55229. // look for points inside the triangle of hole point, segment intersection and endpoint;
  55230. // if there are no points found, we have a valid connection;
  55231. // otherwise choose the point of the minimum angle with the ray as connection point
  55232. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  55233. p = m.next;
  55234. while (p !== stop) {
  55235. if (hx >= p.x &&
  55236. p.x >= mx &&
  55237. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  55238. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  55239. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  55240. m = p;
  55241. tanMin = tan;
  55242. }
  55243. }
  55244. p = p.next;
  55245. }
  55246. return m;
  55247. }
  55248. // interlink polygon nodes in z-order
  55249. function indexCurve(start, minX, minY, size) {
  55250. var p = start;
  55251. do {
  55252. if (p.z === null)
  55253. p.z = zOrder(p.x, p.y, minX, minY, size);
  55254. p.prevZ = p.prev;
  55255. p.nextZ = p.next;
  55256. p = p.next;
  55257. } while (p !== start);
  55258. p.prevZ.nextZ = null;
  55259. p.prevZ = null;
  55260. sortLinked(p);
  55261. }
  55262. // Simon Tatham's linked list merge sort algorithm
  55263. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  55264. function sortLinked(list) {
  55265. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  55266. do {
  55267. p = list;
  55268. list = null;
  55269. tail = null;
  55270. numMerges = 0;
  55271. while (p) {
  55272. numMerges++;
  55273. q = p;
  55274. pSize = 0;
  55275. for (i = 0; i < inSize; i++) {
  55276. pSize++;
  55277. q = q.nextZ;
  55278. if (!q)
  55279. break;
  55280. }
  55281. qSize = inSize;
  55282. while (pSize > 0 || (qSize > 0 && q)) {
  55283. if (pSize === 0) {
  55284. e = q;
  55285. q = q.nextZ;
  55286. qSize--;
  55287. }
  55288. else if (qSize === 0 || !q) {
  55289. e = p;
  55290. p = p.nextZ;
  55291. pSize--;
  55292. }
  55293. else if (p.z <= q.z) {
  55294. e = p;
  55295. p = p.nextZ;
  55296. pSize--;
  55297. }
  55298. else {
  55299. e = q;
  55300. q = q.nextZ;
  55301. qSize--;
  55302. }
  55303. if (tail)
  55304. tail.nextZ = e;
  55305. else
  55306. list = e;
  55307. e.prevZ = tail;
  55308. tail = e;
  55309. }
  55310. p = q;
  55311. }
  55312. tail.nextZ = null;
  55313. inSize *= 2;
  55314. } while (numMerges > 1);
  55315. return list;
  55316. }
  55317. // z-order of a point given coords and size of the data bounding box
  55318. function zOrder(x, y, minX, minY, size) {
  55319. // coords are transformed into non-negative 15-bit integer range
  55320. x = 32767 * (x - minX) / size;
  55321. y = 32767 * (y - minY) / size;
  55322. x = (x | (x << 8)) & 0x00FF00FF;
  55323. x = (x | (x << 4)) & 0x0F0F0F0F;
  55324. x = (x | (x << 2)) & 0x33333333;
  55325. x = (x | (x << 1)) & 0x55555555;
  55326. y = (y | (y << 8)) & 0x00FF00FF;
  55327. y = (y | (y << 4)) & 0x0F0F0F0F;
  55328. y = (y | (y << 2)) & 0x33333333;
  55329. y = (y | (y << 1)) & 0x55555555;
  55330. return x | (y << 1);
  55331. }
  55332. // find the leftmost node of a polygon ring
  55333. function getLeftmost(start) {
  55334. var p = start, leftmost = start;
  55335. do {
  55336. if (p.x < leftmost.x)
  55337. leftmost = p;
  55338. p = p.next;
  55339. } while (p !== start);
  55340. return leftmost;
  55341. }
  55342. // check if a point lies within a convex triangle
  55343. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  55344. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  55345. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  55346. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  55347. }
  55348. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  55349. function isValidDiagonal(a, b) {
  55350. return a.next.i !== b.i &&
  55351. a.prev.i !== b.i &&
  55352. !intersectsPolygon(a, b) &&
  55353. locallyInside(a, b) &&
  55354. locallyInside(b, a) &&
  55355. middleInside(a, b);
  55356. }
  55357. // signed area of a triangle
  55358. function area(p, q, r) {
  55359. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  55360. }
  55361. // check if two points are equal
  55362. function equals(p1, p2) {
  55363. return p1.x === p2.x && p1.y === p2.y;
  55364. }
  55365. // check if two segments intersect
  55366. function intersects(p1, q1, p2, q2) {
  55367. if ((equals(p1, q1) && equals(p2, q2)) ||
  55368. (equals(p1, q2) && equals(p2, q1)))
  55369. return true;
  55370. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  55371. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  55372. }
  55373. // check if a polygon diagonal intersects any polygon segments
  55374. function intersectsPolygon(a, b) {
  55375. var p = a;
  55376. do {
  55377. if (p.i !== a.i &&
  55378. p.next.i !== a.i &&
  55379. p.i !== b.i &&
  55380. p.next.i !== b.i &&
  55381. intersects(p, p.next, a, b))
  55382. return true;
  55383. p = p.next;
  55384. } while (p !== a);
  55385. return false;
  55386. }
  55387. // check if a polygon diagonal is locally inside the polygon
  55388. function locallyInside(a, b) {
  55389. return area(a.prev, a, a.next) < 0
  55390. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  55391. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  55392. }
  55393. // check if the middle point of a polygon diagonal is inside the polygon
  55394. function middleInside(a, b) {
  55395. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  55396. do {
  55397. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  55398. inside = !inside;
  55399. p = p.next;
  55400. } while (p !== a);
  55401. return inside;
  55402. }
  55403. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  55404. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  55405. function splitPolygon(a, b) {
  55406. 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;
  55407. a.next = b;
  55408. b.prev = a;
  55409. a2.next = an;
  55410. an.prev = a2;
  55411. b2.next = a2;
  55412. a2.prev = b2;
  55413. bp.next = b2;
  55414. b2.prev = bp;
  55415. return b2;
  55416. }
  55417. // create a node and optionally link it with previous one (in a circular doubly linked list)
  55418. function insertNode(i, x, y, last) {
  55419. var p = new Node(i, x, y);
  55420. if (!last) {
  55421. p.prev = p;
  55422. p.next = p;
  55423. }
  55424. else {
  55425. p.next = last.next;
  55426. p.prev = last;
  55427. last.next.prev = p;
  55428. last.next = p;
  55429. }
  55430. return p;
  55431. }
  55432. function removeNode(p) {
  55433. p.next.prev = p.prev;
  55434. p.prev.next = p.next;
  55435. if (p.prevZ)
  55436. p.prevZ.nextZ = p.nextZ;
  55437. if (p.nextZ)
  55438. p.nextZ.prevZ = p.prevZ;
  55439. }
  55440. function Node(i, x, y) {
  55441. // vertice index in coordinates array
  55442. this.i = i;
  55443. // vertex coordinates
  55444. this.x = x;
  55445. this.y = y;
  55446. // previous and next vertice nodes in a polygon ring
  55447. this.prev = null;
  55448. this.next = null;
  55449. // z-order curve value
  55450. this.z = null;
  55451. // previous and next nodes in z-order
  55452. this.prevZ = null;
  55453. this.nextZ = null;
  55454. // indicates whether this is a steiner point
  55455. this.steiner = false;
  55456. }
  55457. /**
  55458. * return a percentage difference between the polygon area and its triangulation area;
  55459. * used to verify correctness of triangulation
  55460. */
  55461. function deviation(data, holeIndices, dim, triangles) {
  55462. var hasHoles = holeIndices && holeIndices.length;
  55463. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  55464. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  55465. if (hasHoles) {
  55466. for (var i = 0, len = holeIndices.length; i < len; i++) {
  55467. var start = holeIndices[i] * dim;
  55468. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  55469. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  55470. }
  55471. }
  55472. var trianglesArea = 0;
  55473. for (i = 0; i < triangles.length; i += 3) {
  55474. var a = triangles[i] * dim;
  55475. var b = triangles[i + 1] * dim;
  55476. var c = triangles[i + 2] * dim;
  55477. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  55478. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  55479. }
  55480. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  55481. }
  55482. Earcut.deviation = deviation;
  55483. ;
  55484. function signedArea(data, start, end, dim) {
  55485. var sum = 0;
  55486. for (var i = start, j = end - dim; i < end; i += dim) {
  55487. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  55488. j = i;
  55489. }
  55490. return sum;
  55491. }
  55492. /**
  55493. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  55494. */
  55495. function flatten(data) {
  55496. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  55497. for (var i = 0; i < data.length; i++) {
  55498. for (var j = 0; j < data[i].length; j++) {
  55499. for (var d = 0; d < dim; d++)
  55500. result.vertices.push(data[i][j][d]);
  55501. }
  55502. if (i > 0) {
  55503. holeIndex += data[i - 1].length;
  55504. result.holes.push(holeIndex);
  55505. }
  55506. }
  55507. return result;
  55508. }
  55509. Earcut.flatten = flatten;
  55510. ;
  55511. })(Earcut || (Earcut = {}));
  55512. //# sourceMappingURL=babylon.earcut.js.map
  55513. /// <reference path="..\Math\babylon.math.ts" />
  55514. var BABYLON;
  55515. (function (BABYLON) {
  55516. var IndexedVector2 = (function (_super) {
  55517. __extends(IndexedVector2, _super);
  55518. function IndexedVector2(original, index) {
  55519. var _this = _super.call(this, original.x, original.y) || this;
  55520. _this.index = index;
  55521. return _this;
  55522. }
  55523. return IndexedVector2;
  55524. }(BABYLON.Vector2));
  55525. var PolygonPoints = (function () {
  55526. function PolygonPoints() {
  55527. this.elements = new Array();
  55528. }
  55529. PolygonPoints.prototype.add = function (originalPoints) {
  55530. var _this = this;
  55531. var result = new Array();
  55532. originalPoints.forEach(function (point) {
  55533. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  55534. var newPoint = new IndexedVector2(point, _this.elements.length);
  55535. result.push(newPoint);
  55536. _this.elements.push(newPoint);
  55537. }
  55538. });
  55539. return result;
  55540. };
  55541. PolygonPoints.prototype.computeBounds = function () {
  55542. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  55543. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  55544. this.elements.forEach(function (point) {
  55545. // x
  55546. if (point.x < lmin.x) {
  55547. lmin.x = point.x;
  55548. }
  55549. else if (point.x > lmax.x) {
  55550. lmax.x = point.x;
  55551. }
  55552. // y
  55553. if (point.y < lmin.y) {
  55554. lmin.y = point.y;
  55555. }
  55556. else if (point.y > lmax.y) {
  55557. lmax.y = point.y;
  55558. }
  55559. });
  55560. return {
  55561. min: lmin,
  55562. max: lmax,
  55563. width: lmax.x - lmin.x,
  55564. height: lmax.y - lmin.y
  55565. };
  55566. };
  55567. return PolygonPoints;
  55568. }());
  55569. var Polygon = (function () {
  55570. function Polygon() {
  55571. }
  55572. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  55573. return [
  55574. new BABYLON.Vector2(xmin, ymin),
  55575. new BABYLON.Vector2(xmax, ymin),
  55576. new BABYLON.Vector2(xmax, ymax),
  55577. new BABYLON.Vector2(xmin, ymax)
  55578. ];
  55579. };
  55580. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  55581. if (cx === void 0) { cx = 0; }
  55582. if (cy === void 0) { cy = 0; }
  55583. if (numberOfSides === void 0) { numberOfSides = 32; }
  55584. var result = new Array();
  55585. var angle = 0;
  55586. var increment = (Math.PI * 2) / numberOfSides;
  55587. for (var i = 0; i < numberOfSides; i++) {
  55588. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  55589. angle -= increment;
  55590. }
  55591. return result;
  55592. };
  55593. Polygon.Parse = function (input) {
  55594. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  55595. var i, result = [];
  55596. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  55597. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  55598. }
  55599. return result;
  55600. };
  55601. Polygon.StartingAt = function (x, y) {
  55602. return BABYLON.Path2.StartingAt(x, y);
  55603. };
  55604. return Polygon;
  55605. }());
  55606. BABYLON.Polygon = Polygon;
  55607. var PolygonMeshBuilder = (function () {
  55608. function PolygonMeshBuilder(name, contours, scene) {
  55609. this._points = new PolygonPoints();
  55610. this._outlinepoints = new PolygonPoints();
  55611. this._holes = [];
  55612. this._epoints = new Array();
  55613. this._eholes = new Array();
  55614. this._name = name;
  55615. this._scene = scene;
  55616. var points;
  55617. if (contours instanceof BABYLON.Path2) {
  55618. points = contours.getPoints();
  55619. }
  55620. else {
  55621. points = contours;
  55622. }
  55623. this._addToepoint(points);
  55624. this._points.add(points);
  55625. this._outlinepoints.add(points);
  55626. }
  55627. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  55628. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  55629. var p = points_1[_i];
  55630. this._epoints.push(p.x, p.y);
  55631. }
  55632. };
  55633. PolygonMeshBuilder.prototype.addHole = function (hole) {
  55634. this._points.add(hole);
  55635. var holepoints = new PolygonPoints();
  55636. holepoints.add(hole);
  55637. this._holes.push(holepoints);
  55638. this._eholes.push(this._epoints.length / 2);
  55639. this._addToepoint(hole);
  55640. return this;
  55641. };
  55642. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  55643. var _this = this;
  55644. if (updatable === void 0) { updatable = false; }
  55645. var result = new BABYLON.Mesh(this._name, this._scene);
  55646. var normals = [];
  55647. var positions = [];
  55648. var uvs = [];
  55649. var bounds = this._points.computeBounds();
  55650. this._points.elements.forEach(function (p) {
  55651. normals.push(0, 1.0, 0);
  55652. positions.push(p.x, 0, p.y);
  55653. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  55654. });
  55655. var indices = [];
  55656. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  55657. for (var i = 0; i < res.length; i++) {
  55658. indices.push(res[i]);
  55659. }
  55660. if (depth > 0) {
  55661. var positionscount = (positions.length / 3); //get the current pointcount
  55662. this._points.elements.forEach(function (p) {
  55663. normals.push(0, -1.0, 0);
  55664. positions.push(p.x, -depth, p.y);
  55665. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  55666. });
  55667. var totalCount = indices.length;
  55668. for (var i = 0; i < totalCount; i += 3) {
  55669. var i0 = indices[i + 0];
  55670. var i1 = indices[i + 1];
  55671. var i2 = indices[i + 2];
  55672. indices.push(i2 + positionscount);
  55673. indices.push(i1 + positionscount);
  55674. indices.push(i0 + positionscount);
  55675. }
  55676. //Add the sides
  55677. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  55678. this._holes.forEach(function (hole) {
  55679. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  55680. });
  55681. }
  55682. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  55683. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  55684. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  55685. result.setIndices(indices);
  55686. return result;
  55687. };
  55688. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  55689. var StartIndex = positions.length / 3;
  55690. var ulength = 0;
  55691. for (var i = 0; i < points.elements.length; i++) {
  55692. var p = points.elements[i];
  55693. var p1;
  55694. if ((i + 1) > points.elements.length - 1) {
  55695. p1 = points.elements[0];
  55696. }
  55697. else {
  55698. p1 = points.elements[i + 1];
  55699. }
  55700. positions.push(p.x, 0, p.y);
  55701. positions.push(p.x, -depth, p.y);
  55702. positions.push(p1.x, 0, p1.y);
  55703. positions.push(p1.x, -depth, p1.y);
  55704. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  55705. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  55706. var v3 = v2.subtract(v1);
  55707. var v4 = new BABYLON.Vector3(0, 1, 0);
  55708. var vn = BABYLON.Vector3.Cross(v3, v4);
  55709. vn = vn.normalize();
  55710. uvs.push(ulength / bounds.width, 0);
  55711. uvs.push(ulength / bounds.width, 1);
  55712. ulength += v3.length();
  55713. uvs.push((ulength / bounds.width), 0);
  55714. uvs.push((ulength / bounds.width), 1);
  55715. if (!flip) {
  55716. normals.push(-vn.x, -vn.y, -vn.z);
  55717. normals.push(-vn.x, -vn.y, -vn.z);
  55718. normals.push(-vn.x, -vn.y, -vn.z);
  55719. normals.push(-vn.x, -vn.y, -vn.z);
  55720. indices.push(StartIndex);
  55721. indices.push(StartIndex + 1);
  55722. indices.push(StartIndex + 2);
  55723. indices.push(StartIndex + 1);
  55724. indices.push(StartIndex + 3);
  55725. indices.push(StartIndex + 2);
  55726. }
  55727. else {
  55728. normals.push(vn.x, vn.y, vn.z);
  55729. normals.push(vn.x, vn.y, vn.z);
  55730. normals.push(vn.x, vn.y, vn.z);
  55731. normals.push(vn.x, vn.y, vn.z);
  55732. indices.push(StartIndex);
  55733. indices.push(StartIndex + 2);
  55734. indices.push(StartIndex + 1);
  55735. indices.push(StartIndex + 1);
  55736. indices.push(StartIndex + 2);
  55737. indices.push(StartIndex + 3);
  55738. }
  55739. StartIndex += 4;
  55740. }
  55741. ;
  55742. };
  55743. return PolygonMeshBuilder;
  55744. }());
  55745. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  55746. })(BABYLON || (BABYLON = {}));
  55747. //# sourceMappingURL=babylon.polygonMesh.js.map
  55748. var BABYLON;
  55749. (function (BABYLON) {
  55750. // Unique ID when we import meshes from Babylon to CSG
  55751. var currentCSGMeshId = 0;
  55752. // # class Vertex
  55753. // Represents a vertex of a polygon. Use your own vertex class instead of this
  55754. // one to provide additional features like texture coordinates and vertex
  55755. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  55756. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  55757. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  55758. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  55759. // is not used anywhere else.
  55760. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  55761. var Vertex = (function () {
  55762. function Vertex(pos, normal, uv) {
  55763. this.pos = pos;
  55764. this.normal = normal;
  55765. this.uv = uv;
  55766. }
  55767. Vertex.prototype.clone = function () {
  55768. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  55769. };
  55770. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  55771. // orientation of a polygon is flipped.
  55772. Vertex.prototype.flip = function () {
  55773. this.normal = this.normal.scale(-1);
  55774. };
  55775. // Create a new vertex between this vertex and `other` by linearly
  55776. // interpolating all properties using a parameter of `t`. Subclasses should
  55777. // override this to interpolate additional properties.
  55778. Vertex.prototype.interpolate = function (other, t) {
  55779. 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));
  55780. };
  55781. return Vertex;
  55782. }());
  55783. // # class Plane
  55784. // Represents a plane in 3D space.
  55785. var Plane = (function () {
  55786. function Plane(normal, w) {
  55787. this.normal = normal;
  55788. this.w = w;
  55789. }
  55790. Plane.FromPoints = function (a, b, c) {
  55791. var v0 = c.subtract(a);
  55792. var v1 = b.subtract(a);
  55793. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  55794. return null;
  55795. }
  55796. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  55797. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  55798. };
  55799. Plane.prototype.clone = function () {
  55800. return new Plane(this.normal.clone(), this.w);
  55801. };
  55802. Plane.prototype.flip = function () {
  55803. this.normal.scaleInPlace(-1);
  55804. this.w = -this.w;
  55805. };
  55806. // Split `polygon` by this plane if needed, then put the polygon or polygon
  55807. // fragments in the appropriate lists. Coplanar polygons go into either
  55808. // `coplanarFront` or `coplanarBack` depending on their orientation with
  55809. // respect to this plane. Polygons in front or in back of this plane go into
  55810. // either `front` or `back`.
  55811. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  55812. var COPLANAR = 0;
  55813. var FRONT = 1;
  55814. var BACK = 2;
  55815. var SPANNING = 3;
  55816. // Classify each point as well as the entire polygon into one of the above
  55817. // four classes.
  55818. var polygonType = 0;
  55819. var types = [];
  55820. var i;
  55821. var t;
  55822. for (i = 0; i < polygon.vertices.length; i++) {
  55823. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  55824. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  55825. polygonType |= type;
  55826. types.push(type);
  55827. }
  55828. // Put the polygon in the correct list, splitting it when necessary.
  55829. switch (polygonType) {
  55830. case COPLANAR:
  55831. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  55832. break;
  55833. case FRONT:
  55834. front.push(polygon);
  55835. break;
  55836. case BACK:
  55837. back.push(polygon);
  55838. break;
  55839. case SPANNING:
  55840. var f = [], b = [];
  55841. for (i = 0; i < polygon.vertices.length; i++) {
  55842. var j = (i + 1) % polygon.vertices.length;
  55843. var ti = types[i], tj = types[j];
  55844. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  55845. if (ti !== BACK)
  55846. f.push(vi);
  55847. if (ti !== FRONT)
  55848. b.push(ti !== BACK ? vi.clone() : vi);
  55849. if ((ti | tj) === SPANNING) {
  55850. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  55851. var v = vi.interpolate(vj, t);
  55852. f.push(v);
  55853. b.push(v.clone());
  55854. }
  55855. }
  55856. var poly;
  55857. if (f.length >= 3) {
  55858. poly = new Polygon(f, polygon.shared);
  55859. if (poly.plane)
  55860. front.push(poly);
  55861. }
  55862. if (b.length >= 3) {
  55863. poly = new Polygon(b, polygon.shared);
  55864. if (poly.plane)
  55865. back.push(poly);
  55866. }
  55867. break;
  55868. }
  55869. };
  55870. return Plane;
  55871. }());
  55872. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  55873. // point is on the plane.
  55874. Plane.EPSILON = 1e-5;
  55875. // # class Polygon
  55876. // Represents a convex polygon. The vertices used to initialize a polygon must
  55877. // be coplanar and form a convex loop.
  55878. //
  55879. // Each convex polygon has a `shared` property, which is shared between all
  55880. // polygons that are clones of each other or were split from the same polygon.
  55881. // This can be used to define per-polygon properties (such as surface color).
  55882. var Polygon = (function () {
  55883. function Polygon(vertices, shared) {
  55884. this.vertices = vertices;
  55885. this.shared = shared;
  55886. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  55887. }
  55888. Polygon.prototype.clone = function () {
  55889. var vertices = this.vertices.map(function (v) { return v.clone(); });
  55890. return new Polygon(vertices, this.shared);
  55891. };
  55892. Polygon.prototype.flip = function () {
  55893. this.vertices.reverse().map(function (v) { v.flip(); });
  55894. this.plane.flip();
  55895. };
  55896. return Polygon;
  55897. }());
  55898. // # class Node
  55899. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  55900. // by picking a polygon to split along. That polygon (and all other coplanar
  55901. // polygons) are added directly to that node and the other polygons are added to
  55902. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  55903. // no distinction between internal and leaf nodes.
  55904. var Node = (function () {
  55905. function Node(polygons) {
  55906. this.plane = null;
  55907. this.front = null;
  55908. this.back = null;
  55909. this.polygons = [];
  55910. if (polygons) {
  55911. this.build(polygons);
  55912. }
  55913. }
  55914. Node.prototype.clone = function () {
  55915. var node = new Node();
  55916. node.plane = this.plane && this.plane.clone();
  55917. node.front = this.front && this.front.clone();
  55918. node.back = this.back && this.back.clone();
  55919. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  55920. return node;
  55921. };
  55922. // Convert solid space to empty space and empty space to solid space.
  55923. Node.prototype.invert = function () {
  55924. for (var i = 0; i < this.polygons.length; i++) {
  55925. this.polygons[i].flip();
  55926. }
  55927. if (this.plane) {
  55928. this.plane.flip();
  55929. }
  55930. if (this.front) {
  55931. this.front.invert();
  55932. }
  55933. if (this.back) {
  55934. this.back.invert();
  55935. }
  55936. var temp = this.front;
  55937. this.front = this.back;
  55938. this.back = temp;
  55939. };
  55940. // Recursively remove all polygons in `polygons` that are inside this BSP
  55941. // tree.
  55942. Node.prototype.clipPolygons = function (polygons) {
  55943. if (!this.plane)
  55944. return polygons.slice();
  55945. var front = [], back = [];
  55946. for (var i = 0; i < polygons.length; i++) {
  55947. this.plane.splitPolygon(polygons[i], front, back, front, back);
  55948. }
  55949. if (this.front) {
  55950. front = this.front.clipPolygons(front);
  55951. }
  55952. if (this.back) {
  55953. back = this.back.clipPolygons(back);
  55954. }
  55955. else {
  55956. back = [];
  55957. }
  55958. return front.concat(back);
  55959. };
  55960. // Remove all polygons in this BSP tree that are inside the other BSP tree
  55961. // `bsp`.
  55962. Node.prototype.clipTo = function (bsp) {
  55963. this.polygons = bsp.clipPolygons(this.polygons);
  55964. if (this.front)
  55965. this.front.clipTo(bsp);
  55966. if (this.back)
  55967. this.back.clipTo(bsp);
  55968. };
  55969. // Return a list of all polygons in this BSP tree.
  55970. Node.prototype.allPolygons = function () {
  55971. var polygons = this.polygons.slice();
  55972. if (this.front)
  55973. polygons = polygons.concat(this.front.allPolygons());
  55974. if (this.back)
  55975. polygons = polygons.concat(this.back.allPolygons());
  55976. return polygons;
  55977. };
  55978. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  55979. // new polygons are filtered down to the bottom of the tree and become new
  55980. // nodes there. Each set of polygons is partitioned using the first polygon
  55981. // (no heuristic is used to pick a good split).
  55982. Node.prototype.build = function (polygons) {
  55983. if (!polygons.length)
  55984. return;
  55985. if (!this.plane)
  55986. this.plane = polygons[0].plane.clone();
  55987. var front = [], back = [];
  55988. for (var i = 0; i < polygons.length; i++) {
  55989. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  55990. }
  55991. if (front.length) {
  55992. if (!this.front)
  55993. this.front = new Node();
  55994. this.front.build(front);
  55995. }
  55996. if (back.length) {
  55997. if (!this.back)
  55998. this.back = new Node();
  55999. this.back.build(back);
  56000. }
  56001. };
  56002. return Node;
  56003. }());
  56004. var CSG = (function () {
  56005. function CSG() {
  56006. this.polygons = new Array();
  56007. }
  56008. // Convert BABYLON.Mesh to BABYLON.CSG
  56009. CSG.FromMesh = function (mesh) {
  56010. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  56011. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  56012. if (mesh instanceof BABYLON.Mesh) {
  56013. mesh.computeWorldMatrix(true);
  56014. matrix = mesh.getWorldMatrix();
  56015. meshPosition = mesh.position.clone();
  56016. meshRotation = mesh.rotation.clone();
  56017. if (mesh.rotationQuaternion) {
  56018. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  56019. }
  56020. meshScaling = mesh.scaling.clone();
  56021. }
  56022. else {
  56023. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  56024. }
  56025. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56026. var subMeshes = mesh.subMeshes;
  56027. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  56028. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  56029. vertices = [];
  56030. for (var j = 0; j < 3; j++) {
  56031. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  56032. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  56033. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  56034. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  56035. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  56036. vertex = new Vertex(position, normal, uv);
  56037. vertices.push(vertex);
  56038. }
  56039. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  56040. // To handle the case of degenerated triangle
  56041. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  56042. if (polygon.plane)
  56043. polygons.push(polygon);
  56044. }
  56045. }
  56046. var csg = CSG.FromPolygons(polygons);
  56047. csg.matrix = matrix;
  56048. csg.position = meshPosition;
  56049. csg.rotation = meshRotation;
  56050. csg.scaling = meshScaling;
  56051. csg.rotationQuaternion = meshRotationQuaternion;
  56052. currentCSGMeshId++;
  56053. return csg;
  56054. };
  56055. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  56056. CSG.FromPolygons = function (polygons) {
  56057. var csg = new CSG();
  56058. csg.polygons = polygons;
  56059. return csg;
  56060. };
  56061. CSG.prototype.clone = function () {
  56062. var csg = new CSG();
  56063. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  56064. csg.copyTransformAttributes(this);
  56065. return csg;
  56066. };
  56067. CSG.prototype.toPolygons = function () {
  56068. return this.polygons;
  56069. };
  56070. CSG.prototype.union = function (csg) {
  56071. var a = new Node(this.clone().polygons);
  56072. var b = new Node(csg.clone().polygons);
  56073. a.clipTo(b);
  56074. b.clipTo(a);
  56075. b.invert();
  56076. b.clipTo(a);
  56077. b.invert();
  56078. a.build(b.allPolygons());
  56079. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  56080. };
  56081. CSG.prototype.unionInPlace = function (csg) {
  56082. var a = new Node(this.polygons);
  56083. var b = new Node(csg.polygons);
  56084. a.clipTo(b);
  56085. b.clipTo(a);
  56086. b.invert();
  56087. b.clipTo(a);
  56088. b.invert();
  56089. a.build(b.allPolygons());
  56090. this.polygons = a.allPolygons();
  56091. };
  56092. CSG.prototype.subtract = function (csg) {
  56093. var a = new Node(this.clone().polygons);
  56094. var b = new Node(csg.clone().polygons);
  56095. a.invert();
  56096. a.clipTo(b);
  56097. b.clipTo(a);
  56098. b.invert();
  56099. b.clipTo(a);
  56100. b.invert();
  56101. a.build(b.allPolygons());
  56102. a.invert();
  56103. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  56104. };
  56105. CSG.prototype.subtractInPlace = function (csg) {
  56106. var a = new Node(this.polygons);
  56107. var b = new Node(csg.polygons);
  56108. a.invert();
  56109. a.clipTo(b);
  56110. b.clipTo(a);
  56111. b.invert();
  56112. b.clipTo(a);
  56113. b.invert();
  56114. a.build(b.allPolygons());
  56115. a.invert();
  56116. this.polygons = a.allPolygons();
  56117. };
  56118. CSG.prototype.intersect = function (csg) {
  56119. var a = new Node(this.clone().polygons);
  56120. var b = new Node(csg.clone().polygons);
  56121. a.invert();
  56122. b.clipTo(a);
  56123. b.invert();
  56124. a.clipTo(b);
  56125. b.clipTo(a);
  56126. a.build(b.allPolygons());
  56127. a.invert();
  56128. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  56129. };
  56130. CSG.prototype.intersectInPlace = function (csg) {
  56131. var a = new Node(this.polygons);
  56132. var b = new Node(csg.polygons);
  56133. a.invert();
  56134. b.clipTo(a);
  56135. b.invert();
  56136. a.clipTo(b);
  56137. b.clipTo(a);
  56138. a.build(b.allPolygons());
  56139. a.invert();
  56140. this.polygons = a.allPolygons();
  56141. };
  56142. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  56143. // not modified.
  56144. CSG.prototype.inverse = function () {
  56145. var csg = this.clone();
  56146. csg.inverseInPlace();
  56147. return csg;
  56148. };
  56149. CSG.prototype.inverseInPlace = function () {
  56150. this.polygons.map(function (p) { p.flip(); });
  56151. };
  56152. // This is used to keep meshes transformations so they can be restored
  56153. // when we build back a Babylon Mesh
  56154. // NB : All CSG operations are performed in world coordinates
  56155. CSG.prototype.copyTransformAttributes = function (csg) {
  56156. this.matrix = csg.matrix;
  56157. this.position = csg.position;
  56158. this.rotation = csg.rotation;
  56159. this.scaling = csg.scaling;
  56160. this.rotationQuaternion = csg.rotationQuaternion;
  56161. return this;
  56162. };
  56163. // Build Raw mesh from CSG
  56164. // Coordinates here are in world space
  56165. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  56166. var matrix = this.matrix.clone();
  56167. matrix.invert();
  56168. 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;
  56169. if (keepSubMeshes) {
  56170. // Sort Polygons, since subMeshes are indices range
  56171. polygons.sort(function (a, b) {
  56172. if (a.shared.meshId === b.shared.meshId) {
  56173. return a.shared.subMeshId - b.shared.subMeshId;
  56174. }
  56175. else {
  56176. return a.shared.meshId - b.shared.meshId;
  56177. }
  56178. });
  56179. }
  56180. for (var i = 0, il = polygons.length; i < il; i++) {
  56181. polygon = polygons[i];
  56182. // Building SubMeshes
  56183. if (!subMesh_dict[polygon.shared.meshId]) {
  56184. subMesh_dict[polygon.shared.meshId] = {};
  56185. }
  56186. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  56187. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  56188. indexStart: +Infinity,
  56189. indexEnd: -Infinity,
  56190. materialIndex: polygon.shared.materialIndex
  56191. };
  56192. }
  56193. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  56194. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  56195. polygonIndices[0] = 0;
  56196. polygonIndices[1] = j - 1;
  56197. polygonIndices[2] = j;
  56198. for (var k = 0; k < 3; k++) {
  56199. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  56200. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  56201. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  56202. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  56203. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  56204. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  56205. // Check if 2 points can be merged
  56206. if (!(typeof vertex_idx !== 'undefined' &&
  56207. normals[vertex_idx * 3] === localNormal.x &&
  56208. normals[vertex_idx * 3 + 1] === localNormal.y &&
  56209. normals[vertex_idx * 3 + 2] === localNormal.z &&
  56210. uvs[vertex_idx * 2] === uv.x &&
  56211. uvs[vertex_idx * 2 + 1] === uv.y)) {
  56212. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  56213. uvs.push(uv.x, uv.y);
  56214. normals.push(normal.x, normal.y, normal.z);
  56215. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  56216. }
  56217. indices.push(vertex_idx);
  56218. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  56219. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  56220. currentIndex++;
  56221. }
  56222. }
  56223. }
  56224. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  56225. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  56226. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  56227. mesh.setIndices(indices);
  56228. if (keepSubMeshes) {
  56229. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  56230. var materialIndexOffset = 0, materialMaxIndex;
  56231. mesh.subMeshes = new Array();
  56232. for (var m in subMesh_dict) {
  56233. materialMaxIndex = -1;
  56234. for (var sm in subMesh_dict[m]) {
  56235. subMesh_obj = subMesh_dict[m][sm];
  56236. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  56237. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  56238. }
  56239. materialIndexOffset += ++materialMaxIndex;
  56240. }
  56241. }
  56242. return mesh;
  56243. };
  56244. // Build Mesh from CSG taking material and transforms into account
  56245. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  56246. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  56247. mesh.material = material;
  56248. mesh.position.copyFrom(this.position);
  56249. mesh.rotation.copyFrom(this.rotation);
  56250. if (this.rotationQuaternion) {
  56251. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  56252. }
  56253. mesh.scaling.copyFrom(this.scaling);
  56254. mesh.computeWorldMatrix(true);
  56255. return mesh;
  56256. };
  56257. return CSG;
  56258. }());
  56259. BABYLON.CSG = CSG;
  56260. })(BABYLON || (BABYLON = {}));
  56261. //# sourceMappingURL=babylon.csg.js.map
  56262. var BABYLON;
  56263. (function (BABYLON) {
  56264. var LensFlare = (function () {
  56265. function LensFlare(size, position, color, imgUrl, system) {
  56266. this.size = size;
  56267. this.position = position;
  56268. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  56269. this.dispose = function () {
  56270. if (this.texture) {
  56271. this.texture.dispose();
  56272. }
  56273. // Remove from scene
  56274. var index = this._system.lensFlares.indexOf(this);
  56275. this._system.lensFlares.splice(index, 1);
  56276. };
  56277. this.color = color || new BABYLON.Color3(1, 1, 1);
  56278. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  56279. this._system = system;
  56280. system.lensFlares.push(this);
  56281. }
  56282. return LensFlare;
  56283. }());
  56284. BABYLON.LensFlare = LensFlare;
  56285. })(BABYLON || (BABYLON = {}));
  56286. //# sourceMappingURL=babylon.lensFlare.js.map
  56287. var BABYLON;
  56288. (function (BABYLON) {
  56289. var LensFlareSystem = (function () {
  56290. function LensFlareSystem(name, emitter, scene) {
  56291. this.name = name;
  56292. this.lensFlares = new Array();
  56293. this.borderLimit = 300;
  56294. this.viewportBorder = 0;
  56295. this.layerMask = 0x0FFFFFFF;
  56296. this._vertexBuffers = {};
  56297. this._isEnabled = true;
  56298. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56299. this._emitter = emitter;
  56300. this.id = name;
  56301. scene.lensFlareSystems.push(this);
  56302. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  56303. var engine = scene.getEngine();
  56304. // VBO
  56305. var vertices = [];
  56306. vertices.push(1, 1);
  56307. vertices.push(-1, 1);
  56308. vertices.push(-1, -1);
  56309. vertices.push(1, -1);
  56310. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  56311. // Indices
  56312. var indices = [];
  56313. indices.push(0);
  56314. indices.push(1);
  56315. indices.push(2);
  56316. indices.push(0);
  56317. indices.push(2);
  56318. indices.push(3);
  56319. this._indexBuffer = engine.createIndexBuffer(indices);
  56320. // Effects
  56321. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  56322. }
  56323. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  56324. get: function () {
  56325. return this._isEnabled;
  56326. },
  56327. set: function (value) {
  56328. this._isEnabled = value;
  56329. },
  56330. enumerable: true,
  56331. configurable: true
  56332. });
  56333. LensFlareSystem.prototype.getScene = function () {
  56334. return this._scene;
  56335. };
  56336. LensFlareSystem.prototype.getEmitter = function () {
  56337. return this._emitter;
  56338. };
  56339. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  56340. this._emitter = newEmitter;
  56341. };
  56342. LensFlareSystem.prototype.getEmitterPosition = function () {
  56343. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  56344. };
  56345. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  56346. var position = this.getEmitterPosition();
  56347. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  56348. this._positionX = position.x;
  56349. this._positionY = position.y;
  56350. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  56351. if (this.viewportBorder > 0) {
  56352. globalViewport.x -= this.viewportBorder;
  56353. globalViewport.y -= this.viewportBorder;
  56354. globalViewport.width += this.viewportBorder * 2;
  56355. globalViewport.height += this.viewportBorder * 2;
  56356. position.x += this.viewportBorder;
  56357. position.y += this.viewportBorder;
  56358. this._positionX += this.viewportBorder;
  56359. this._positionY += this.viewportBorder;
  56360. }
  56361. if (position.z > 0) {
  56362. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  56363. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  56364. return true;
  56365. }
  56366. return true;
  56367. }
  56368. return false;
  56369. };
  56370. LensFlareSystem.prototype._isVisible = function () {
  56371. if (!this._isEnabled) {
  56372. return false;
  56373. }
  56374. var emitterPosition = this.getEmitterPosition();
  56375. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  56376. var distance = direction.length();
  56377. direction.normalize();
  56378. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  56379. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  56380. return !pickInfo.hit || pickInfo.distance > distance;
  56381. };
  56382. LensFlareSystem.prototype.render = function () {
  56383. if (!this._effect.isReady())
  56384. return false;
  56385. var engine = this._scene.getEngine();
  56386. var viewport = this._scene.activeCamera.viewport;
  56387. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  56388. // Position
  56389. if (!this.computeEffectivePosition(globalViewport)) {
  56390. return false;
  56391. }
  56392. // Visibility
  56393. if (!this._isVisible()) {
  56394. return false;
  56395. }
  56396. // Intensity
  56397. var awayX;
  56398. var awayY;
  56399. if (this._positionX < this.borderLimit + globalViewport.x) {
  56400. awayX = this.borderLimit + globalViewport.x - this._positionX;
  56401. }
  56402. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  56403. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  56404. }
  56405. else {
  56406. awayX = 0;
  56407. }
  56408. if (this._positionY < this.borderLimit + globalViewport.y) {
  56409. awayY = this.borderLimit + globalViewport.y - this._positionY;
  56410. }
  56411. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  56412. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  56413. }
  56414. else {
  56415. awayY = 0;
  56416. }
  56417. var away = (awayX > awayY) ? awayX : awayY;
  56418. away -= this.viewportBorder;
  56419. if (away > this.borderLimit) {
  56420. away = this.borderLimit;
  56421. }
  56422. var intensity = 1.0 - (away / this.borderLimit);
  56423. if (intensity < 0) {
  56424. return false;
  56425. }
  56426. if (intensity > 1.0) {
  56427. intensity = 1.0;
  56428. }
  56429. if (this.viewportBorder > 0) {
  56430. globalViewport.x += this.viewportBorder;
  56431. globalViewport.y += this.viewportBorder;
  56432. globalViewport.width -= this.viewportBorder * 2;
  56433. globalViewport.height -= this.viewportBorder * 2;
  56434. this._positionX -= this.viewportBorder;
  56435. this._positionY -= this.viewportBorder;
  56436. }
  56437. // Position
  56438. var centerX = globalViewport.x + globalViewport.width / 2;
  56439. var centerY = globalViewport.y + globalViewport.height / 2;
  56440. var distX = centerX - this._positionX;
  56441. var distY = centerY - this._positionY;
  56442. // Effects
  56443. engine.enableEffect(this._effect);
  56444. engine.setState(false);
  56445. engine.setDepthBuffer(false);
  56446. // VBOs
  56447. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  56448. // Flares
  56449. for (var index = 0; index < this.lensFlares.length; index++) {
  56450. var flare = this.lensFlares[index];
  56451. engine.setAlphaMode(flare.alphaMode);
  56452. var x = centerX - (distX * flare.position);
  56453. var y = centerY - (distY * flare.position);
  56454. var cw = flare.size;
  56455. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  56456. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  56457. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  56458. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  56459. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  56460. // Texture
  56461. this._effect.setTexture("textureSampler", flare.texture);
  56462. // Color
  56463. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  56464. // Draw order
  56465. engine.draw(true, 0, 6);
  56466. }
  56467. engine.setDepthBuffer(true);
  56468. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56469. return true;
  56470. };
  56471. LensFlareSystem.prototype.dispose = function () {
  56472. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56473. if (vertexBuffer) {
  56474. vertexBuffer.dispose();
  56475. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  56476. }
  56477. if (this._indexBuffer) {
  56478. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56479. this._indexBuffer = null;
  56480. }
  56481. while (this.lensFlares.length) {
  56482. this.lensFlares[0].dispose();
  56483. }
  56484. // Remove from scene
  56485. var index = this._scene.lensFlareSystems.indexOf(this);
  56486. this._scene.lensFlareSystems.splice(index, 1);
  56487. };
  56488. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  56489. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  56490. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  56491. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  56492. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  56493. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  56494. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  56495. var parsedFlare = parsedLensFlareSystem.flares[index];
  56496. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  56497. }
  56498. return lensFlareSystem;
  56499. };
  56500. LensFlareSystem.prototype.serialize = function () {
  56501. var serializationObject = {};
  56502. serializationObject.id = this.id;
  56503. serializationObject.name = this.name;
  56504. serializationObject.emitterId = this.getEmitter().id;
  56505. serializationObject.borderLimit = this.borderLimit;
  56506. serializationObject.flares = [];
  56507. for (var index = 0; index < this.lensFlares.length; index++) {
  56508. var flare = this.lensFlares[index];
  56509. serializationObject.flares.push({
  56510. size: flare.size,
  56511. position: flare.position,
  56512. color: flare.color.asArray(),
  56513. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  56514. });
  56515. }
  56516. return serializationObject;
  56517. };
  56518. return LensFlareSystem;
  56519. }());
  56520. BABYLON.LensFlareSystem = LensFlareSystem;
  56521. })(BABYLON || (BABYLON = {}));
  56522. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  56523. var BABYLON;
  56524. (function (BABYLON) {
  56525. /**
  56526. * This is a holder class for the physics joint created by the physics plugin.
  56527. * It holds a set of functions to control the underlying joint.
  56528. */
  56529. var PhysicsJoint = (function () {
  56530. function PhysicsJoint(type, jointData) {
  56531. this.type = type;
  56532. this.jointData = jointData;
  56533. jointData.nativeParams = jointData.nativeParams || {};
  56534. }
  56535. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  56536. get: function () {
  56537. return this._physicsJoint;
  56538. },
  56539. set: function (newJoint) {
  56540. if (this._physicsJoint) {
  56541. //remove from the wolrd
  56542. }
  56543. this._physicsJoint = newJoint;
  56544. },
  56545. enumerable: true,
  56546. configurable: true
  56547. });
  56548. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  56549. set: function (physicsPlugin) {
  56550. this._physicsPlugin = physicsPlugin;
  56551. },
  56552. enumerable: true,
  56553. configurable: true
  56554. });
  56555. /**
  56556. * Execute a function that is physics-plugin specific.
  56557. * @param {Function} func the function that will be executed.
  56558. * It accepts two parameters: the physics world and the physics joint.
  56559. */
  56560. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  56561. func(this._physicsPlugin.world, this._physicsJoint);
  56562. };
  56563. return PhysicsJoint;
  56564. }());
  56565. //TODO check if the native joints are the same
  56566. //Joint Types
  56567. PhysicsJoint.DistanceJoint = 0;
  56568. PhysicsJoint.HingeJoint = 1;
  56569. PhysicsJoint.BallAndSocketJoint = 2;
  56570. PhysicsJoint.WheelJoint = 3;
  56571. PhysicsJoint.SliderJoint = 4;
  56572. //OIMO
  56573. PhysicsJoint.PrismaticJoint = 5;
  56574. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  56575. PhysicsJoint.UniversalJoint = 6;
  56576. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  56577. //Cannon
  56578. //Similar to a Ball-Joint. Different in params
  56579. PhysicsJoint.PointToPointJoint = 8;
  56580. //Cannon only at the moment
  56581. PhysicsJoint.SpringJoint = 9;
  56582. PhysicsJoint.LockJoint = 10;
  56583. BABYLON.PhysicsJoint = PhysicsJoint;
  56584. /**
  56585. * A class representing a physics distance joint.
  56586. */
  56587. var DistanceJoint = (function (_super) {
  56588. __extends(DistanceJoint, _super);
  56589. function DistanceJoint(jointData) {
  56590. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  56591. }
  56592. /**
  56593. * Update the predefined distance.
  56594. */
  56595. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  56596. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  56597. };
  56598. return DistanceJoint;
  56599. }(PhysicsJoint));
  56600. BABYLON.DistanceJoint = DistanceJoint;
  56601. var MotorEnabledJoint = (function (_super) {
  56602. __extends(MotorEnabledJoint, _super);
  56603. function MotorEnabledJoint(type, jointData) {
  56604. return _super.call(this, type, jointData) || this;
  56605. }
  56606. /**
  56607. * Set the motor values.
  56608. * Attention, this function is plugin specific. Engines won't react 100% the same.
  56609. * @param {number} force the force to apply
  56610. * @param {number} maxForce max force for this motor.
  56611. */
  56612. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  56613. this._physicsPlugin.setMotor(this, force, maxForce);
  56614. };
  56615. /**
  56616. * Set the motor's limits.
  56617. * Attention, this function is plugin specific. Engines won't react 100% the same.
  56618. */
  56619. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  56620. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  56621. };
  56622. return MotorEnabledJoint;
  56623. }(PhysicsJoint));
  56624. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  56625. /**
  56626. * This class represents a single hinge physics joint
  56627. */
  56628. var HingeJoint = (function (_super) {
  56629. __extends(HingeJoint, _super);
  56630. function HingeJoint(jointData) {
  56631. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  56632. }
  56633. /**
  56634. * Set the motor values.
  56635. * Attention, this function is plugin specific. Engines won't react 100% the same.
  56636. * @param {number} force the force to apply
  56637. * @param {number} maxForce max force for this motor.
  56638. */
  56639. HingeJoint.prototype.setMotor = function (force, maxForce) {
  56640. this._physicsPlugin.setMotor(this, force, maxForce);
  56641. };
  56642. /**
  56643. * Set the motor's limits.
  56644. * Attention, this function is plugin specific. Engines won't react 100% the same.
  56645. */
  56646. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  56647. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  56648. };
  56649. return HingeJoint;
  56650. }(MotorEnabledJoint));
  56651. BABYLON.HingeJoint = HingeJoint;
  56652. /**
  56653. * This class represents a dual hinge physics joint (same as wheel joint)
  56654. */
  56655. var Hinge2Joint = (function (_super) {
  56656. __extends(Hinge2Joint, _super);
  56657. function Hinge2Joint(jointData) {
  56658. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  56659. }
  56660. /**
  56661. * Set the motor values.
  56662. * Attention, this function is plugin specific. Engines won't react 100% the same.
  56663. * @param {number} force the force to apply
  56664. * @param {number} maxForce max force for this motor.
  56665. * @param {motorIndex} the motor's index, 0 or 1.
  56666. */
  56667. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  56668. if (motorIndex === void 0) { motorIndex = 0; }
  56669. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  56670. };
  56671. /**
  56672. * Set the motor limits.
  56673. * Attention, this function is plugin specific. Engines won't react 100% the same.
  56674. * @param {number} upperLimit the upper limit
  56675. * @param {number} lowerLimit lower limit
  56676. * @param {motorIndex} the motor's index, 0 or 1.
  56677. */
  56678. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  56679. if (motorIndex === void 0) { motorIndex = 0; }
  56680. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  56681. };
  56682. return Hinge2Joint;
  56683. }(MotorEnabledJoint));
  56684. BABYLON.Hinge2Joint = Hinge2Joint;
  56685. })(BABYLON || (BABYLON = {}));
  56686. //# sourceMappingURL=babylon.physicsJoint.js.map
  56687. var BABYLON;
  56688. (function (BABYLON) {
  56689. var PhysicsImpostor = (function () {
  56690. function PhysicsImpostor(object, type, _options, _scene) {
  56691. if (_options === void 0) { _options = { mass: 0 }; }
  56692. var _this = this;
  56693. this.object = object;
  56694. this.type = type;
  56695. this._options = _options;
  56696. this._scene = _scene;
  56697. this._bodyUpdateRequired = false;
  56698. this._onBeforePhysicsStepCallbacks = new Array();
  56699. this._onAfterPhysicsStepCallbacks = new Array();
  56700. this._onPhysicsCollideCallbacks = [];
  56701. this._deltaPosition = BABYLON.Vector3.Zero();
  56702. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  56703. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  56704. /**
  56705. * this function is executed by the physics engine.
  56706. */
  56707. this.beforeStep = function () {
  56708. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  56709. //conjugate deltaRotation
  56710. if (_this._deltaRotationConjugated) {
  56711. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  56712. }
  56713. else {
  56714. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  56715. }
  56716. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  56717. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  56718. func(_this);
  56719. });
  56720. };
  56721. /**
  56722. * this function is executed by the physics engine.
  56723. */
  56724. this.afterStep = function () {
  56725. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  56726. func(_this);
  56727. });
  56728. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  56729. _this.object.position.addInPlace(_this._deltaPosition);
  56730. if (_this._deltaRotation) {
  56731. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  56732. }
  56733. };
  56734. /**
  56735. * Legacy collision detection event support
  56736. */
  56737. this.onCollideEvent = null;
  56738. //event and body object due to cannon's event-based architecture.
  56739. this.onCollide = function (e) {
  56740. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  56741. return;
  56742. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  56743. if (otherImpostor) {
  56744. // Legacy collision detection event support
  56745. if (_this.onCollideEvent) {
  56746. _this.onCollideEvent(_this, otherImpostor);
  56747. }
  56748. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  56749. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  56750. }).forEach(function (obj) {
  56751. obj.callback(_this, otherImpostor);
  56752. });
  56753. }
  56754. };
  56755. //sanity check!
  56756. if (!this.object) {
  56757. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  56758. return;
  56759. }
  56760. //legacy support for old syntax.
  56761. if (!this._scene && object.getScene) {
  56762. this._scene = object.getScene();
  56763. }
  56764. this._physicsEngine = this._scene.getPhysicsEngine();
  56765. if (!this._physicsEngine) {
  56766. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  56767. }
  56768. else {
  56769. //set the object's quaternion, if not set
  56770. if (!this.object.rotationQuaternion) {
  56771. if (this.object.rotation) {
  56772. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  56773. }
  56774. else {
  56775. this.object.rotationQuaternion = new BABYLON.Quaternion();
  56776. }
  56777. }
  56778. //default options params
  56779. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  56780. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  56781. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  56782. this._joints = [];
  56783. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  56784. if (!this.object.parent) {
  56785. this._init();
  56786. }
  56787. else if (this.object.parent.physicsImpostor) {
  56788. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  56789. }
  56790. }
  56791. }
  56792. /**
  56793. * This function will completly initialize this impostor.
  56794. * It will create a new body - but only if this mesh has no parent.
  56795. * If it has, this impostor will not be used other than to define the impostor
  56796. * of the child mesh.
  56797. */
  56798. PhysicsImpostor.prototype._init = function () {
  56799. this._physicsEngine.removeImpostor(this);
  56800. this.physicsBody = null;
  56801. this._parent = this._parent || this._getPhysicsParent();
  56802. if (!this.parent) {
  56803. this._physicsEngine.addImpostor(this);
  56804. }
  56805. };
  56806. PhysicsImpostor.prototype._getPhysicsParent = function () {
  56807. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  56808. var parentMesh = this.object.parent;
  56809. return parentMesh.physicsImpostor;
  56810. }
  56811. return;
  56812. };
  56813. /**
  56814. * Should a new body be generated.
  56815. */
  56816. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  56817. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  56818. };
  56819. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  56820. this.forceUpdate();
  56821. };
  56822. /**
  56823. * Force a regeneration of this or the parent's impostor's body.
  56824. * Use under cautious - This will remove all joints already implemented.
  56825. */
  56826. PhysicsImpostor.prototype.forceUpdate = function () {
  56827. this._init();
  56828. if (this.parent) {
  56829. this.parent.forceUpdate();
  56830. }
  56831. };
  56832. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  56833. /*public get mesh(): AbstractMesh {
  56834. return this._mesh;
  56835. }*/
  56836. /**
  56837. * Gets the body that holds this impostor. Either its own, or its parent.
  56838. */
  56839. get: function () {
  56840. return this._parent ? this._parent.physicsBody : this._physicsBody;
  56841. },
  56842. /**
  56843. * Set the physics body. Used mainly by the physics engine/plugin
  56844. */
  56845. set: function (physicsBody) {
  56846. if (this._physicsBody) {
  56847. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  56848. }
  56849. this._physicsBody = physicsBody;
  56850. this.resetUpdateFlags();
  56851. },
  56852. enumerable: true,
  56853. configurable: true
  56854. });
  56855. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  56856. get: function () {
  56857. return this._parent;
  56858. },
  56859. set: function (value) {
  56860. this._parent = value;
  56861. },
  56862. enumerable: true,
  56863. configurable: true
  56864. });
  56865. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  56866. this._bodyUpdateRequired = false;
  56867. };
  56868. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  56869. if (this.object.getBoundingInfo) {
  56870. var q = this.object.rotationQuaternion;
  56871. //reset rotation
  56872. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  56873. //calculate the world matrix with no rotation
  56874. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  56875. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  56876. //bring back the rotation
  56877. this.object.rotationQuaternion = q;
  56878. //calculate the world matrix with the new rotation
  56879. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  56880. return size;
  56881. }
  56882. else {
  56883. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  56884. }
  56885. };
  56886. PhysicsImpostor.prototype.getObjectCenter = function () {
  56887. if (this.object.getBoundingInfo) {
  56888. return this.object.getBoundingInfo().boundingBox.centerWorld;
  56889. }
  56890. else {
  56891. return this.object.position;
  56892. }
  56893. };
  56894. /**
  56895. * Get a specific parametes from the options parameter.
  56896. */
  56897. PhysicsImpostor.prototype.getParam = function (paramName) {
  56898. return this._options[paramName];
  56899. };
  56900. /**
  56901. * Sets a specific parameter in the options given to the physics plugin
  56902. */
  56903. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  56904. this._options[paramName] = value;
  56905. this._bodyUpdateRequired = true;
  56906. };
  56907. /**
  56908. * Specifically change the body's mass option. Won't recreate the physics body object
  56909. */
  56910. PhysicsImpostor.prototype.setMass = function (mass) {
  56911. if (this.getParam("mass") !== mass) {
  56912. this.setParam("mass", mass);
  56913. }
  56914. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  56915. };
  56916. PhysicsImpostor.prototype.getLinearVelocity = function () {
  56917. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  56918. };
  56919. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  56920. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  56921. };
  56922. PhysicsImpostor.prototype.getAngularVelocity = function () {
  56923. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  56924. };
  56925. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  56926. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  56927. };
  56928. /**
  56929. * Execute a function with the physics plugin native code.
  56930. * Provide a function the will have two variables - the world object and the physics body object.
  56931. */
  56932. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  56933. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  56934. };
  56935. /**
  56936. * Register a function that will be executed before the physics world is stepping forward.
  56937. */
  56938. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  56939. this._onBeforePhysicsStepCallbacks.push(func);
  56940. };
  56941. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  56942. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  56943. if (index > -1) {
  56944. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  56945. }
  56946. else {
  56947. BABYLON.Tools.Warn("Function to remove was not found");
  56948. }
  56949. };
  56950. /**
  56951. * Register a function that will be executed after the physics step
  56952. */
  56953. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  56954. this._onAfterPhysicsStepCallbacks.push(func);
  56955. };
  56956. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  56957. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  56958. if (index > -1) {
  56959. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  56960. }
  56961. else {
  56962. BABYLON.Tools.Warn("Function to remove was not found");
  56963. }
  56964. };
  56965. /**
  56966. * register a function that will be executed when this impostor collides against a different body.
  56967. */
  56968. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  56969. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  56970. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  56971. };
  56972. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  56973. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  56974. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  56975. if (index > -1) {
  56976. this._onPhysicsCollideCallbacks.splice(index, 1);
  56977. }
  56978. else {
  56979. BABYLON.Tools.Warn("Function to remove was not found");
  56980. }
  56981. };
  56982. /**
  56983. * Apply a force
  56984. */
  56985. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  56986. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  56987. };
  56988. /**
  56989. * Apply an impulse
  56990. */
  56991. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  56992. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  56993. };
  56994. /**
  56995. * A help function to create a joint.
  56996. */
  56997. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  56998. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  56999. this.addJoint(otherImpostor, joint);
  57000. };
  57001. /**
  57002. * Add a joint to this impostor with a different impostor.
  57003. */
  57004. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  57005. this._joints.push({
  57006. otherImpostor: otherImpostor,
  57007. joint: joint
  57008. });
  57009. this._physicsEngine.addJoint(this, otherImpostor, joint);
  57010. };
  57011. /**
  57012. * Will keep this body still, in a sleep mode.
  57013. */
  57014. PhysicsImpostor.prototype.sleep = function () {
  57015. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  57016. };
  57017. /**
  57018. * Wake the body up.
  57019. */
  57020. PhysicsImpostor.prototype.wakeUp = function () {
  57021. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  57022. };
  57023. PhysicsImpostor.prototype.clone = function (newObject) {
  57024. if (!newObject)
  57025. return null;
  57026. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  57027. };
  57028. PhysicsImpostor.prototype.dispose = function () {
  57029. var _this = this;
  57030. //no dispose if no physics engine is available.
  57031. if (!this._physicsEngine) {
  57032. return;
  57033. }
  57034. this._joints.forEach(function (j) {
  57035. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  57036. });
  57037. //dispose the physics body
  57038. this._physicsEngine.removeImpostor(this);
  57039. if (this.parent) {
  57040. this.parent.forceUpdate();
  57041. }
  57042. else {
  57043. /*this._object.getChildMeshes().forEach(function(mesh) {
  57044. if (mesh.physicsImpostor) {
  57045. if (disposeChildren) {
  57046. mesh.physicsImpostor.dispose();
  57047. mesh.physicsImpostor = null;
  57048. }
  57049. }
  57050. })*/
  57051. }
  57052. };
  57053. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  57054. this._deltaPosition.copyFrom(position);
  57055. };
  57056. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  57057. if (!this._deltaRotation) {
  57058. this._deltaRotation = new BABYLON.Quaternion();
  57059. }
  57060. this._deltaRotation.copyFrom(rotation);
  57061. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  57062. };
  57063. return PhysicsImpostor;
  57064. }());
  57065. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  57066. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  57067. //Impostor types
  57068. PhysicsImpostor.NoImpostor = 0;
  57069. PhysicsImpostor.SphereImpostor = 1;
  57070. PhysicsImpostor.BoxImpostor = 2;
  57071. PhysicsImpostor.PlaneImpostor = 3;
  57072. PhysicsImpostor.MeshImpostor = 4;
  57073. PhysicsImpostor.CylinderImpostor = 7;
  57074. PhysicsImpostor.ParticleImpostor = 8;
  57075. PhysicsImpostor.HeightmapImpostor = 9;
  57076. BABYLON.PhysicsImpostor = PhysicsImpostor;
  57077. })(BABYLON || (BABYLON = {}));
  57078. //# sourceMappingURL=babylon.physicsImpostor.js.map
  57079. var BABYLON;
  57080. (function (BABYLON) {
  57081. var PhysicsEngine = (function () {
  57082. function PhysicsEngine(gravity, _physicsPlugin) {
  57083. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  57084. this._physicsPlugin = _physicsPlugin;
  57085. //new methods and parameters
  57086. this._impostors = [];
  57087. this._joints = [];
  57088. if (!this._physicsPlugin.isSupported()) {
  57089. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  57090. + "Please make sure it is included.");
  57091. }
  57092. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  57093. this.setGravity(gravity);
  57094. this.setTimeStep();
  57095. }
  57096. PhysicsEngine.prototype.setGravity = function (gravity) {
  57097. this.gravity = gravity;
  57098. this._physicsPlugin.setGravity(this.gravity);
  57099. };
  57100. /**
  57101. * Set the time step of the physics engine.
  57102. * default is 1/60.
  57103. * To slow it down, enter 1/600 for example.
  57104. * To speed it up, 1/30
  57105. * @param {number} newTimeStep the new timestep to apply to this world.
  57106. */
  57107. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  57108. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  57109. this._physicsPlugin.setTimeStep(newTimeStep);
  57110. };
  57111. PhysicsEngine.prototype.dispose = function () {
  57112. this._impostors.forEach(function (impostor) {
  57113. impostor.dispose();
  57114. });
  57115. this._physicsPlugin.dispose();
  57116. };
  57117. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  57118. return this._physicsPlugin.name;
  57119. };
  57120. /**
  57121. * Adding a new impostor for the impostor tracking.
  57122. * This will be done by the impostor itself.
  57123. * @param {PhysicsImpostor} impostor the impostor to add
  57124. */
  57125. PhysicsEngine.prototype.addImpostor = function (impostor) {
  57126. impostor.uniqueId = this._impostors.push(impostor);
  57127. //if no parent, generate the body
  57128. if (!impostor.parent) {
  57129. this._physicsPlugin.generatePhysicsBody(impostor);
  57130. }
  57131. };
  57132. /**
  57133. * Remove an impostor from the engine.
  57134. * This impostor and its mesh will not longer be updated by the physics engine.
  57135. * @param {PhysicsImpostor} impostor the impostor to remove
  57136. */
  57137. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  57138. var index = this._impostors.indexOf(impostor);
  57139. if (index > -1) {
  57140. var removed = this._impostors.splice(index, 1);
  57141. //Is it needed?
  57142. if (removed.length) {
  57143. //this will also remove it from the world.
  57144. removed[0].physicsBody = null;
  57145. }
  57146. }
  57147. };
  57148. /**
  57149. * Add a joint to the physics engine
  57150. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  57151. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  57152. * @param {PhysicsJoint} the joint that will connect both impostors.
  57153. */
  57154. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  57155. var impostorJoint = {
  57156. mainImpostor: mainImpostor,
  57157. connectedImpostor: connectedImpostor,
  57158. joint: joint
  57159. };
  57160. joint.physicsPlugin = this._physicsPlugin;
  57161. this._joints.push(impostorJoint);
  57162. this._physicsPlugin.generateJoint(impostorJoint);
  57163. };
  57164. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  57165. var matchingJoints = this._joints.filter(function (impostorJoint) {
  57166. return (impostorJoint.connectedImpostor === connectedImpostor
  57167. && impostorJoint.joint === joint
  57168. && impostorJoint.mainImpostor === mainImpostor);
  57169. });
  57170. if (matchingJoints.length) {
  57171. this._physicsPlugin.removeJoint(matchingJoints[0]);
  57172. //TODO remove it from the list as well
  57173. }
  57174. };
  57175. /**
  57176. * Called by the scene. no need to call it.
  57177. */
  57178. PhysicsEngine.prototype._step = function (delta) {
  57179. var _this = this;
  57180. //check if any mesh has no body / requires an update
  57181. this._impostors.forEach(function (impostor) {
  57182. if (impostor.isBodyInitRequired()) {
  57183. _this._physicsPlugin.generatePhysicsBody(impostor);
  57184. }
  57185. });
  57186. if (delta > 0.1) {
  57187. delta = 0.1;
  57188. }
  57189. else if (delta <= 0) {
  57190. delta = 1.0 / 60.0;
  57191. }
  57192. this._physicsPlugin.executeStep(delta, this._impostors);
  57193. };
  57194. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  57195. return this._physicsPlugin;
  57196. };
  57197. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  57198. for (var i = 0; i < this._impostors.length; ++i) {
  57199. if (this._impostors[i].object === object) {
  57200. return this._impostors[i];
  57201. }
  57202. }
  57203. };
  57204. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  57205. for (var i = 0; i < this._impostors.length; ++i) {
  57206. if (this._impostors[i].physicsBody === body) {
  57207. return this._impostors[i];
  57208. }
  57209. }
  57210. };
  57211. return PhysicsEngine;
  57212. }());
  57213. // Statics
  57214. PhysicsEngine.Epsilon = 0.001;
  57215. BABYLON.PhysicsEngine = PhysicsEngine;
  57216. })(BABYLON || (BABYLON = {}));
  57217. //# sourceMappingURL=babylon.physicsEngine.js.map
  57218. var BABYLON;
  57219. (function (BABYLON) {
  57220. var CannonJSPlugin = (function () {
  57221. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  57222. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  57223. if (iterations === void 0) { iterations = 10; }
  57224. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  57225. this.name = "CannonJSPlugin";
  57226. this._physicsMaterials = [];
  57227. this._fixedTimeStep = 1 / 60;
  57228. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  57229. this._currentCollisionGroup = 2;
  57230. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  57231. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  57232. this._tmpPosition = BABYLON.Vector3.Zero();
  57233. this._tmpQuaternion = new BABYLON.Quaternion();
  57234. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  57235. this._tmpDeltaRotation = new BABYLON.Quaternion();
  57236. this._tmpUnityRotation = new BABYLON.Quaternion();
  57237. if (!this.isSupported()) {
  57238. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  57239. return;
  57240. }
  57241. this.world = new CANNON.World();
  57242. this.world.broadphase = new CANNON.NaiveBroadphase();
  57243. this.world.solver.iterations = iterations;
  57244. }
  57245. CannonJSPlugin.prototype.setGravity = function (gravity) {
  57246. this.world.gravity.copy(gravity);
  57247. };
  57248. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  57249. this._fixedTimeStep = timeStep;
  57250. };
  57251. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  57252. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  57253. };
  57254. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  57255. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  57256. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  57257. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  57258. };
  57259. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  57260. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  57261. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  57262. impostor.physicsBody.applyForce(impulse, worldPoint);
  57263. };
  57264. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  57265. //parent-child relationship. Does this impostor has a parent impostor?
  57266. if (impostor.parent) {
  57267. if (impostor.physicsBody) {
  57268. this.removePhysicsBody(impostor);
  57269. //TODO is that needed?
  57270. impostor.forceUpdate();
  57271. }
  57272. return;
  57273. }
  57274. //should a new body be created for this impostor?
  57275. if (impostor.isBodyInitRequired()) {
  57276. var shape = this._createShape(impostor);
  57277. //unregister events, if body is being changed
  57278. var oldBody = impostor.physicsBody;
  57279. if (oldBody) {
  57280. this.removePhysicsBody(impostor);
  57281. }
  57282. //create the body and material
  57283. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  57284. var bodyCreationObject = {
  57285. mass: impostor.getParam("mass"),
  57286. material: material
  57287. };
  57288. // A simple extend, in case native options were used.
  57289. var nativeOptions = impostor.getParam("nativeOptions");
  57290. for (var key in nativeOptions) {
  57291. if (nativeOptions.hasOwnProperty(key)) {
  57292. bodyCreationObject[key] = nativeOptions[key];
  57293. }
  57294. }
  57295. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  57296. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  57297. this.world.addEventListener("preStep", impostor.beforeStep);
  57298. this.world.addEventListener("postStep", impostor.afterStep);
  57299. impostor.physicsBody.addShape(shape);
  57300. this.world.add(impostor.physicsBody);
  57301. //try to keep the body moving in the right direction by taking old properties.
  57302. //Should be tested!
  57303. if (oldBody) {
  57304. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  57305. impostor.physicsBody[param].copy(oldBody[param]);
  57306. });
  57307. }
  57308. this._processChildMeshes(impostor);
  57309. }
  57310. //now update the body's transformation
  57311. this._updatePhysicsBodyTransformation(impostor);
  57312. };
  57313. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  57314. var _this = this;
  57315. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  57316. if (meshChildren.length) {
  57317. var processMesh = function (localPosition, mesh) {
  57318. var childImpostor = mesh.getPhysicsImpostor();
  57319. if (childImpostor) {
  57320. var parent = childImpostor.parent;
  57321. if (parent !== mainImpostor) {
  57322. var localPosition = mesh.position;
  57323. if (childImpostor.physicsBody) {
  57324. _this.removePhysicsBody(childImpostor);
  57325. childImpostor.physicsBody = null;
  57326. }
  57327. childImpostor.parent = mainImpostor;
  57328. childImpostor.resetUpdateFlags();
  57329. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  57330. //Add the mass of the children.
  57331. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  57332. }
  57333. }
  57334. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  57335. };
  57336. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  57337. }
  57338. };
  57339. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  57340. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  57341. this.world.removeEventListener("preStep", impostor.beforeStep);
  57342. this.world.removeEventListener("postStep", impostor.afterStep);
  57343. this.world.remove(impostor.physicsBody);
  57344. };
  57345. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  57346. var mainBody = impostorJoint.mainImpostor.physicsBody;
  57347. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  57348. if (!mainBody || !connectedBody) {
  57349. return;
  57350. }
  57351. var constraint;
  57352. var jointData = impostorJoint.joint.jointData;
  57353. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  57354. var constraintData = {
  57355. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  57356. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  57357. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  57358. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  57359. maxForce: jointData.nativeParams.maxForce,
  57360. collideConnected: !!jointData.collision
  57361. };
  57362. switch (impostorJoint.joint.type) {
  57363. case BABYLON.PhysicsJoint.HingeJoint:
  57364. case BABYLON.PhysicsJoint.Hinge2Joint:
  57365. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  57366. break;
  57367. case BABYLON.PhysicsJoint.DistanceJoint:
  57368. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  57369. break;
  57370. case BABYLON.PhysicsJoint.SpringJoint:
  57371. var springData = jointData;
  57372. constraint = new CANNON.Spring(mainBody, connectedBody, {
  57373. restLength: springData.length,
  57374. stiffness: springData.stiffness,
  57375. damping: springData.damping,
  57376. localAnchorA: constraintData.pivotA,
  57377. localAnchorB: constraintData.pivotB
  57378. });
  57379. break;
  57380. case BABYLON.PhysicsJoint.LockJoint:
  57381. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  57382. break;
  57383. case BABYLON.PhysicsJoint.PointToPointJoint:
  57384. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  57385. default:
  57386. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  57387. break;
  57388. }
  57389. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  57390. constraint.collideConnected = !!jointData.collision;
  57391. impostorJoint.joint.physicsJoint = constraint;
  57392. //don't add spring as constraint, as it is not one.
  57393. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  57394. this.world.addConstraint(constraint);
  57395. }
  57396. else {
  57397. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  57398. constraint.applyForce();
  57399. });
  57400. }
  57401. };
  57402. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  57403. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  57404. };
  57405. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  57406. var index;
  57407. var mat;
  57408. for (index = 0; index < this._physicsMaterials.length; index++) {
  57409. mat = this._physicsMaterials[index];
  57410. if (mat.friction === friction && mat.restitution === restitution) {
  57411. return mat;
  57412. }
  57413. }
  57414. var currentMat = new CANNON.Material(name);
  57415. currentMat.friction = friction;
  57416. currentMat.restitution = restitution;
  57417. this._physicsMaterials.push(currentMat);
  57418. return currentMat;
  57419. };
  57420. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  57421. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  57422. };
  57423. CannonJSPlugin.prototype._createShape = function (impostor) {
  57424. var object = impostor.object;
  57425. var returnValue;
  57426. var extendSize = impostor.getObjectExtendSize();
  57427. switch (impostor.type) {
  57428. case BABYLON.PhysicsImpostor.SphereImpostor:
  57429. var radiusX = extendSize.x;
  57430. var radiusY = extendSize.y;
  57431. var radiusZ = extendSize.z;
  57432. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  57433. break;
  57434. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  57435. case BABYLON.PhysicsImpostor.CylinderImpostor:
  57436. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  57437. break;
  57438. case BABYLON.PhysicsImpostor.BoxImpostor:
  57439. var box = extendSize.scale(0.5);
  57440. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  57441. break;
  57442. case BABYLON.PhysicsImpostor.PlaneImpostor:
  57443. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  57444. returnValue = new CANNON.Plane();
  57445. break;
  57446. case BABYLON.PhysicsImpostor.MeshImpostor:
  57447. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  57448. var rawFaces = object.getIndices ? object.getIndices() : [];
  57449. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  57450. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  57451. break;
  57452. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  57453. returnValue = this._createHeightmap(object);
  57454. break;
  57455. case BABYLON.PhysicsImpostor.ParticleImpostor:
  57456. returnValue = new CANNON.Particle();
  57457. break;
  57458. }
  57459. return returnValue;
  57460. };
  57461. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  57462. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57463. var matrix = [];
  57464. //For now pointDepth will not be used and will be automatically calculated.
  57465. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  57466. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  57467. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  57468. var elementSize = dim * 2 / arraySize;
  57469. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  57470. for (var i = 0; i < pos.length; i = i + 3) {
  57471. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  57472. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  57473. var y = pos[i + 1] + minY;
  57474. if (!matrix[x]) {
  57475. matrix[x] = [];
  57476. }
  57477. if (!matrix[x][z]) {
  57478. matrix[x][z] = y;
  57479. }
  57480. matrix[x][z] = Math.max(y, matrix[x][z]);
  57481. }
  57482. for (var x = 0; x <= arraySize; ++x) {
  57483. if (!matrix[x]) {
  57484. var loc = 1;
  57485. while (!matrix[(x + loc) % arraySize]) {
  57486. loc++;
  57487. }
  57488. matrix[x] = matrix[(x + loc) % arraySize].slice();
  57489. //console.log("missing x", x);
  57490. }
  57491. for (var z = 0; z <= arraySize; ++z) {
  57492. if (!matrix[x][z]) {
  57493. var loc = 1;
  57494. var newValue;
  57495. while (newValue === undefined) {
  57496. newValue = matrix[x][(z + loc++) % arraySize];
  57497. }
  57498. matrix[x][z] = newValue;
  57499. }
  57500. }
  57501. }
  57502. var shape = new CANNON.Heightfield(matrix, {
  57503. elementSize: elementSize
  57504. });
  57505. //For future reference, needed for body transformation
  57506. shape.minY = minY;
  57507. return shape;
  57508. };
  57509. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  57510. var object = impostor.object;
  57511. //make sure it is updated...
  57512. object.computeWorldMatrix && object.computeWorldMatrix(true);
  57513. // The delta between the mesh position and the mesh bounding box center
  57514. var center = impostor.getObjectCenter();
  57515. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  57516. this._tmpPosition.copyFrom(center);
  57517. var quaternion = object.rotationQuaternion;
  57518. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  57519. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  57520. //-90 DEG in X, precalculated
  57521. quaternion = quaternion.multiply(this._minus90X);
  57522. //Invert! (Precalculated, 90 deg in X)
  57523. //No need to clone. this will never change.
  57524. impostor.setDeltaRotation(this._plus90X);
  57525. }
  57526. //If it is a heightfield, if should be centered.
  57527. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  57528. var mesh = object;
  57529. //calculate the correct body position:
  57530. var rotationQuaternion = mesh.rotationQuaternion;
  57531. mesh.rotationQuaternion = this._tmpUnityRotation;
  57532. mesh.computeWorldMatrix(true);
  57533. //get original center with no rotation
  57534. var c = center.clone();
  57535. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  57536. //rotation is back
  57537. mesh.rotationQuaternion = rotationQuaternion;
  57538. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  57539. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  57540. mesh.setPivotMatrix(p);
  57541. mesh.computeWorldMatrix(true);
  57542. //calculate the translation
  57543. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  57544. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  57545. //add it inverted to the delta
  57546. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  57547. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  57548. mesh.setPivotMatrix(oldPivot);
  57549. mesh.computeWorldMatrix(true);
  57550. }
  57551. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  57552. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  57553. this._tmpPosition.copyFrom(object.position);
  57554. }
  57555. impostor.setDeltaPosition(this._tmpDeltaPosition);
  57556. //Now update the impostor object
  57557. impostor.physicsBody.position.copy(this._tmpPosition);
  57558. impostor.physicsBody.quaternion.copy(quaternion);
  57559. };
  57560. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  57561. impostor.object.position.copyFrom(impostor.physicsBody.position);
  57562. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  57563. };
  57564. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  57565. impostor.physicsBody.position.copy(newPosition);
  57566. impostor.physicsBody.quaternion.copy(newRotation);
  57567. };
  57568. CannonJSPlugin.prototype.isSupported = function () {
  57569. return window.CANNON !== undefined;
  57570. };
  57571. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  57572. impostor.physicsBody.velocity.copy(velocity);
  57573. };
  57574. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  57575. impostor.physicsBody.angularVelocity.copy(velocity);
  57576. };
  57577. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  57578. var v = impostor.physicsBody.velocity;
  57579. if (!v)
  57580. return null;
  57581. return new BABYLON.Vector3(v.x, v.y, v.z);
  57582. };
  57583. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  57584. var v = impostor.physicsBody.angularVelocity;
  57585. if (!v)
  57586. return null;
  57587. return new BABYLON.Vector3(v.x, v.y, v.z);
  57588. };
  57589. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  57590. impostor.physicsBody.mass = mass;
  57591. impostor.physicsBody.updateMassProperties();
  57592. };
  57593. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  57594. impostor.physicsBody.sleep();
  57595. };
  57596. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  57597. impostor.physicsBody.wakeUp();
  57598. };
  57599. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  57600. joint.physicsJoint.distance = maxDistance;
  57601. };
  57602. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  57603. if (!motorIndex) {
  57604. joint.physicsJoint.enableMotor();
  57605. }
  57606. };
  57607. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  57608. if (!motorIndex) {
  57609. joint.physicsJoint.disableMotor();
  57610. }
  57611. };
  57612. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  57613. if (!motorIndex) {
  57614. joint.physicsJoint.enableMotor();
  57615. joint.physicsJoint.setMotorSpeed(speed);
  57616. if (maxForce) {
  57617. this.setLimit(joint, maxForce);
  57618. }
  57619. }
  57620. };
  57621. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  57622. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  57623. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  57624. };
  57625. CannonJSPlugin.prototype.dispose = function () {
  57626. //nothing to do, actually.
  57627. };
  57628. return CannonJSPlugin;
  57629. }());
  57630. BABYLON.CannonJSPlugin = CannonJSPlugin;
  57631. })(BABYLON || (BABYLON = {}));
  57632. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  57633. var BABYLON;
  57634. (function (BABYLON) {
  57635. var OimoJSPlugin = (function () {
  57636. function OimoJSPlugin(iterations) {
  57637. this.name = "OimoJSPlugin";
  57638. this._tmpImpostorsArray = [];
  57639. this._tmpPositionVector = BABYLON.Vector3.Zero();
  57640. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  57641. this.world.worldscale(1);
  57642. this.world.clear();
  57643. //making sure no stats are calculated
  57644. this.world.isNoStat = true;
  57645. }
  57646. OimoJSPlugin.prototype.setGravity = function (gravity) {
  57647. this.world.gravity.copy(gravity);
  57648. };
  57649. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  57650. this.world.timeStep = timeStep;
  57651. };
  57652. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  57653. var _this = this;
  57654. impostors.forEach(function (impostor) {
  57655. impostor.beforeStep();
  57656. });
  57657. this.world.step();
  57658. impostors.forEach(function (impostor) {
  57659. impostor.afterStep();
  57660. //update the ordered impostors array
  57661. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  57662. });
  57663. //check for collisions
  57664. var contact = this.world.contacts;
  57665. while (contact !== null) {
  57666. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  57667. contact = contact.next;
  57668. continue;
  57669. }
  57670. //is this body colliding with any other? get the impostor
  57671. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  57672. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  57673. if (!mainImpostor || !collidingImpostor) {
  57674. contact = contact.next;
  57675. continue;
  57676. }
  57677. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  57678. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  57679. contact = contact.next;
  57680. }
  57681. };
  57682. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  57683. var mass = impostor.physicsBody.massInfo.mass;
  57684. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  57685. };
  57686. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  57687. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  57688. this.applyImpulse(impostor, force, contactPoint);
  57689. };
  57690. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  57691. var _this = this;
  57692. //parent-child relationship. Does this impostor has a parent impostor?
  57693. if (impostor.parent) {
  57694. if (impostor.physicsBody) {
  57695. this.removePhysicsBody(impostor);
  57696. //TODO is that needed?
  57697. impostor.forceUpdate();
  57698. }
  57699. return;
  57700. }
  57701. if (impostor.isBodyInitRequired()) {
  57702. var bodyConfig = {
  57703. name: impostor.uniqueId,
  57704. //Oimo must have mass, also for static objects.
  57705. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  57706. size: [],
  57707. type: [],
  57708. pos: [],
  57709. rot: [],
  57710. move: impostor.getParam("mass") !== 0,
  57711. //Supporting older versions of Oimo
  57712. world: this.world
  57713. };
  57714. var impostors = [impostor];
  57715. var addToArray = function (parent) {
  57716. if (!parent.getChildMeshes)
  57717. return;
  57718. parent.getChildMeshes().forEach(function (m) {
  57719. if (m.physicsImpostor) {
  57720. impostors.push(m.physicsImpostor);
  57721. m.physicsImpostor._init();
  57722. }
  57723. });
  57724. };
  57725. addToArray(impostor.object);
  57726. var checkWithEpsilon_1 = function (value) {
  57727. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  57728. };
  57729. impostors.forEach(function (i) {
  57730. //get the correct bounding box
  57731. var oldQuaternion = i.object.rotationQuaternion;
  57732. var rot = new OIMO.Euler().setFromQuaternion({
  57733. x: impostor.object.rotationQuaternion.x,
  57734. y: impostor.object.rotationQuaternion.y,
  57735. z: impostor.object.rotationQuaternion.z,
  57736. s: impostor.object.rotationQuaternion.w
  57737. });
  57738. var extendSize = i.getObjectExtendSize();
  57739. if (i === impostor) {
  57740. var center = impostor.getObjectCenter();
  57741. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  57742. //Can also use Array.prototype.push.apply
  57743. bodyConfig.pos.push(center.x);
  57744. bodyConfig.pos.push(center.y);
  57745. bodyConfig.pos.push(center.z);
  57746. //tmp solution
  57747. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  57748. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  57749. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  57750. }
  57751. else {
  57752. bodyConfig.pos.push(i.object.position.x);
  57753. bodyConfig.pos.push(i.object.position.y);
  57754. bodyConfig.pos.push(i.object.position.z);
  57755. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  57756. bodyConfig.rot.push(0);
  57757. bodyConfig.rot.push(0);
  57758. bodyConfig.rot.push(0);
  57759. }
  57760. // register mesh
  57761. switch (i.type) {
  57762. case BABYLON.PhysicsImpostor.ParticleImpostor:
  57763. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  57764. case BABYLON.PhysicsImpostor.SphereImpostor:
  57765. var radiusX = extendSize.x;
  57766. var radiusY = extendSize.y;
  57767. var radiusZ = extendSize.z;
  57768. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  57769. bodyConfig.type.push('sphere');
  57770. //due to the way oimo works with compounds, add 3 times
  57771. bodyConfig.size.push(size);
  57772. bodyConfig.size.push(size);
  57773. bodyConfig.size.push(size);
  57774. break;
  57775. case BABYLON.PhysicsImpostor.CylinderImpostor:
  57776. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  57777. var sizeY = checkWithEpsilon_1(extendSize.y);
  57778. bodyConfig.type.push('cylinder');
  57779. bodyConfig.size.push(sizeX);
  57780. bodyConfig.size.push(sizeY);
  57781. //due to the way oimo works with compounds, add one more value.
  57782. bodyConfig.size.push(sizeY);
  57783. break;
  57784. case BABYLON.PhysicsImpostor.PlaneImpostor:
  57785. case BABYLON.PhysicsImpostor.BoxImpostor:
  57786. default:
  57787. var sizeX = checkWithEpsilon_1(extendSize.x);
  57788. var sizeY = checkWithEpsilon_1(extendSize.y);
  57789. var sizeZ = checkWithEpsilon_1(extendSize.z);
  57790. bodyConfig.type.push('box');
  57791. bodyConfig.size.push(sizeX);
  57792. bodyConfig.size.push(sizeY);
  57793. bodyConfig.size.push(sizeZ);
  57794. break;
  57795. }
  57796. //actually not needed, but hey...
  57797. i.object.rotationQuaternion = oldQuaternion;
  57798. });
  57799. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  57800. }
  57801. else {
  57802. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  57803. }
  57804. impostor.setDeltaPosition(this._tmpPositionVector);
  57805. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  57806. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  57807. };
  57808. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  57809. //impostor.physicsBody.dispose();
  57810. //Same as : (older oimo versions)
  57811. this.world.removeRigidBody(impostor.physicsBody);
  57812. };
  57813. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  57814. var mainBody = impostorJoint.mainImpostor.physicsBody;
  57815. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  57816. if (!mainBody || !connectedBody) {
  57817. return;
  57818. }
  57819. var jointData = impostorJoint.joint.jointData;
  57820. var options = jointData.nativeParams || {};
  57821. var type;
  57822. var nativeJointData = {
  57823. body1: mainBody,
  57824. body2: connectedBody,
  57825. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  57826. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  57827. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  57828. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  57829. min: options.min,
  57830. max: options.max,
  57831. collision: options.collision || jointData.collision,
  57832. spring: options.spring,
  57833. //supporting older version of Oimo
  57834. world: this.world
  57835. };
  57836. switch (impostorJoint.joint.type) {
  57837. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  57838. type = "jointBall";
  57839. break;
  57840. case BABYLON.PhysicsJoint.SpringJoint:
  57841. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  57842. var springData = jointData;
  57843. nativeJointData.min = springData.length || nativeJointData.min;
  57844. //Max should also be set, just make sure it is at least min
  57845. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  57846. case BABYLON.PhysicsJoint.DistanceJoint:
  57847. type = "jointDistance";
  57848. nativeJointData.max = jointData.maxDistance;
  57849. break;
  57850. case BABYLON.PhysicsJoint.PrismaticJoint:
  57851. type = "jointPrisme";
  57852. break;
  57853. case BABYLON.PhysicsJoint.SliderJoint:
  57854. type = "jointSlide";
  57855. break;
  57856. case BABYLON.PhysicsJoint.WheelJoint:
  57857. type = "jointWheel";
  57858. break;
  57859. case BABYLON.PhysicsJoint.HingeJoint:
  57860. default:
  57861. type = "jointHinge";
  57862. break;
  57863. }
  57864. nativeJointData.type = type;
  57865. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  57866. };
  57867. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  57868. //Bug in Oimo prevents us from disposing a joint in the playground
  57869. //joint.joint.physicsJoint.dispose();
  57870. //So we will bruteforce it!
  57871. try {
  57872. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  57873. }
  57874. catch (e) {
  57875. BABYLON.Tools.Warn(e);
  57876. }
  57877. };
  57878. OimoJSPlugin.prototype.isSupported = function () {
  57879. return OIMO !== undefined;
  57880. };
  57881. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  57882. if (!impostor.physicsBody.sleeping) {
  57883. //TODO check that
  57884. if (impostor.physicsBody.shapes.next) {
  57885. var parentShape = this._getLastShape(impostor.physicsBody);
  57886. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  57887. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  57888. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  57889. }
  57890. else {
  57891. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  57892. }
  57893. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  57894. impostor.object.rotationQuaternion.normalize();
  57895. }
  57896. };
  57897. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  57898. var body = impostor.physicsBody;
  57899. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  57900. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  57901. body.syncShapes();
  57902. body.awake();
  57903. };
  57904. OimoJSPlugin.prototype._getLastShape = function (body) {
  57905. var lastShape = body.shapes;
  57906. while (lastShape.next) {
  57907. lastShape = lastShape.next;
  57908. }
  57909. return lastShape;
  57910. };
  57911. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  57912. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  57913. };
  57914. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  57915. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  57916. };
  57917. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  57918. var v = impostor.physicsBody.linearVelocity;
  57919. if (!v)
  57920. return null;
  57921. return new BABYLON.Vector3(v.x, v.y, v.z);
  57922. };
  57923. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  57924. var v = impostor.physicsBody.angularVelocity;
  57925. if (!v)
  57926. return null;
  57927. return new BABYLON.Vector3(v.x, v.y, v.z);
  57928. };
  57929. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  57930. var staticBody = mass === 0;
  57931. //this will actually set the body's density and not its mass.
  57932. //But this is how oimo treats the mass variable.
  57933. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  57934. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  57935. };
  57936. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  57937. impostor.physicsBody.sleep();
  57938. };
  57939. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  57940. impostor.physicsBody.awake();
  57941. };
  57942. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  57943. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  57944. if (minDistance !== void 0) {
  57945. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  57946. }
  57947. };
  57948. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  57949. //TODO separate rotational and transational motors.
  57950. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  57951. if (motor) {
  57952. motor.setMotor(speed, maxForce);
  57953. }
  57954. };
  57955. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  57956. //TODO separate rotational and transational motors.
  57957. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  57958. if (motor) {
  57959. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  57960. }
  57961. };
  57962. OimoJSPlugin.prototype.dispose = function () {
  57963. this.world.clear();
  57964. };
  57965. return OimoJSPlugin;
  57966. }());
  57967. BABYLON.OimoJSPlugin = OimoJSPlugin;
  57968. })(BABYLON || (BABYLON = {}));
  57969. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  57970. var BABYLON;
  57971. (function (BABYLON) {
  57972. var Internals;
  57973. (function (Internals) {
  57974. /*
  57975. * Based on jsTGALoader - Javascript loader for TGA file
  57976. * By Vincent Thibault
  57977. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  57978. */
  57979. var TGATools = (function () {
  57980. function TGATools() {
  57981. }
  57982. TGATools.GetTGAHeader = function (data) {
  57983. var offset = 0;
  57984. var header = {
  57985. id_length: data[offset++],
  57986. colormap_type: data[offset++],
  57987. image_type: data[offset++],
  57988. colormap_index: data[offset++] | data[offset++] << 8,
  57989. colormap_length: data[offset++] | data[offset++] << 8,
  57990. colormap_size: data[offset++],
  57991. origin: [
  57992. data[offset++] | data[offset++] << 8,
  57993. data[offset++] | data[offset++] << 8
  57994. ],
  57995. width: data[offset++] | data[offset++] << 8,
  57996. height: data[offset++] | data[offset++] << 8,
  57997. pixel_size: data[offset++],
  57998. flags: data[offset++]
  57999. };
  58000. return header;
  58001. };
  58002. TGATools.UploadContent = function (gl, data) {
  58003. // Not enough data to contain header ?
  58004. if (data.length < 19) {
  58005. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  58006. return;
  58007. }
  58008. // Read Header
  58009. var offset = 18;
  58010. var header = TGATools.GetTGAHeader(data);
  58011. // Assume it's a valid Targa file.
  58012. if (header.id_length + offset > data.length) {
  58013. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  58014. return;
  58015. }
  58016. // Skip not needed data
  58017. offset += header.id_length;
  58018. var use_rle = false;
  58019. var use_pal = false;
  58020. var use_rgb = false;
  58021. var use_grey = false;
  58022. // Get some informations.
  58023. switch (header.image_type) {
  58024. case TGATools._TYPE_RLE_INDEXED:
  58025. use_rle = true;
  58026. case TGATools._TYPE_INDEXED:
  58027. use_pal = true;
  58028. break;
  58029. case TGATools._TYPE_RLE_RGB:
  58030. use_rle = true;
  58031. case TGATools._TYPE_RGB:
  58032. use_rgb = true;
  58033. break;
  58034. case TGATools._TYPE_RLE_GREY:
  58035. use_rle = true;
  58036. case TGATools._TYPE_GREY:
  58037. use_grey = true;
  58038. break;
  58039. }
  58040. var pixel_data;
  58041. var numAlphaBits = header.flags & 0xf;
  58042. var pixel_size = header.pixel_size >> 3;
  58043. var pixel_total = header.width * header.height * pixel_size;
  58044. // Read palettes
  58045. var palettes;
  58046. if (use_pal) {
  58047. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  58048. }
  58049. // Read LRE
  58050. if (use_rle) {
  58051. pixel_data = new Uint8Array(pixel_total);
  58052. var c, count, i;
  58053. var localOffset = 0;
  58054. var pixels = new Uint8Array(pixel_size);
  58055. while (offset < pixel_total && localOffset < pixel_total) {
  58056. c = data[offset++];
  58057. count = (c & 0x7f) + 1;
  58058. // RLE pixels
  58059. if (c & 0x80) {
  58060. // Bind pixel tmp array
  58061. for (i = 0; i < pixel_size; ++i) {
  58062. pixels[i] = data[offset++];
  58063. }
  58064. // Copy pixel array
  58065. for (i = 0; i < count; ++i) {
  58066. pixel_data.set(pixels, localOffset + i * pixel_size);
  58067. }
  58068. localOffset += pixel_size * count;
  58069. }
  58070. else {
  58071. count *= pixel_size;
  58072. for (i = 0; i < count; ++i) {
  58073. pixel_data[localOffset + i] = data[offset++];
  58074. }
  58075. localOffset += count;
  58076. }
  58077. }
  58078. }
  58079. else {
  58080. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  58081. }
  58082. // Load to texture
  58083. var x_start, y_start, x_step, y_step, y_end, x_end;
  58084. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  58085. default:
  58086. case TGATools._ORIGIN_UL:
  58087. x_start = 0;
  58088. x_step = 1;
  58089. x_end = header.width;
  58090. y_start = 0;
  58091. y_step = 1;
  58092. y_end = header.height;
  58093. break;
  58094. case TGATools._ORIGIN_BL:
  58095. x_start = 0;
  58096. x_step = 1;
  58097. x_end = header.width;
  58098. y_start = header.height - 1;
  58099. y_step = -1;
  58100. y_end = -1;
  58101. break;
  58102. case TGATools._ORIGIN_UR:
  58103. x_start = header.width - 1;
  58104. x_step = -1;
  58105. x_end = -1;
  58106. y_start = 0;
  58107. y_step = 1;
  58108. y_end = header.height;
  58109. break;
  58110. case TGATools._ORIGIN_BR:
  58111. x_start = header.width - 1;
  58112. x_step = -1;
  58113. x_end = -1;
  58114. y_start = header.height - 1;
  58115. y_step = -1;
  58116. y_end = -1;
  58117. break;
  58118. }
  58119. // Load the specify method
  58120. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  58121. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  58122. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  58123. };
  58124. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58125. var image = pixel_data, colormap = palettes;
  58126. var width = header.width, height = header.height;
  58127. var color, i = 0, x, y;
  58128. var imageData = new Uint8Array(width * height * 4);
  58129. for (y = y_start; y !== y_end; y += y_step) {
  58130. for (x = x_start; x !== x_end; x += x_step, i++) {
  58131. color = image[i];
  58132. imageData[(x + width * y) * 4 + 3] = 255;
  58133. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  58134. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  58135. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  58136. }
  58137. }
  58138. return imageData;
  58139. };
  58140. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58141. var image = pixel_data;
  58142. var width = header.width, height = header.height;
  58143. var color, i = 0, x, y;
  58144. var imageData = new Uint8Array(width * height * 4);
  58145. for (y = y_start; y !== y_end; y += y_step) {
  58146. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  58147. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  58148. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  58149. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  58150. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  58151. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  58152. }
  58153. }
  58154. return imageData;
  58155. };
  58156. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58157. var image = pixel_data;
  58158. var width = header.width, height = header.height;
  58159. var i = 0, x, y;
  58160. var imageData = new Uint8Array(width * height * 4);
  58161. for (y = y_start; y !== y_end; y += y_step) {
  58162. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  58163. imageData[(x + width * y) * 4 + 3] = 255;
  58164. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  58165. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  58166. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  58167. }
  58168. }
  58169. return imageData;
  58170. };
  58171. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58172. var image = pixel_data;
  58173. var width = header.width, height = header.height;
  58174. var i = 0, x, y;
  58175. var imageData = new Uint8Array(width * height * 4);
  58176. for (y = y_start; y !== y_end; y += y_step) {
  58177. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  58178. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  58179. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  58180. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  58181. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  58182. }
  58183. }
  58184. return imageData;
  58185. };
  58186. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58187. var image = pixel_data;
  58188. var width = header.width, height = header.height;
  58189. var color, i = 0, x, y;
  58190. var imageData = new Uint8Array(width * height * 4);
  58191. for (y = y_start; y !== y_end; y += y_step) {
  58192. for (x = x_start; x !== x_end; x += x_step, i++) {
  58193. color = image[i];
  58194. imageData[(x + width * y) * 4 + 0] = color;
  58195. imageData[(x + width * y) * 4 + 1] = color;
  58196. imageData[(x + width * y) * 4 + 2] = color;
  58197. imageData[(x + width * y) * 4 + 3] = 255;
  58198. }
  58199. }
  58200. return imageData;
  58201. };
  58202. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58203. var image = pixel_data;
  58204. var width = header.width, height = header.height;
  58205. var i = 0, x, y;
  58206. var imageData = new Uint8Array(width * height * 4);
  58207. for (y = y_start; y !== y_end; y += y_step) {
  58208. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  58209. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  58210. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  58211. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  58212. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  58213. }
  58214. }
  58215. return imageData;
  58216. };
  58217. return TGATools;
  58218. }());
  58219. TGATools._TYPE_NO_DATA = 0;
  58220. TGATools._TYPE_INDEXED = 1;
  58221. TGATools._TYPE_RGB = 2;
  58222. TGATools._TYPE_GREY = 3;
  58223. TGATools._TYPE_RLE_INDEXED = 9;
  58224. TGATools._TYPE_RLE_RGB = 10;
  58225. TGATools._TYPE_RLE_GREY = 11;
  58226. TGATools._ORIGIN_MASK = 0x30;
  58227. TGATools._ORIGIN_SHIFT = 0x04;
  58228. TGATools._ORIGIN_BL = 0x00;
  58229. TGATools._ORIGIN_BR = 0x01;
  58230. TGATools._ORIGIN_UL = 0x02;
  58231. TGATools._ORIGIN_UR = 0x03;
  58232. Internals.TGATools = TGATools;
  58233. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58234. })(BABYLON || (BABYLON = {}));
  58235. //# sourceMappingURL=babylon.tga.js.map
  58236. var BABYLON;
  58237. (function (BABYLON) {
  58238. var Internals;
  58239. (function (Internals) {
  58240. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  58241. // All values and structures referenced from:
  58242. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  58243. var DDS_MAGIC = 0x20534444;
  58244. 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;
  58245. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  58246. 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;
  58247. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  58248. function FourCCToInt32(value) {
  58249. return value.charCodeAt(0) +
  58250. (value.charCodeAt(1) << 8) +
  58251. (value.charCodeAt(2) << 16) +
  58252. (value.charCodeAt(3) << 24);
  58253. }
  58254. function Int32ToFourCC(value) {
  58255. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  58256. }
  58257. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  58258. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  58259. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  58260. var headerLengthInt = 31; // The header length in 32 bit ints
  58261. // Offsets into the header array
  58262. var off_magic = 0;
  58263. var off_size = 1;
  58264. var off_flags = 2;
  58265. var off_height = 3;
  58266. var off_width = 4;
  58267. var off_mipmapCount = 7;
  58268. var off_pfFlags = 20;
  58269. var off_pfFourCC = 21;
  58270. var off_RGBbpp = 22;
  58271. var off_RMask = 23;
  58272. var off_GMask = 24;
  58273. var off_BMask = 25;
  58274. var off_AMask = 26;
  58275. var off_caps1 = 27;
  58276. var off_caps2 = 28;
  58277. ;
  58278. var DDSTools = (function () {
  58279. function DDSTools() {
  58280. }
  58281. DDSTools.GetDDSInfo = function (arrayBuffer) {
  58282. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  58283. var mipmapCount = 1;
  58284. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  58285. mipmapCount = Math.max(1, header[off_mipmapCount]);
  58286. }
  58287. return {
  58288. width: header[off_width],
  58289. height: header[off_height],
  58290. mipmapCount: mipmapCount,
  58291. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  58292. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  58293. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  58294. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  58295. };
  58296. };
  58297. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  58298. var byteArray = new Uint8Array(dataLength);
  58299. var srcData = new Uint8Array(arrayBuffer);
  58300. var index = 0;
  58301. for (var y = height - 1; y >= 0; y--) {
  58302. for (var x = 0; x < width; x++) {
  58303. var srcPos = dataOffset + (x + y * width) * 4;
  58304. byteArray[index + 2] = srcData[srcPos];
  58305. byteArray[index + 1] = srcData[srcPos + 1];
  58306. byteArray[index] = srcData[srcPos + 2];
  58307. byteArray[index + 3] = srcData[srcPos + 3];
  58308. index += 4;
  58309. }
  58310. }
  58311. return byteArray;
  58312. };
  58313. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  58314. var byteArray = new Uint8Array(dataLength);
  58315. var srcData = new Uint8Array(arrayBuffer);
  58316. var index = 0;
  58317. for (var y = height - 1; y >= 0; y--) {
  58318. for (var x = 0; x < width; x++) {
  58319. var srcPos = dataOffset + (x + y * width) * 3;
  58320. byteArray[index + 2] = srcData[srcPos];
  58321. byteArray[index + 1] = srcData[srcPos + 1];
  58322. byteArray[index] = srcData[srcPos + 2];
  58323. index += 3;
  58324. }
  58325. }
  58326. return byteArray;
  58327. };
  58328. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  58329. var byteArray = new Uint8Array(dataLength);
  58330. var srcData = new Uint8Array(arrayBuffer);
  58331. var index = 0;
  58332. for (var y = height - 1; y >= 0; y--) {
  58333. for (var x = 0; x < width; x++) {
  58334. var srcPos = dataOffset + (x + y * width);
  58335. byteArray[index] = srcData[srcPos];
  58336. index++;
  58337. }
  58338. }
  58339. return byteArray;
  58340. };
  58341. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  58342. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  58343. if (header[off_magic] != DDS_MAGIC) {
  58344. BABYLON.Tools.Error("Invalid magic number in DDS header");
  58345. return;
  58346. }
  58347. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  58348. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  58349. return;
  58350. }
  58351. if (info.isFourCC) {
  58352. fourCC = header[off_pfFourCC];
  58353. switch (fourCC) {
  58354. case FOURCC_DXT1:
  58355. blockBytes = 8;
  58356. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  58357. break;
  58358. case FOURCC_DXT3:
  58359. blockBytes = 16;
  58360. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  58361. break;
  58362. case FOURCC_DXT5:
  58363. blockBytes = 16;
  58364. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  58365. break;
  58366. default:
  58367. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  58368. return;
  58369. }
  58370. }
  58371. mipmapCount = 1;
  58372. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  58373. mipmapCount = Math.max(1, header[off_mipmapCount]);
  58374. }
  58375. var bpp = header[off_RGBbpp];
  58376. for (var face = 0; face < faces; face++) {
  58377. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  58378. width = header[off_width];
  58379. height = header[off_height];
  58380. dataOffset = header[off_size] + 4;
  58381. for (i = 0; i < mipmapCount; ++i) {
  58382. if (info.isRGB) {
  58383. if (bpp === 24) {
  58384. dataLength = width * height * 3;
  58385. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  58386. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  58387. }
  58388. else {
  58389. dataLength = width * height * 4;
  58390. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  58391. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  58392. }
  58393. }
  58394. else if (info.isLuminance) {
  58395. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  58396. var unpaddedRowSize = width;
  58397. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  58398. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  58399. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  58400. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  58401. }
  58402. else {
  58403. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  58404. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  58405. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  58406. }
  58407. dataOffset += dataLength;
  58408. width *= 0.5;
  58409. height *= 0.5;
  58410. width = Math.max(1.0, width);
  58411. height = Math.max(1.0, height);
  58412. }
  58413. }
  58414. };
  58415. return DDSTools;
  58416. }());
  58417. Internals.DDSTools = DDSTools;
  58418. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58419. })(BABYLON || (BABYLON = {}));
  58420. //# sourceMappingURL=babylon.dds.js.map
  58421. var BABYLON;
  58422. (function (BABYLON) {
  58423. var Internals;
  58424. (function (Internals) {
  58425. /**
  58426. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  58427. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  58428. */
  58429. var KhronosTextureContainer = (function () {
  58430. /**
  58431. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  58432. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  58433. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  58434. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  58435. */
  58436. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  58437. this.arrayBuffer = arrayBuffer;
  58438. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  58439. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  58440. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  58441. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  58442. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  58443. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  58444. BABYLON.Tools.Error("texture missing KTX identifier");
  58445. return;
  58446. }
  58447. // load the reset of the header in native 32 bit int
  58448. var header = new Int32Array(this.arrayBuffer, 12, 13);
  58449. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  58450. var oppositeEndianess = header[0] === 0x01020304;
  58451. // read all the header elements in order they exist in the file, without modification (sans endainness)
  58452. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  58453. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  58454. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  58455. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  58456. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  58457. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  58458. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  58459. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  58460. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  58461. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  58462. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  58463. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  58464. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  58465. if (this.glType !== 0) {
  58466. BABYLON.Tools.Error("only compressed formats currently supported");
  58467. return;
  58468. }
  58469. else {
  58470. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  58471. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  58472. }
  58473. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  58474. BABYLON.Tools.Error("only 2D textures currently supported");
  58475. return;
  58476. }
  58477. if (this.numberOfArrayElements !== 0) {
  58478. BABYLON.Tools.Error("texture arrays not currently supported");
  58479. return;
  58480. }
  58481. if (this.numberOfFaces !== facesExpected) {
  58482. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  58483. return;
  58484. }
  58485. // we now have a completely validated file, so could use existence of loadType as success
  58486. // would need to make this more elaborate & adjust checks above to support more than one load type
  58487. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  58488. }
  58489. // not as fast hardware based, but will probably never need to use
  58490. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  58491. return ((val & 0xFF) << 24)
  58492. | ((val & 0xFF00) << 8)
  58493. | ((val >> 8) & 0xFF00)
  58494. | ((val >> 24) & 0xFF);
  58495. };
  58496. /**
  58497. * It is assumed that the texture has already been created & is currently bound
  58498. */
  58499. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  58500. switch (this.loadType) {
  58501. case KhronosTextureContainer.COMPRESSED_2D:
  58502. this._upload2DCompressedLevels(gl, loadMipmaps);
  58503. break;
  58504. case KhronosTextureContainer.TEX_2D:
  58505. case KhronosTextureContainer.COMPRESSED_3D:
  58506. case KhronosTextureContainer.TEX_3D:
  58507. }
  58508. };
  58509. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  58510. // initialize width & height for level 1
  58511. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  58512. var width = this.pixelWidth;
  58513. var height = this.pixelHeight;
  58514. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  58515. for (var level = 0; level < mipmapCount; level++) {
  58516. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  58517. for (var face = 0; face < this.numberOfFaces; face++) {
  58518. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  58519. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  58520. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  58521. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  58522. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  58523. }
  58524. width = Math.max(1.0, width * 0.5);
  58525. height = Math.max(1.0, height * 0.5);
  58526. }
  58527. };
  58528. return KhronosTextureContainer;
  58529. }());
  58530. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  58531. // load types
  58532. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  58533. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  58534. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  58535. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  58536. Internals.KhronosTextureContainer = KhronosTextureContainer;
  58537. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58538. })(BABYLON || (BABYLON = {}));
  58539. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  58540. var BABYLON;
  58541. (function (BABYLON) {
  58542. var DynamicFloatArrayElementInfo = (function () {
  58543. function DynamicFloatArrayElementInfo() {
  58544. }
  58545. return DynamicFloatArrayElementInfo;
  58546. }());
  58547. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  58548. /**
  58549. * 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.
  58550. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  58551. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  58552. * 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.
  58553. * 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.
  58554. * 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".
  58555. */
  58556. var DynamicFloatArray = (function () {
  58557. /**
  58558. * Construct an instance of the dynamic float array
  58559. * @param stride size of one element in float (i.e. not bytes!)
  58560. * @param initialElementCount the number of available entries at construction
  58561. */
  58562. function DynamicFloatArray(stride, initialElementCount) {
  58563. this.compareValueOffset = null;
  58564. this.sortingAscending = true;
  58565. this._stride = stride;
  58566. this.buffer = new Float32Array(stride * initialElementCount);
  58567. this._lastUsed = 0;
  58568. this._firstFree = 0;
  58569. this._allEntries = new Array(initialElementCount);
  58570. this._freeEntries = new Array(initialElementCount);
  58571. for (var i = 0; i < initialElementCount; i++) {
  58572. var element = new DynamicFloatArrayElementInfo();
  58573. element.offset = i * stride;
  58574. this._allEntries[i] = element;
  58575. this._freeEntries[initialElementCount - i - 1] = element;
  58576. }
  58577. }
  58578. /**
  58579. * Allocate an element in the array.
  58580. * @return the element info instance that contains the offset into the main buffer of the element's location.
  58581. * Beware, this offset may change when you call pack()
  58582. */
  58583. DynamicFloatArray.prototype.allocElement = function () {
  58584. if (this._freeEntries.length === 0) {
  58585. this._growBuffer();
  58586. }
  58587. var el = this._freeEntries.pop();
  58588. this._lastUsed = Math.max(el.offset, this._lastUsed);
  58589. if (el.offset === this._firstFree) {
  58590. if (this._freeEntries.length > 0) {
  58591. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  58592. }
  58593. else {
  58594. this._firstFree += this._stride;
  58595. }
  58596. }
  58597. return el;
  58598. };
  58599. /**
  58600. * Free the element corresponding to the given element info
  58601. * @param elInfo the element that describe the allocated element
  58602. */
  58603. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  58604. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  58605. this._freeEntries.push(elInfo);
  58606. };
  58607. /**
  58608. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  58609. * 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().
  58610. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  58611. */
  58612. DynamicFloatArray.prototype.pack = function () {
  58613. // no free slot? no need to pack
  58614. if (this._freeEntries.length === 0) {
  58615. return this.buffer;
  58616. }
  58617. // If the buffer is already packed the last used will always be lower than the first free
  58618. // 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.
  58619. if (this._lastUsed < this._firstFree) {
  58620. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  58621. return elementsBuffer_1;
  58622. }
  58623. var s = this._stride;
  58624. // 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
  58625. var lastFree = new DynamicFloatArrayElementInfo();
  58626. lastFree.offset = this.totalElementCount * s;
  58627. this._freeEntries.push(lastFree);
  58628. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  58629. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  58630. var firstFreeSlotOffset = sortedFree[0].offset;
  58631. var freeZoneSize = 1;
  58632. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  58633. var prevOffset = sortedFree[0].offset;
  58634. for (var i = 1; i < sortedFree.length; i++) {
  58635. // 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
  58636. if (firstFreeSlotOffset >= occupiedZoneSize) {
  58637. break;
  58638. }
  58639. var curFree = sortedFree[i];
  58640. var curOffset = curFree.offset;
  58641. // Compute the distance between this offset and the previous
  58642. var distance = curOffset - prevOffset;
  58643. // If the distance is the stride size, they are adjacent, it good, move to the next
  58644. if (distance === s) {
  58645. // Free zone is one element bigger
  58646. ++freeZoneSize;
  58647. // as we're about to iterate to the next, the cur becomes the previous...
  58648. prevOffset = curOffset;
  58649. continue;
  58650. }
  58651. // Distance is bigger, which means there's x element between the previous free and this one
  58652. var usedRange = (distance / s) - 1;
  58653. // Two cases the free zone is smaller than the data to move or bigger
  58654. // Copy what can fit in the free zone
  58655. var curMoveOffset = curOffset - s;
  58656. var copyCount = Math.min(freeZoneSize, usedRange);
  58657. for (var j = 0; j < copyCount; j++) {
  58658. var freeI = firstFreeSlotOffset / s;
  58659. var curI = curMoveOffset / s;
  58660. var moveEl = sortedAll[curI];
  58661. this._moveElement(moveEl, firstFreeSlotOffset);
  58662. var replacedEl = sortedAll[freeI];
  58663. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  58664. replacedEl.offset = curMoveOffset;
  58665. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  58666. sortedAll[freeI] = moveEl;
  58667. sortedAll[curI] = replacedEl;
  58668. curMoveOffset -= s;
  58669. firstFreeSlotOffset += s;
  58670. }
  58671. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  58672. if (freeZoneSize <= usedRange) {
  58673. firstFreeSlotOffset = curMoveOffset + s;
  58674. freeZoneSize = 1 + copyCount;
  58675. }
  58676. else {
  58677. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  58678. }
  58679. // as we're about to iterate to the next, the cur becomes the previous...
  58680. prevOffset = curOffset;
  58681. }
  58682. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  58683. this._lastUsed = firstFreeSlotOffset - s;
  58684. this._firstFree = firstFreeSlotOffset;
  58685. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  58686. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  58687. this._allEntries = sortedAll;
  58688. return elementsBuffer;
  58689. };
  58690. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  58691. for (var i = 0; i < this._stride; i++) {
  58692. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  58693. }
  58694. element.offset = destOffset;
  58695. };
  58696. DynamicFloatArray.prototype._growBuffer = function () {
  58697. // Allocate the new buffer with 50% more entries, copy the content of the current one
  58698. var newElCount = Math.floor(this.totalElementCount * 1.5);
  58699. var newBuffer = new Float32Array(newElCount * this._stride);
  58700. newBuffer.set(this.buffer);
  58701. var curCount = this.totalElementCount;
  58702. var addedCount = newElCount - this.totalElementCount;
  58703. for (var i = 0; i < addedCount; i++) {
  58704. var element = new DynamicFloatArrayElementInfo();
  58705. element.offset = (curCount + i) * this.stride;
  58706. this._allEntries.push(element);
  58707. this._freeEntries[addedCount - i - 1] = element;
  58708. }
  58709. this._firstFree = curCount * this.stride;
  58710. this.buffer = newBuffer;
  58711. };
  58712. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  58713. /**
  58714. * Get the total count of entries that can fit in the current buffer
  58715. * @returns the elements count
  58716. */
  58717. get: function () {
  58718. return this._allEntries.length;
  58719. },
  58720. enumerable: true,
  58721. configurable: true
  58722. });
  58723. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  58724. /**
  58725. * Get the count of free entries that can still be allocated without resizing the buffer
  58726. * @returns the free elements count
  58727. */
  58728. get: function () {
  58729. return this._freeEntries.length;
  58730. },
  58731. enumerable: true,
  58732. configurable: true
  58733. });
  58734. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  58735. /**
  58736. * Get the count of allocated elements
  58737. * @returns the allocated elements count
  58738. */
  58739. get: function () {
  58740. return this._allEntries.length - this._freeEntries.length;
  58741. },
  58742. enumerable: true,
  58743. configurable: true
  58744. });
  58745. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  58746. /**
  58747. * Return the size of one element in float
  58748. * @returns the size in float
  58749. */
  58750. get: function () {
  58751. return this._stride;
  58752. },
  58753. enumerable: true,
  58754. configurable: true
  58755. });
  58756. DynamicFloatArray.prototype.sort = function () {
  58757. var _this = this;
  58758. if (!this.compareValueOffset) {
  58759. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  58760. }
  58761. var count = this.usedElementCount;
  58762. // Do we have to (re)create the sort table?
  58763. if (!this._sortTable || this._sortTable.length < count) {
  58764. // 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...
  58765. var newCount = Math.min(this.totalElementCount, count * 2);
  58766. this._sortTable = new Array(newCount);
  58767. }
  58768. if (!this._sortedTable || this._sortedTable.length !== count) {
  58769. this._sortedTable = new Array(count);
  58770. }
  58771. // Because, you know...
  58772. this.pack();
  58773. //let stride = this.stride;
  58774. //for (let i = 0; i < count; i++) {
  58775. // let si = this._sortTable[i];
  58776. // if (!si) {
  58777. // si = new SortInfo();
  58778. // this._sortTable[i] = si;
  58779. // }
  58780. // si.entry = this._allEntries[i];
  58781. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  58782. // si.swapedOffset = null;
  58783. // this._sortedTable[i] = si;
  58784. //}
  58785. var curOffset = 0;
  58786. var stride = this.stride;
  58787. for (var i = 0; i < count; i++, curOffset += stride) {
  58788. var si = this._sortTable[i];
  58789. if (!si) {
  58790. si = new SortInfo();
  58791. this._sortTable[i] = si;
  58792. }
  58793. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  58794. si.offset = curOffset;
  58795. si.swapedOffset = null;
  58796. this._sortedTable[i] = si;
  58797. }
  58798. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  58799. if (this.sortingAscending) {
  58800. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  58801. }
  58802. else {
  58803. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  58804. }
  58805. var swapElements = function (src, dst) {
  58806. for (var i = 0; i < stride; i++) {
  58807. var tps = _this.buffer[dst + i];
  58808. _this.buffer[dst + i] = _this.buffer[src + i];
  58809. _this.buffer[src + i] = tps;
  58810. }
  58811. };
  58812. // 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:
  58813. // 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),
  58814. // and I still want something with a good algorithm complexity.
  58815. // 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,
  58816. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  58817. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  58818. // 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
  58819. // until we find a SortInfo object without a swapedOffset which means we got the right location
  58820. // 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
  58821. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  58822. for (var i = 0; i < count; i++) {
  58823. // Get the element to move
  58824. var sourceSI = this._sortedTable[i];
  58825. var destSI = this._sortTable[i];
  58826. var sourceOff = sourceSI.offset;
  58827. // If the source changed location, find the new one
  58828. if (sourceSI.swapedOffset) {
  58829. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  58830. var curSI = sourceSI;
  58831. while (curSI.swapedOffset) {
  58832. curSI = this._sortTable[curSI.swapedOffset / stride];
  58833. }
  58834. // Finally get the right location
  58835. sourceOff = curSI.offset;
  58836. }
  58837. // Tag the element being replaced with its new location
  58838. destSI.swapedOffset = sourceOff;
  58839. // Swap elements (only if needed)
  58840. if (sourceOff !== destSI.offset) {
  58841. swapElements(sourceOff, destSI.offset);
  58842. }
  58843. // Update the offset in the corresponding DFAE
  58844. //sourceSI.entry.offset = destSI.entry.offset;
  58845. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  58846. }
  58847. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  58848. return true;
  58849. };
  58850. return DynamicFloatArray;
  58851. }());
  58852. BABYLON.DynamicFloatArray = DynamicFloatArray;
  58853. var SortInfo = (function () {
  58854. function SortInfo() {
  58855. this.compareData = this.offset = this.swapedOffset = null;
  58856. }
  58857. return SortInfo;
  58858. }());
  58859. })(BABYLON || (BABYLON = {}));
  58860. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  58861. var BABYLON;
  58862. (function (BABYLON) {
  58863. var Debug;
  58864. (function (Debug) {
  58865. /**
  58866. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  58867. */
  58868. var SkeletonViewer = (function () {
  58869. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  58870. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58871. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58872. this.skeleton = skeleton;
  58873. this.mesh = mesh;
  58874. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58875. this.renderingGroupId = renderingGroupId;
  58876. this.color = BABYLON.Color3.White();
  58877. this._debugLines = [];
  58878. this._isEnabled = false;
  58879. this._scene = scene;
  58880. this.update();
  58881. this._renderFunction = this.update.bind(this);
  58882. }
  58883. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58884. get: function () {
  58885. return this._isEnabled;
  58886. },
  58887. set: function (value) {
  58888. if (this._isEnabled === value) {
  58889. return;
  58890. }
  58891. this._isEnabled = value;
  58892. if (value) {
  58893. this._scene.registerBeforeRender(this._renderFunction);
  58894. }
  58895. else {
  58896. this._scene.unregisterBeforeRender(this._renderFunction);
  58897. }
  58898. },
  58899. enumerable: true,
  58900. configurable: true
  58901. });
  58902. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58903. if (x === void 0) { x = 0; }
  58904. if (y === void 0) { y = 0; }
  58905. if (z === void 0) { z = 0; }
  58906. var tmat = BABYLON.Tmp.Matrix[0];
  58907. var parentBone = bone.getParent();
  58908. tmat.copyFrom(bone.getLocalMatrix());
  58909. if (x !== 0 || y !== 0 || z !== 0) {
  58910. var tmat2 = BABYLON.Tmp.Matrix[1];
  58911. BABYLON.Matrix.IdentityToRef(tmat2);
  58912. tmat2.m[12] = x;
  58913. tmat2.m[13] = y;
  58914. tmat2.m[14] = z;
  58915. tmat2.multiplyToRef(tmat, tmat);
  58916. }
  58917. if (parentBone) {
  58918. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58919. }
  58920. tmat.multiplyToRef(meshMat, tmat);
  58921. position.x = tmat.m[12];
  58922. position.y = tmat.m[13];
  58923. position.z = tmat.m[14];
  58924. };
  58925. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58926. var len = bones.length;
  58927. var meshPos = this.mesh.position;
  58928. for (var i = 0; i < len; i++) {
  58929. var bone = bones[i];
  58930. var points = this._debugLines[i];
  58931. if (!points) {
  58932. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58933. this._debugLines[i] = points;
  58934. }
  58935. this._getBonePosition(points[0], bone, meshMat);
  58936. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58937. points[0].subtractInPlace(meshPos);
  58938. points[1].subtractInPlace(meshPos);
  58939. }
  58940. };
  58941. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58942. var len = bones.length;
  58943. var boneNum = 0;
  58944. var meshPos = this.mesh.position;
  58945. for (var i = len - 1; i >= 0; i--) {
  58946. var childBone = bones[i];
  58947. var parentBone = childBone.getParent();
  58948. if (!parentBone) {
  58949. continue;
  58950. }
  58951. var points = this._debugLines[boneNum];
  58952. if (!points) {
  58953. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58954. this._debugLines[boneNum] = points;
  58955. }
  58956. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  58957. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  58958. points[0].subtractInPlace(meshPos);
  58959. points[1].subtractInPlace(meshPos);
  58960. boneNum++;
  58961. }
  58962. };
  58963. SkeletonViewer.prototype.update = function () {
  58964. if (this.autoUpdateBonesMatrices) {
  58965. this.skeleton.computeAbsoluteTransforms();
  58966. }
  58967. if (this.skeleton.bones[0].length === undefined) {
  58968. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58969. }
  58970. else {
  58971. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58972. }
  58973. if (!this._debugMesh) {
  58974. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  58975. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58976. }
  58977. else {
  58978. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58979. }
  58980. this._debugMesh.position.copyFrom(this.mesh.position);
  58981. this._debugMesh.color = this.color;
  58982. };
  58983. SkeletonViewer.prototype.dispose = function () {
  58984. if (this._debugMesh) {
  58985. this.isEnabled = false;
  58986. this._debugMesh.dispose();
  58987. this._debugMesh = null;
  58988. }
  58989. };
  58990. return SkeletonViewer;
  58991. }());
  58992. Debug.SkeletonViewer = SkeletonViewer;
  58993. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58994. })(BABYLON || (BABYLON = {}));
  58995. //# sourceMappingURL=babylon.skeletonViewer.js.map
  58996. var BABYLON;
  58997. (function (BABYLON) {
  58998. var Debug;
  58999. (function (Debug) {
  59000. var AxesViewer = (function () {
  59001. function AxesViewer(scene, scaleLines) {
  59002. if (scaleLines === void 0) { scaleLines = 1; }
  59003. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59004. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59005. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59006. this.scaleLines = 1;
  59007. this.scaleLines = scaleLines;
  59008. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  59009. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  59010. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  59011. this._xmesh.renderingGroupId = 2;
  59012. this._ymesh.renderingGroupId = 2;
  59013. this._zmesh.renderingGroupId = 2;
  59014. this._xmesh.material.checkReadyOnlyOnce = true;
  59015. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  59016. this._ymesh.material.checkReadyOnlyOnce = true;
  59017. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  59018. this._zmesh.material.checkReadyOnlyOnce = true;
  59019. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  59020. this.scene = scene;
  59021. }
  59022. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  59023. var scaleLines = this.scaleLines;
  59024. this._xmesh.position.copyFrom(position);
  59025. this._ymesh.position.copyFrom(position);
  59026. this._zmesh.position.copyFrom(position);
  59027. var point2 = this._xline[1];
  59028. point2.x = xaxis.x * scaleLines;
  59029. point2.y = xaxis.y * scaleLines;
  59030. point2.z = xaxis.z * scaleLines;
  59031. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  59032. point2 = this._yline[1];
  59033. point2.x = yaxis.x * scaleLines;
  59034. point2.y = yaxis.y * scaleLines;
  59035. point2.z = yaxis.z * scaleLines;
  59036. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  59037. point2 = this._zline[1];
  59038. point2.x = zaxis.x * scaleLines;
  59039. point2.y = zaxis.y * scaleLines;
  59040. point2.z = zaxis.z * scaleLines;
  59041. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  59042. };
  59043. AxesViewer.prototype.dispose = function () {
  59044. if (this._xmesh) {
  59045. this._xmesh.dispose();
  59046. this._ymesh.dispose();
  59047. this._zmesh.dispose();
  59048. this._xmesh = null;
  59049. this._ymesh = null;
  59050. this._zmesh = null;
  59051. this._xline = null;
  59052. this._yline = null;
  59053. this._zline = null;
  59054. this.scene = null;
  59055. }
  59056. };
  59057. return AxesViewer;
  59058. }());
  59059. Debug.AxesViewer = AxesViewer;
  59060. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59061. })(BABYLON || (BABYLON = {}));
  59062. //# sourceMappingURL=babylon.axesViewer.js.map
  59063. var BABYLON;
  59064. (function (BABYLON) {
  59065. var Debug;
  59066. (function (Debug) {
  59067. var BoneAxesViewer = (function (_super) {
  59068. __extends(BoneAxesViewer, _super);
  59069. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  59070. if (scaleLines === void 0) { scaleLines = 1; }
  59071. var _this = _super.call(this, scene, scaleLines) || this;
  59072. _this.pos = BABYLON.Vector3.Zero();
  59073. _this.xaxis = BABYLON.Vector3.Zero();
  59074. _this.yaxis = BABYLON.Vector3.Zero();
  59075. _this.zaxis = BABYLON.Vector3.Zero();
  59076. _this.mesh = mesh;
  59077. _this.bone = bone;
  59078. return _this;
  59079. }
  59080. BoneAxesViewer.prototype.update = function () {
  59081. var bone = this.bone;
  59082. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  59083. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  59084. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  59085. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  59086. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  59087. };
  59088. BoneAxesViewer.prototype.dispose = function () {
  59089. if (this.pos) {
  59090. this.pos = null;
  59091. this.xaxis = null;
  59092. this.yaxis = null;
  59093. this.zaxis = null;
  59094. this.mesh = null;
  59095. this.bone = null;
  59096. _super.prototype.dispose.call(this);
  59097. }
  59098. };
  59099. return BoneAxesViewer;
  59100. }(Debug.AxesViewer));
  59101. Debug.BoneAxesViewer = BoneAxesViewer;
  59102. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59103. })(BABYLON || (BABYLON = {}));
  59104. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  59105. var BABYLON;
  59106. (function (BABYLON) {
  59107. var RayHelper = (function () {
  59108. function RayHelper(ray) {
  59109. this.ray = ray;
  59110. }
  59111. RayHelper.CreateAndShow = function (ray, scene, color) {
  59112. var helper = new RayHelper(ray);
  59113. helper.show(scene, color);
  59114. return helper;
  59115. };
  59116. RayHelper.prototype.show = function (scene, color) {
  59117. if (!this._renderFunction) {
  59118. var ray = this.ray;
  59119. this._renderFunction = this._render.bind(this);
  59120. this._scene = scene;
  59121. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  59122. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  59123. this._scene.registerBeforeRender(this._renderFunction);
  59124. }
  59125. if (color) {
  59126. this._renderLine.color.copyFrom(color);
  59127. }
  59128. };
  59129. RayHelper.prototype.hide = function () {
  59130. if (this._renderFunction) {
  59131. this._scene.unregisterBeforeRender(this._renderFunction);
  59132. this._scene = null;
  59133. this._renderFunction = null;
  59134. this._renderLine.dispose();
  59135. this._renderLine = null;
  59136. this._renderPoints = null;
  59137. }
  59138. };
  59139. RayHelper.prototype._render = function () {
  59140. var ray = this.ray;
  59141. var point = this._renderPoints[1];
  59142. var len = Math.min(ray.length, 1000000);
  59143. point.copyFrom(ray.direction);
  59144. point.scaleInPlace(len);
  59145. point.addInPlace(ray.origin);
  59146. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  59147. };
  59148. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  59149. this._attachedToMesh = mesh;
  59150. var ray = this.ray;
  59151. if (!ray.direction) {
  59152. ray.direction = BABYLON.Vector3.Zero();
  59153. }
  59154. if (!ray.origin) {
  59155. ray.origin = BABYLON.Vector3.Zero();
  59156. }
  59157. if (length) {
  59158. ray.length = length;
  59159. }
  59160. if (!meshSpaceOrigin) {
  59161. meshSpaceOrigin = BABYLON.Vector3.Zero();
  59162. }
  59163. if (!meshSpaceDirection) {
  59164. // -1 so that this will work with Mesh.lookAt
  59165. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  59166. }
  59167. if (!this._meshSpaceDirection) {
  59168. this._meshSpaceDirection = meshSpaceDirection.clone();
  59169. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  59170. }
  59171. else {
  59172. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  59173. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  59174. }
  59175. if (!this._updateToMeshFunction) {
  59176. this._updateToMeshFunction = this._updateToMesh.bind(this);
  59177. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  59178. }
  59179. this._updateToMesh();
  59180. };
  59181. RayHelper.prototype.detachFromMesh = function () {
  59182. if (this._attachedToMesh) {
  59183. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  59184. this._attachedToMesh = null;
  59185. this._updateToMeshFunction = null;
  59186. }
  59187. };
  59188. RayHelper.prototype._updateToMesh = function () {
  59189. var ray = this.ray;
  59190. if (this._attachedToMesh._isDisposed) {
  59191. this.detachFromMesh();
  59192. return;
  59193. }
  59194. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  59195. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  59196. };
  59197. RayHelper.prototype.dispose = function () {
  59198. this.hide();
  59199. this.detachFromMesh();
  59200. this.ray = null;
  59201. };
  59202. return RayHelper;
  59203. }());
  59204. BABYLON.RayHelper = RayHelper;
  59205. })(BABYLON || (BABYLON = {}));
  59206. //# sourceMappingURL=babylon.rayHelper.js.map
  59207. var BABYLON;
  59208. (function (BABYLON) {
  59209. var DebugLayer = (function () {
  59210. function DebugLayer(scene) {
  59211. this._scene = scene;
  59212. }
  59213. /** Creates the inspector window. */
  59214. DebugLayer.prototype._createInspector = function (config) {
  59215. if (config === void 0) { config = {}; }
  59216. var popup = config.popup || false;
  59217. var initialTab = config.initialTab || 0;
  59218. var parentElement = config.parentElement || null;
  59219. if (!this._inspector) {
  59220. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  59221. } // else nothing to do,; instance is already existing
  59222. };
  59223. DebugLayer.prototype.isVisible = function () {
  59224. if (!this._inspector) {
  59225. return false;
  59226. }
  59227. return true;
  59228. };
  59229. DebugLayer.prototype.hide = function () {
  59230. if (this._inspector) {
  59231. try {
  59232. this._inspector.dispose();
  59233. }
  59234. catch (e) {
  59235. // If the inspector has been removed directly from the inspector tool
  59236. }
  59237. this._inspector = null;
  59238. }
  59239. };
  59240. DebugLayer.prototype.show = function (config) {
  59241. if (config === void 0) { config = {}; }
  59242. if (typeof INSPECTOR == 'undefined') {
  59243. // Load inspector and add it to the DOM
  59244. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  59245. }
  59246. else {
  59247. // Otherwise creates the inspector
  59248. this._createInspector(config);
  59249. }
  59250. };
  59251. return DebugLayer;
  59252. }());
  59253. // Get protocol used - http or https
  59254. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  59255. BABYLON.DebugLayer = DebugLayer;
  59256. })(BABYLON || (BABYLON = {}));
  59257. //# sourceMappingURL=babylon.debugLayer.js.map
  59258. var BABYLON;
  59259. (function (BABYLON) {
  59260. var BoundingBoxRenderer = (function () {
  59261. function BoundingBoxRenderer(scene) {
  59262. this.frontColor = new BABYLON.Color3(1, 1, 1);
  59263. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  59264. this.showBackLines = true;
  59265. this.renderList = new BABYLON.SmartArray(32);
  59266. this._vertexBuffers = {};
  59267. this._scene = scene;
  59268. }
  59269. BoundingBoxRenderer.prototype._prepareRessources = function () {
  59270. if (this._colorShader) {
  59271. return;
  59272. }
  59273. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  59274. attributes: [BABYLON.VertexBuffer.PositionKind],
  59275. uniforms: ["world", "viewProjection", "color"]
  59276. });
  59277. var engine = this._scene.getEngine();
  59278. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  59279. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  59280. 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]);
  59281. };
  59282. BoundingBoxRenderer.prototype.reset = function () {
  59283. this.renderList.reset();
  59284. };
  59285. BoundingBoxRenderer.prototype.render = function () {
  59286. if (this.renderList.length === 0) {
  59287. return;
  59288. }
  59289. this._prepareRessources();
  59290. if (!this._colorShader.isReady()) {
  59291. return;
  59292. }
  59293. var engine = this._scene.getEngine();
  59294. engine.setDepthWrite(false);
  59295. this._colorShader._preBind();
  59296. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  59297. var boundingBox = this.renderList.data[boundingBoxIndex];
  59298. var min = boundingBox.minimum;
  59299. var max = boundingBox.maximum;
  59300. var diff = max.subtract(min);
  59301. var median = min.add(diff.scale(0.5));
  59302. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59303. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59304. .multiply(boundingBox.getWorldMatrix());
  59305. // VBOs
  59306. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59307. if (this.showBackLines) {
  59308. // Back
  59309. engine.setDepthFunctionToGreaterOrEqual();
  59310. this._scene.resetCachedMaterial();
  59311. this._colorShader.setColor4("color", this.backColor.toColor4());
  59312. this._colorShader.bind(worldMatrix);
  59313. // Draw order
  59314. engine.draw(false, 0, 24);
  59315. }
  59316. // Front
  59317. engine.setDepthFunctionToLess();
  59318. this._scene.resetCachedMaterial();
  59319. this._colorShader.setColor4("color", this.frontColor.toColor4());
  59320. this._colorShader.bind(worldMatrix);
  59321. // Draw order
  59322. engine.draw(false, 0, 24);
  59323. }
  59324. this._colorShader.unbind();
  59325. engine.setDepthFunctionToLessOrEqual();
  59326. engine.setDepthWrite(true);
  59327. };
  59328. BoundingBoxRenderer.prototype.dispose = function () {
  59329. if (!this._colorShader) {
  59330. return;
  59331. }
  59332. this.renderList.dispose();
  59333. this._colorShader.dispose();
  59334. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59335. if (buffer) {
  59336. buffer.dispose();
  59337. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59338. }
  59339. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59340. };
  59341. return BoundingBoxRenderer;
  59342. }());
  59343. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  59344. })(BABYLON || (BABYLON = {}));
  59345. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  59346. var BABYLON;
  59347. (function (BABYLON) {
  59348. var MorphTarget = (function () {
  59349. function MorphTarget(name, influence) {
  59350. if (influence === void 0) { influence = 0; }
  59351. this.name = name;
  59352. this.animations = new Array();
  59353. this.onInfluenceChanged = new BABYLON.Observable();
  59354. this.influence = influence;
  59355. }
  59356. Object.defineProperty(MorphTarget.prototype, "influence", {
  59357. get: function () {
  59358. return this._influence;
  59359. },
  59360. set: function (influence) {
  59361. if (this._influence === influence) {
  59362. return;
  59363. }
  59364. var previous = this._influence;
  59365. this._influence = influence;
  59366. if (this.onInfluenceChanged.hasObservers) {
  59367. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  59368. }
  59369. },
  59370. enumerable: true,
  59371. configurable: true
  59372. });
  59373. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  59374. get: function () {
  59375. return this._normals !== undefined;
  59376. },
  59377. enumerable: true,
  59378. configurable: true
  59379. });
  59380. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  59381. get: function () {
  59382. return this._tangents !== undefined;
  59383. },
  59384. enumerable: true,
  59385. configurable: true
  59386. });
  59387. MorphTarget.prototype.setPositions = function (data) {
  59388. this._positions = new Float32Array(data);
  59389. };
  59390. MorphTarget.prototype.getPositions = function () {
  59391. return this._positions;
  59392. };
  59393. MorphTarget.prototype.setNormals = function (data) {
  59394. this._normals = new Float32Array(data);
  59395. };
  59396. MorphTarget.prototype.getNormals = function () {
  59397. return this._normals;
  59398. };
  59399. MorphTarget.prototype.setTangents = function (data) {
  59400. this._tangents = new Float32Array(data);
  59401. };
  59402. MorphTarget.prototype.getTangents = function () {
  59403. return this._tangents;
  59404. };
  59405. /**
  59406. * Serializes the current target into a Serialization object.
  59407. * Returns the serialized object.
  59408. */
  59409. MorphTarget.prototype.serialize = function () {
  59410. var serializationObject = {};
  59411. serializationObject.name = this.name;
  59412. serializationObject.influence = this.influence;
  59413. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  59414. if (this.hasNormals) {
  59415. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  59416. }
  59417. if (this.hasTangents) {
  59418. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  59419. }
  59420. return serializationObject;
  59421. };
  59422. // Statics
  59423. MorphTarget.Parse = function (serializationObject) {
  59424. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  59425. result.setPositions(serializationObject.positions);
  59426. if (serializationObject.normals) {
  59427. result.setNormals(serializationObject.normals);
  59428. }
  59429. if (serializationObject.tangents) {
  59430. result.setTangents(serializationObject.tangents);
  59431. }
  59432. return result;
  59433. };
  59434. MorphTarget.FromMesh = function (mesh, name, influence) {
  59435. if (!name) {
  59436. name = mesh.name;
  59437. }
  59438. var result = new MorphTarget(name, influence);
  59439. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  59440. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  59441. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  59442. }
  59443. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  59444. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  59445. }
  59446. return result;
  59447. };
  59448. return MorphTarget;
  59449. }());
  59450. BABYLON.MorphTarget = MorphTarget;
  59451. })(BABYLON || (BABYLON = {}));
  59452. //# sourceMappingURL=babylon.morphTarget.js.map
  59453. var BABYLON;
  59454. (function (BABYLON) {
  59455. var MorphTargetManager = (function () {
  59456. function MorphTargetManager(scene) {
  59457. this._targets = new Array();
  59458. this._targetObservable = new Array();
  59459. this._activeTargets = new BABYLON.SmartArray(16);
  59460. this._supportsNormals = false;
  59461. this._supportsTangents = false;
  59462. this._vertexCount = 0;
  59463. this._uniqueId = 0;
  59464. if (!scene) {
  59465. scene = BABYLON.Engine.LastCreatedScene;
  59466. }
  59467. this._scene = scene;
  59468. this._scene.morphTargetManagers.push(this);
  59469. this._uniqueId = scene.getUniqueId();
  59470. }
  59471. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  59472. get: function () {
  59473. return this._uniqueId;
  59474. },
  59475. enumerable: true,
  59476. configurable: true
  59477. });
  59478. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  59479. get: function () {
  59480. return this._vertexCount;
  59481. },
  59482. enumerable: true,
  59483. configurable: true
  59484. });
  59485. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  59486. get: function () {
  59487. return this._supportsNormals;
  59488. },
  59489. enumerable: true,
  59490. configurable: true
  59491. });
  59492. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  59493. get: function () {
  59494. return this._supportsTangents;
  59495. },
  59496. enumerable: true,
  59497. configurable: true
  59498. });
  59499. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  59500. get: function () {
  59501. return this._targets.length;
  59502. },
  59503. enumerable: true,
  59504. configurable: true
  59505. });
  59506. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  59507. get: function () {
  59508. return this._activeTargets.length;
  59509. },
  59510. enumerable: true,
  59511. configurable: true
  59512. });
  59513. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  59514. get: function () {
  59515. return this._influences;
  59516. },
  59517. enumerable: true,
  59518. configurable: true
  59519. });
  59520. MorphTargetManager.prototype.getActiveTarget = function (index) {
  59521. return this._activeTargets.data[index];
  59522. };
  59523. MorphTargetManager.prototype.getTarget = function (index) {
  59524. return this._targets[index];
  59525. };
  59526. MorphTargetManager.prototype.addTarget = function (target) {
  59527. var _this = this;
  59528. if (this._vertexCount) {
  59529. if (this._vertexCount !== target.getPositions().length / 3) {
  59530. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  59531. return;
  59532. }
  59533. }
  59534. this._targets.push(target);
  59535. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  59536. _this._syncActiveTargets(needUpdate);
  59537. }));
  59538. this._syncActiveTargets(true);
  59539. };
  59540. MorphTargetManager.prototype.removeTarget = function (target) {
  59541. var index = this._targets.indexOf(target);
  59542. if (index >= 0) {
  59543. this._targets.splice(index, 1);
  59544. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  59545. this._vertexCount = 0;
  59546. this._syncActiveTargets(true);
  59547. }
  59548. };
  59549. /**
  59550. * Serializes the current manager into a Serialization object.
  59551. * Returns the serialized object.
  59552. */
  59553. MorphTargetManager.prototype.serialize = function () {
  59554. var serializationObject = {};
  59555. serializationObject.id = this.uniqueId;
  59556. serializationObject.targets = [];
  59557. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  59558. var target = _a[_i];
  59559. serializationObject.targets.push(target.serialize());
  59560. }
  59561. return serializationObject;
  59562. };
  59563. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  59564. this._syncActiveTargets(needUpdate);
  59565. };
  59566. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  59567. this._activeTargets.reset();
  59568. var tempInfluences = [];
  59569. this._supportsNormals = true;
  59570. this._supportsTangents = true;
  59571. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  59572. var target = _a[_i];
  59573. if (target.influence > 0) {
  59574. this._activeTargets.push(target);
  59575. tempInfluences.push(target.influence);
  59576. this._supportsNormals = this._supportsNormals && target.hasNormals;
  59577. this._supportsTangents = this._supportsTangents && target.hasTangents;
  59578. if (this._vertexCount === 0) {
  59579. this._vertexCount = target.getPositions().length / 3;
  59580. }
  59581. }
  59582. }
  59583. this._influences = new Float32Array(tempInfluences);
  59584. if (needUpdate) {
  59585. // Flag meshes as dirty to resync with the active targets
  59586. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  59587. var mesh = _c[_b];
  59588. if (mesh.morphTargetManager === this) {
  59589. mesh._syncGeometryWithMorphTargetManager();
  59590. }
  59591. }
  59592. }
  59593. };
  59594. // Statics
  59595. MorphTargetManager.Parse = function (serializationObject, scene) {
  59596. var result = new MorphTargetManager(scene);
  59597. result._uniqueId = serializationObject.id;
  59598. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  59599. var targetData = _a[_i];
  59600. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  59601. }
  59602. return result;
  59603. };
  59604. return MorphTargetManager;
  59605. }());
  59606. BABYLON.MorphTargetManager = MorphTargetManager;
  59607. })(BABYLON || (BABYLON = {}));
  59608. //# sourceMappingURL=babylon.morphTargetManager.js.map
  59609. var BABYLON;
  59610. (function (BABYLON) {
  59611. /**
  59612. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  59613. * It can help converting any input color in a desired output one. This can then be used to create effects
  59614. * from sepia, black and white to sixties or futuristic rendering...
  59615. *
  59616. * The only supported format is currently 3dl.
  59617. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  59618. */
  59619. var ColorGradingTexture = (function (_super) {
  59620. __extends(ColorGradingTexture, _super);
  59621. /**
  59622. * Instantiates a ColorGradingTexture from the following parameters.
  59623. *
  59624. * @param url The location of the color gradind data (currently only supporting 3dl)
  59625. * @param scene The scene the texture will be used in
  59626. */
  59627. function ColorGradingTexture(url, scene) {
  59628. var _this = _super.call(this, scene) || this;
  59629. if (!url) {
  59630. return _this;
  59631. }
  59632. _this._textureMatrix = BABYLON.Matrix.Identity();
  59633. _this.name = url;
  59634. _this.url = url;
  59635. _this.hasAlpha = false;
  59636. _this.isCube = false;
  59637. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59638. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59639. _this.anisotropicFilteringLevel = 1;
  59640. _this._texture = _this._getFromCache(url, true);
  59641. if (!_this._texture) {
  59642. if (!scene.useDelayedTextureLoading) {
  59643. _this.loadTexture();
  59644. }
  59645. else {
  59646. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59647. }
  59648. }
  59649. return _this;
  59650. }
  59651. /**
  59652. * Returns the texture matrix used in most of the material.
  59653. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  59654. */
  59655. ColorGradingTexture.prototype.getTextureMatrix = function () {
  59656. return this._textureMatrix;
  59657. };
  59658. /**
  59659. * Occurs when the file being loaded is a .3dl LUT file.
  59660. */
  59661. ColorGradingTexture.prototype.load3dlTexture = function () {
  59662. var _this = this;
  59663. var mipLevels = 0;
  59664. var floatArrayView = null;
  59665. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59666. this._texture = texture;
  59667. var callback = function (text) {
  59668. var data;
  59669. var tempData;
  59670. var line;
  59671. var lines = text.split('\n');
  59672. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  59673. var maxColor = 0;
  59674. for (var i = 0; i < lines.length; i++) {
  59675. line = lines[i];
  59676. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  59677. continue;
  59678. if (line.indexOf('#') === 0)
  59679. continue;
  59680. var words = line.split(" ");
  59681. if (size === 0) {
  59682. // Number of space + one
  59683. size = words.length;
  59684. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  59685. tempData = new Float32Array(size * size * size * 4);
  59686. continue;
  59687. }
  59688. if (size != 0) {
  59689. var r = Math.max(parseInt(words[0]), 0);
  59690. var g = Math.max(parseInt(words[1]), 0);
  59691. var b = Math.max(parseInt(words[2]), 0);
  59692. maxColor = Math.max(r, maxColor);
  59693. maxColor = Math.max(g, maxColor);
  59694. maxColor = Math.max(b, maxColor);
  59695. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  59696. tempData[pixelStorageIndex + 0] = r;
  59697. tempData[pixelStorageIndex + 1] = g;
  59698. tempData[pixelStorageIndex + 2] = b;
  59699. tempData[pixelStorageIndex + 3] = 0;
  59700. pixelIndexSlice++;
  59701. if (pixelIndexSlice % size == 0) {
  59702. pixelIndexH++;
  59703. pixelIndexSlice = 0;
  59704. if (pixelIndexH % size == 0) {
  59705. pixelIndexW++;
  59706. pixelIndexH = 0;
  59707. }
  59708. }
  59709. }
  59710. }
  59711. for (var i = 0; i < tempData.length; i++) {
  59712. var value = tempData[i];
  59713. data[i] = (value / maxColor * 255);
  59714. }
  59715. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  59716. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  59717. };
  59718. BABYLON.Tools.LoadFile(this.url, callback);
  59719. return this._texture;
  59720. };
  59721. /**
  59722. * Starts the loading process of the texture.
  59723. */
  59724. ColorGradingTexture.prototype.loadTexture = function () {
  59725. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  59726. this.load3dlTexture();
  59727. }
  59728. };
  59729. /**
  59730. * Clones the color gradind texture.
  59731. */
  59732. ColorGradingTexture.prototype.clone = function () {
  59733. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  59734. // Base texture
  59735. newTexture.level = this.level;
  59736. return newTexture;
  59737. };
  59738. /**
  59739. * Called during delayed load for textures.
  59740. */
  59741. ColorGradingTexture.prototype.delayLoad = function () {
  59742. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59743. return;
  59744. }
  59745. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59746. this._texture = this._getFromCache(this.url, true);
  59747. if (!this._texture) {
  59748. this.loadTexture();
  59749. }
  59750. };
  59751. /**
  59752. * Binds the color grading to the shader.
  59753. * @param colorGrading The texture to bind
  59754. * @param effect The effect to bind to
  59755. */
  59756. ColorGradingTexture.Bind = function (colorGrading, effect) {
  59757. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  59758. var x = colorGrading.level; // Texture Level
  59759. var y = colorGrading.getSize().height; // Texture Size example with 8
  59760. var z = y - 1.0; // SizeMinusOne 8 - 1
  59761. var w = 1 / y; // Space of 1 slice 1 / 8
  59762. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  59763. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  59764. 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
  59765. 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
  59766. 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
  59767. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  59768. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  59769. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  59770. };
  59771. /**
  59772. * Prepare the list of uniforms associated with the ColorGrading effects.
  59773. * @param uniformsList The list of uniforms used in the effect
  59774. * @param samplersList The list of samplers used in the effect
  59775. */
  59776. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  59777. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  59778. samplersList.push("cameraColorGrading2DSampler");
  59779. };
  59780. /**
  59781. * Parses a color grading texture serialized by Babylon.
  59782. * @param parsedTexture The texture information being parsedTexture
  59783. * @param scene The scene to load the texture in
  59784. * @param rootUrl The root url of the data assets to load
  59785. * @return A color gradind texture
  59786. */
  59787. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59788. var texture = null;
  59789. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  59790. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  59791. texture.name = parsedTexture.name;
  59792. texture.level = parsedTexture.level;
  59793. }
  59794. return texture;
  59795. };
  59796. /**
  59797. * Serializes the LUT texture to json format.
  59798. */
  59799. ColorGradingTexture.prototype.serialize = function () {
  59800. if (!this.name) {
  59801. return null;
  59802. }
  59803. var serializationObject = {};
  59804. serializationObject.name = this.name;
  59805. serializationObject.level = this.level;
  59806. serializationObject.customType = "BABYLON.ColorGradingTexture";
  59807. return serializationObject;
  59808. };
  59809. return ColorGradingTexture;
  59810. }(BABYLON.BaseTexture));
  59811. /**
  59812. * Empty line regex stored for GC.
  59813. */
  59814. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  59815. BABYLON.ColorGradingTexture = ColorGradingTexture;
  59816. })(BABYLON || (BABYLON = {}));
  59817. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  59818. var BABYLON;
  59819. (function (BABYLON) {
  59820. /**
  59821. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  59822. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  59823. * 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;
  59824. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  59825. */
  59826. var ColorCurves = (function () {
  59827. function ColorCurves() {
  59828. this._dirty = true;
  59829. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  59830. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  59831. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59832. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  59833. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59834. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  59835. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  59836. this._globalHue = 30;
  59837. this._globalDensity = 0;
  59838. this._globalSaturation = 0;
  59839. this._globalExposure = 0;
  59840. this._highlightsHue = 30;
  59841. this._highlightsDensity = 0;
  59842. this._highlightsSaturation = 0;
  59843. this._highlightsExposure = 0;
  59844. this._midtonesHue = 30;
  59845. this._midtonesDensity = 0;
  59846. this._midtonesSaturation = 0;
  59847. this._midtonesExposure = 0;
  59848. this._shadowsHue = 30;
  59849. this._shadowsDensity = 0;
  59850. this._shadowsSaturation = 0;
  59851. this._shadowsExposure = 0;
  59852. }
  59853. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  59854. /**
  59855. * Gets the global Hue value.
  59856. * 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).
  59857. */
  59858. get: function () {
  59859. return this._globalHue;
  59860. },
  59861. /**
  59862. * Sets the global Hue value.
  59863. * 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).
  59864. */
  59865. set: function (value) {
  59866. this._globalHue = value;
  59867. this._dirty = true;
  59868. },
  59869. enumerable: true,
  59870. configurable: true
  59871. });
  59872. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  59873. /**
  59874. * Gets the global Density value.
  59875. * 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.
  59876. * Values less than zero provide a filter of opposite hue.
  59877. */
  59878. get: function () {
  59879. return this._globalDensity;
  59880. },
  59881. /**
  59882. * Sets the global Density value.
  59883. * 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.
  59884. * Values less than zero provide a filter of opposite hue.
  59885. */
  59886. set: function (value) {
  59887. this._globalDensity = value;
  59888. this._dirty = true;
  59889. },
  59890. enumerable: true,
  59891. configurable: true
  59892. });
  59893. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  59894. /**
  59895. * Gets the global Saturation value.
  59896. * 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.
  59897. */
  59898. get: function () {
  59899. return this._globalSaturation;
  59900. },
  59901. /**
  59902. * Sets the global Saturation value.
  59903. * 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.
  59904. */
  59905. set: function (value) {
  59906. this._globalSaturation = value;
  59907. this._dirty = true;
  59908. },
  59909. enumerable: true,
  59910. configurable: true
  59911. });
  59912. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  59913. /**
  59914. * Gets the highlights Hue value.
  59915. * 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).
  59916. */
  59917. get: function () {
  59918. return this._highlightsHue;
  59919. },
  59920. /**
  59921. * Sets the highlights Hue value.
  59922. * 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).
  59923. */
  59924. set: function (value) {
  59925. this._highlightsHue = value;
  59926. this._dirty = true;
  59927. },
  59928. enumerable: true,
  59929. configurable: true
  59930. });
  59931. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  59932. /**
  59933. * Gets the highlights Density value.
  59934. * 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.
  59935. * Values less than zero provide a filter of opposite hue.
  59936. */
  59937. get: function () {
  59938. return this._highlightsDensity;
  59939. },
  59940. /**
  59941. * Sets the highlights Density value.
  59942. * 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.
  59943. * Values less than zero provide a filter of opposite hue.
  59944. */
  59945. set: function (value) {
  59946. this._highlightsDensity = value;
  59947. this._dirty = true;
  59948. },
  59949. enumerable: true,
  59950. configurable: true
  59951. });
  59952. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  59953. /**
  59954. * Gets the highlights Saturation value.
  59955. * 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.
  59956. */
  59957. get: function () {
  59958. return this._highlightsSaturation;
  59959. },
  59960. /**
  59961. * Sets the highlights Saturation value.
  59962. * 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.
  59963. */
  59964. set: function (value) {
  59965. this._highlightsSaturation = value;
  59966. this._dirty = true;
  59967. },
  59968. enumerable: true,
  59969. configurable: true
  59970. });
  59971. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  59972. /**
  59973. * Gets the highlights Exposure value.
  59974. * 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.
  59975. */
  59976. get: function () {
  59977. return this._highlightsExposure;
  59978. },
  59979. /**
  59980. * Sets the highlights Exposure value.
  59981. * 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.
  59982. */
  59983. set: function (value) {
  59984. this._highlightsExposure = value;
  59985. this._dirty = true;
  59986. },
  59987. enumerable: true,
  59988. configurable: true
  59989. });
  59990. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  59991. /**
  59992. * Gets the midtones Hue value.
  59993. * 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).
  59994. */
  59995. get: function () {
  59996. return this._midtonesHue;
  59997. },
  59998. /**
  59999. * Sets the midtones Hue value.
  60000. * 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).
  60001. */
  60002. set: function (value) {
  60003. this._midtonesHue = value;
  60004. this._dirty = true;
  60005. },
  60006. enumerable: true,
  60007. configurable: true
  60008. });
  60009. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  60010. /**
  60011. * Gets the midtones Density value.
  60012. * 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.
  60013. * Values less than zero provide a filter of opposite hue.
  60014. */
  60015. get: function () {
  60016. return this._midtonesDensity;
  60017. },
  60018. /**
  60019. * Sets the midtones Density value.
  60020. * 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.
  60021. * Values less than zero provide a filter of opposite hue.
  60022. */
  60023. set: function (value) {
  60024. this._midtonesDensity = value;
  60025. this._dirty = true;
  60026. },
  60027. enumerable: true,
  60028. configurable: true
  60029. });
  60030. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  60031. /**
  60032. * Gets the midtones Saturation value.
  60033. * 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.
  60034. */
  60035. get: function () {
  60036. return this._midtonesSaturation;
  60037. },
  60038. /**
  60039. * Sets the midtones Saturation value.
  60040. * 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.
  60041. */
  60042. set: function (value) {
  60043. this._midtonesSaturation = value;
  60044. this._dirty = true;
  60045. },
  60046. enumerable: true,
  60047. configurable: true
  60048. });
  60049. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  60050. /**
  60051. * Gets the midtones Exposure value.
  60052. * 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.
  60053. */
  60054. get: function () {
  60055. return this._midtonesExposure;
  60056. },
  60057. /**
  60058. * Sets the midtones Exposure value.
  60059. * 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.
  60060. */
  60061. set: function (value) {
  60062. this._midtonesExposure = value;
  60063. this._dirty = true;
  60064. },
  60065. enumerable: true,
  60066. configurable: true
  60067. });
  60068. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  60069. /**
  60070. * Gets the shadows Hue value.
  60071. * 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).
  60072. */
  60073. get: function () {
  60074. return this._shadowsHue;
  60075. },
  60076. /**
  60077. * Sets the shadows Hue value.
  60078. * 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).
  60079. */
  60080. set: function (value) {
  60081. this._shadowsHue = value;
  60082. this._dirty = true;
  60083. },
  60084. enumerable: true,
  60085. configurable: true
  60086. });
  60087. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  60088. /**
  60089. * Gets the shadows Density value.
  60090. * 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.
  60091. * Values less than zero provide a filter of opposite hue.
  60092. */
  60093. get: function () {
  60094. return this._shadowsDensity;
  60095. },
  60096. /**
  60097. * Sets the shadows Density value.
  60098. * 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.
  60099. * Values less than zero provide a filter of opposite hue.
  60100. */
  60101. set: function (value) {
  60102. this._shadowsDensity = value;
  60103. this._dirty = true;
  60104. },
  60105. enumerable: true,
  60106. configurable: true
  60107. });
  60108. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  60109. /**
  60110. * Gets the shadows Saturation value.
  60111. * 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.
  60112. */
  60113. get: function () {
  60114. return this._shadowsSaturation;
  60115. },
  60116. /**
  60117. * Sets the shadows Saturation value.
  60118. * 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.
  60119. */
  60120. set: function (value) {
  60121. this._shadowsSaturation = value;
  60122. this._dirty = true;
  60123. },
  60124. enumerable: true,
  60125. configurable: true
  60126. });
  60127. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  60128. /**
  60129. * Gets the shadows Exposure value.
  60130. * 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.
  60131. */
  60132. get: function () {
  60133. return this._shadowsExposure;
  60134. },
  60135. /**
  60136. * Sets the shadows Exposure value.
  60137. * 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.
  60138. */
  60139. set: function (value) {
  60140. this._shadowsExposure = value;
  60141. this._dirty = true;
  60142. },
  60143. enumerable: true,
  60144. configurable: true
  60145. });
  60146. /**
  60147. * Binds the color curves to the shader.
  60148. * @param colorCurves The color curve to bind
  60149. * @param effect The effect to bind to
  60150. */
  60151. ColorCurves.Bind = function (colorCurves, effect) {
  60152. if (colorCurves._dirty) {
  60153. colorCurves._dirty = false;
  60154. // Fill in global info.
  60155. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  60156. // Compute highlights info.
  60157. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  60158. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  60159. // Compute midtones info.
  60160. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  60161. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  60162. // Compute shadows info.
  60163. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  60164. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  60165. // Compute deltas (neutral is midtones).
  60166. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  60167. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  60168. }
  60169. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  60170. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  60171. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  60172. };
  60173. /**
  60174. * Prepare the list of uniforms associated with the ColorCurves effects.
  60175. * @param uniformsList The list of uniforms used in the effect
  60176. */
  60177. ColorCurves.PrepareUniforms = function (uniformsList) {
  60178. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  60179. };
  60180. /**
  60181. * Returns color grading data based on a hue, density, saturation and exposure value.
  60182. * @param filterHue The hue of the color filter.
  60183. * @param filterDensity The density of the color filter.
  60184. * @param saturation The saturation.
  60185. * @param exposure The exposure.
  60186. * @param result The result data container.
  60187. */
  60188. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  60189. if (hue == null) {
  60190. return;
  60191. }
  60192. hue = ColorCurves.clamp(hue, 0, 360);
  60193. density = ColorCurves.clamp(density, -100, 100);
  60194. saturation = ColorCurves.clamp(saturation, -100, 100);
  60195. exposure = ColorCurves.clamp(exposure, -100, 100);
  60196. // Remap the slider/config filter density with non-linear mapping and also scale by half
  60197. // so that the maximum filter density is only 50% control. This provides fine control
  60198. // for small values and reasonable range.
  60199. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  60200. density *= 0.5;
  60201. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  60202. if (density < 0) {
  60203. density *= -1;
  60204. hue = (hue + 180) % 360;
  60205. }
  60206. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  60207. result.scaleToRef(2, result);
  60208. result.a = 1 + 0.01 * saturation;
  60209. };
  60210. /**
  60211. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  60212. * @param value The input slider value in range [-100,100].
  60213. * @returns Adjusted value.
  60214. */
  60215. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  60216. value /= 100;
  60217. var x = Math.abs(value);
  60218. x = Math.pow(x, 2);
  60219. if (value < 0) {
  60220. x *= -1;
  60221. }
  60222. x *= 100;
  60223. return x;
  60224. };
  60225. /**
  60226. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  60227. * @param hue The hue (H) input.
  60228. * @param saturation The saturation (S) input.
  60229. * @param brightness The brightness (B) input.
  60230. * @result An RGBA color represented as Vector4.
  60231. */
  60232. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  60233. var h = ColorCurves.clamp(hue, 0, 360);
  60234. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  60235. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  60236. if (s === 0) {
  60237. result.r = v;
  60238. result.g = v;
  60239. result.b = v;
  60240. }
  60241. else {
  60242. // sector 0 to 5
  60243. h /= 60;
  60244. var i = Math.floor(h);
  60245. // fractional part of h
  60246. var f = h - i;
  60247. var p = v * (1 - s);
  60248. var q = v * (1 - s * f);
  60249. var t = v * (1 - s * (1 - f));
  60250. switch (i) {
  60251. case 0:
  60252. result.r = v;
  60253. result.g = t;
  60254. result.b = p;
  60255. break;
  60256. case 1:
  60257. result.r = q;
  60258. result.g = v;
  60259. result.b = p;
  60260. break;
  60261. case 2:
  60262. result.r = p;
  60263. result.g = v;
  60264. result.b = t;
  60265. break;
  60266. case 3:
  60267. result.r = p;
  60268. result.g = q;
  60269. result.b = v;
  60270. break;
  60271. case 4:
  60272. result.r = t;
  60273. result.g = p;
  60274. result.b = v;
  60275. break;
  60276. default:
  60277. result.r = v;
  60278. result.g = p;
  60279. result.b = q;
  60280. break;
  60281. }
  60282. }
  60283. result.a = 1;
  60284. };
  60285. /**
  60286. * Returns a value clamped between min and max
  60287. * @param value The value to clamp
  60288. * @param min The minimum of value
  60289. * @param max The maximum of value
  60290. * @returns The clamped value.
  60291. */
  60292. ColorCurves.clamp = function (value, min, max) {
  60293. return Math.min(Math.max(value, min), max);
  60294. };
  60295. /**
  60296. * Clones the current color curve instance.
  60297. * @return The cloned curves
  60298. */
  60299. ColorCurves.prototype.clone = function () {
  60300. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  60301. };
  60302. /**
  60303. * Serializes the current color curve instance to a json representation.
  60304. * @return a JSON representation
  60305. */
  60306. ColorCurves.prototype.serialize = function () {
  60307. return BABYLON.SerializationHelper.Serialize(this);
  60308. };
  60309. /**
  60310. * Parses the color curve from a json representation.
  60311. * @param source the JSON source to parse
  60312. * @return The parsed curves
  60313. */
  60314. ColorCurves.Parse = function (source) {
  60315. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  60316. };
  60317. return ColorCurves;
  60318. }());
  60319. __decorate([
  60320. BABYLON.serialize()
  60321. ], ColorCurves.prototype, "_globalHue", void 0);
  60322. __decorate([
  60323. BABYLON.serialize()
  60324. ], ColorCurves.prototype, "_globalDensity", void 0);
  60325. __decorate([
  60326. BABYLON.serialize()
  60327. ], ColorCurves.prototype, "_globalSaturation", void 0);
  60328. __decorate([
  60329. BABYLON.serialize()
  60330. ], ColorCurves.prototype, "_globalExposure", void 0);
  60331. __decorate([
  60332. BABYLON.serialize()
  60333. ], ColorCurves.prototype, "_highlightsHue", void 0);
  60334. __decorate([
  60335. BABYLON.serialize()
  60336. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  60337. __decorate([
  60338. BABYLON.serialize()
  60339. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  60340. __decorate([
  60341. BABYLON.serialize()
  60342. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  60343. __decorate([
  60344. BABYLON.serialize()
  60345. ], ColorCurves.prototype, "_midtonesHue", void 0);
  60346. __decorate([
  60347. BABYLON.serialize()
  60348. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  60349. __decorate([
  60350. BABYLON.serialize()
  60351. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  60352. __decorate([
  60353. BABYLON.serialize()
  60354. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  60355. BABYLON.ColorCurves = ColorCurves;
  60356. })(BABYLON || (BABYLON = {}));
  60357. //# sourceMappingURL=babylon.colorCurves.js.map
  60358. var BABYLON;
  60359. (function (BABYLON) {
  60360. var Octree = (function () {
  60361. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  60362. if (maxDepth === void 0) { maxDepth = 2; }
  60363. this.maxDepth = maxDepth;
  60364. this.dynamicContent = new Array();
  60365. this._maxBlockCapacity = maxBlockCapacity || 64;
  60366. this._selectionContent = new BABYLON.SmartArray(1024);
  60367. this._creationFunc = creationFunc;
  60368. }
  60369. // Methods
  60370. Octree.prototype.update = function (worldMin, worldMax, entries) {
  60371. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  60372. };
  60373. Octree.prototype.addMesh = function (entry) {
  60374. for (var index = 0; index < this.blocks.length; index++) {
  60375. var block = this.blocks[index];
  60376. block.addEntry(entry);
  60377. }
  60378. };
  60379. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  60380. this._selectionContent.reset();
  60381. for (var index = 0; index < this.blocks.length; index++) {
  60382. var block = this.blocks[index];
  60383. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  60384. }
  60385. if (allowDuplicate) {
  60386. this._selectionContent.concat(this.dynamicContent);
  60387. }
  60388. else {
  60389. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  60390. }
  60391. return this._selectionContent;
  60392. };
  60393. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  60394. this._selectionContent.reset();
  60395. for (var index = 0; index < this.blocks.length; index++) {
  60396. var block = this.blocks[index];
  60397. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  60398. }
  60399. if (allowDuplicate) {
  60400. this._selectionContent.concat(this.dynamicContent);
  60401. }
  60402. else {
  60403. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  60404. }
  60405. return this._selectionContent;
  60406. };
  60407. Octree.prototype.intersectsRay = function (ray) {
  60408. this._selectionContent.reset();
  60409. for (var index = 0; index < this.blocks.length; index++) {
  60410. var block = this.blocks[index];
  60411. block.intersectsRay(ray, this._selectionContent);
  60412. }
  60413. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  60414. return this._selectionContent;
  60415. };
  60416. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  60417. target.blocks = new Array();
  60418. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  60419. // Segmenting space
  60420. for (var x = 0; x < 2; x++) {
  60421. for (var y = 0; y < 2; y++) {
  60422. for (var z = 0; z < 2; z++) {
  60423. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  60424. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  60425. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  60426. block.addEntries(entries);
  60427. target.blocks.push(block);
  60428. }
  60429. }
  60430. }
  60431. };
  60432. return Octree;
  60433. }());
  60434. Octree.CreationFuncForMeshes = function (entry, block) {
  60435. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  60436. block.entries.push(entry);
  60437. }
  60438. };
  60439. Octree.CreationFuncForSubMeshes = function (entry, block) {
  60440. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  60441. block.entries.push(entry);
  60442. }
  60443. };
  60444. BABYLON.Octree = Octree;
  60445. })(BABYLON || (BABYLON = {}));
  60446. //# sourceMappingURL=babylon.octree.js.map
  60447. var BABYLON;
  60448. (function (BABYLON) {
  60449. var OctreeBlock = (function () {
  60450. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  60451. this.entries = new Array();
  60452. this._boundingVectors = new Array();
  60453. this._capacity = capacity;
  60454. this._depth = depth;
  60455. this._maxDepth = maxDepth;
  60456. this._creationFunc = creationFunc;
  60457. this._minPoint = minPoint;
  60458. this._maxPoint = maxPoint;
  60459. this._boundingVectors.push(minPoint.clone());
  60460. this._boundingVectors.push(maxPoint.clone());
  60461. this._boundingVectors.push(minPoint.clone());
  60462. this._boundingVectors[2].x = maxPoint.x;
  60463. this._boundingVectors.push(minPoint.clone());
  60464. this._boundingVectors[3].y = maxPoint.y;
  60465. this._boundingVectors.push(minPoint.clone());
  60466. this._boundingVectors[4].z = maxPoint.z;
  60467. this._boundingVectors.push(maxPoint.clone());
  60468. this._boundingVectors[5].z = minPoint.z;
  60469. this._boundingVectors.push(maxPoint.clone());
  60470. this._boundingVectors[6].x = minPoint.x;
  60471. this._boundingVectors.push(maxPoint.clone());
  60472. this._boundingVectors[7].y = minPoint.y;
  60473. }
  60474. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  60475. // Property
  60476. get: function () {
  60477. return this._capacity;
  60478. },
  60479. enumerable: true,
  60480. configurable: true
  60481. });
  60482. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  60483. get: function () {
  60484. return this._minPoint;
  60485. },
  60486. enumerable: true,
  60487. configurable: true
  60488. });
  60489. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  60490. get: function () {
  60491. return this._maxPoint;
  60492. },
  60493. enumerable: true,
  60494. configurable: true
  60495. });
  60496. // Methods
  60497. OctreeBlock.prototype.addEntry = function (entry) {
  60498. if (this.blocks) {
  60499. for (var index = 0; index < this.blocks.length; index++) {
  60500. var block = this.blocks[index];
  60501. block.addEntry(entry);
  60502. }
  60503. return;
  60504. }
  60505. this._creationFunc(entry, this);
  60506. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  60507. this.createInnerBlocks();
  60508. }
  60509. };
  60510. OctreeBlock.prototype.addEntries = function (entries) {
  60511. for (var index = 0; index < entries.length; index++) {
  60512. var mesh = entries[index];
  60513. this.addEntry(mesh);
  60514. }
  60515. };
  60516. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  60517. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  60518. if (this.blocks) {
  60519. for (var index = 0; index < this.blocks.length; index++) {
  60520. var block = this.blocks[index];
  60521. block.select(frustumPlanes, selection, allowDuplicate);
  60522. }
  60523. return;
  60524. }
  60525. if (allowDuplicate) {
  60526. selection.concat(this.entries);
  60527. }
  60528. else {
  60529. selection.concatWithNoDuplicate(this.entries);
  60530. }
  60531. }
  60532. };
  60533. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  60534. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  60535. if (this.blocks) {
  60536. for (var index = 0; index < this.blocks.length; index++) {
  60537. var block = this.blocks[index];
  60538. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  60539. }
  60540. return;
  60541. }
  60542. if (allowDuplicate) {
  60543. selection.concat(this.entries);
  60544. }
  60545. else {
  60546. selection.concatWithNoDuplicate(this.entries);
  60547. }
  60548. }
  60549. };
  60550. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  60551. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  60552. if (this.blocks) {
  60553. for (var index = 0; index < this.blocks.length; index++) {
  60554. var block = this.blocks[index];
  60555. block.intersectsRay(ray, selection);
  60556. }
  60557. return;
  60558. }
  60559. selection.concatWithNoDuplicate(this.entries);
  60560. }
  60561. };
  60562. OctreeBlock.prototype.createInnerBlocks = function () {
  60563. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  60564. };
  60565. return OctreeBlock;
  60566. }());
  60567. BABYLON.OctreeBlock = OctreeBlock;
  60568. })(BABYLON || (BABYLON = {}));
  60569. //# sourceMappingURL=babylon.octreeBlock.js.map
  60570. var BABYLON;
  60571. (function (BABYLON) {
  60572. var SIMDVector3 = (function () {
  60573. function SIMDVector3() {
  60574. }
  60575. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  60576. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  60577. };
  60578. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  60579. var m = transformation.m;
  60580. var m0 = SIMD.Float32x4.load(m, 0);
  60581. var m1 = SIMD.Float32x4.load(m, 4);
  60582. var m2 = SIMD.Float32x4.load(m, 8);
  60583. var m3 = SIMD.Float32x4.load(m, 12);
  60584. 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));
  60585. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  60586. result.x = SIMD.Float32x4.extractLane(r, 0);
  60587. result.y = SIMD.Float32x4.extractLane(r, 1);
  60588. result.z = SIMD.Float32x4.extractLane(r, 2);
  60589. };
  60590. return SIMDVector3;
  60591. }());
  60592. var SIMDMatrix = (function () {
  60593. function SIMDMatrix() {
  60594. }
  60595. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  60596. var tm = this.m;
  60597. var om = other.m;
  60598. var m0 = SIMD.Float32x4.load(om, 0);
  60599. var m1 = SIMD.Float32x4.load(om, 4);
  60600. var m2 = SIMD.Float32x4.load(om, 8);
  60601. var m3 = SIMD.Float32x4.load(om, 12);
  60602. for (var i = 0; i < 16; i += 4) {
  60603. 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)))));
  60604. }
  60605. return this;
  60606. };
  60607. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  60608. var src = this.m;
  60609. var dest = other.m;
  60610. // Load the 4 rows
  60611. var src0 = SIMD.Float32x4.load(src, 0);
  60612. var src1 = SIMD.Float32x4.load(src, 4);
  60613. var src2 = SIMD.Float32x4.load(src, 8);
  60614. var src3 = SIMD.Float32x4.load(src, 12);
  60615. // Transpose the source matrix. Sort of. Not a true transpose operation
  60616. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  60617. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  60618. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  60619. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  60620. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  60621. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  60622. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  60623. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  60624. // This is a true transposition, but it will lead to an incorrect result
  60625. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  60626. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  60627. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  60628. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  60629. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  60630. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  60631. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  60632. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  60633. // ----
  60634. tmp1 = SIMD.Float32x4.mul(row2, row3);
  60635. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  60636. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  60637. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  60638. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  60639. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  60640. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  60641. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  60642. // ----
  60643. tmp1 = SIMD.Float32x4.mul(row1, row2);
  60644. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  60645. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  60646. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  60647. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  60648. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  60649. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  60650. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  60651. // ----
  60652. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  60653. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  60654. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  60655. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  60656. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  60657. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  60658. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  60659. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  60660. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  60661. // ----
  60662. tmp1 = SIMD.Float32x4.mul(row0, row1);
  60663. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  60664. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  60665. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  60666. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  60667. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  60668. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  60669. // ----
  60670. tmp1 = SIMD.Float32x4.mul(row0, row3);
  60671. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  60672. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  60673. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  60674. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  60675. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  60676. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  60677. // ----
  60678. tmp1 = SIMD.Float32x4.mul(row0, row2);
  60679. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  60680. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  60681. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  60682. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  60683. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  60684. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  60685. // Compute determinant
  60686. var det = SIMD.Float32x4.mul(row0, minor0);
  60687. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  60688. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  60689. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  60690. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  60691. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  60692. // These shuffles aren't necessary if the faulty transposition is done
  60693. // up at the top of this function.
  60694. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  60695. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  60696. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  60697. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  60698. // Compute final values by multiplying with 1/det
  60699. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  60700. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  60701. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  60702. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  60703. return this;
  60704. };
  60705. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  60706. var out = result.m;
  60707. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  60708. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  60709. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  60710. // cc.kmVec3Subtract(f, pCenter, pEye);
  60711. var f = SIMD.Float32x4.sub(center, eye);
  60712. // cc.kmVec3Normalize(f, f);
  60713. var tmp = SIMD.Float32x4.mul(f, f);
  60714. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  60715. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  60716. // cc.kmVec3Assign(up, pUp);
  60717. // cc.kmVec3Normalize(up, up);
  60718. tmp = SIMD.Float32x4.mul(up, up);
  60719. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  60720. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  60721. // cc.kmVec3Cross(s, f, up);
  60722. 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)));
  60723. // cc.kmVec3Normalize(s, s);
  60724. tmp = SIMD.Float32x4.mul(s, s);
  60725. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  60726. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  60727. // cc.kmVec3Cross(u, s, f);
  60728. 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)));
  60729. // cc.kmVec3Normalize(s, s);
  60730. tmp = SIMD.Float32x4.mul(s, s);
  60731. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  60732. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  60733. var zero = SIMD.Float32x4.splat(0.0);
  60734. s = SIMD.Float32x4.neg(s);
  60735. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  60736. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  60737. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  60738. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  60739. 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);
  60740. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  60741. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  60742. 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)))));
  60743. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  60744. 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)))));
  60745. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  60746. 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)))));
  60747. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  60748. 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)))));
  60749. };
  60750. return SIMDMatrix;
  60751. }());
  60752. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  60753. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  60754. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  60755. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  60756. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  60757. var SIMDHelper = (function () {
  60758. function SIMDHelper() {
  60759. }
  60760. Object.defineProperty(SIMDHelper, "IsEnabled", {
  60761. get: function () {
  60762. return SIMDHelper._isEnabled;
  60763. },
  60764. enumerable: true,
  60765. configurable: true
  60766. });
  60767. SIMDHelper.DisableSIMD = function () {
  60768. // Replace functions
  60769. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  60770. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  60771. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  60772. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  60773. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  60774. SIMDHelper._isEnabled = false;
  60775. };
  60776. SIMDHelper.EnableSIMD = function () {
  60777. if (self.SIMD === undefined) {
  60778. return;
  60779. }
  60780. // check if polyfills needed
  60781. if (!self.Math.fround) {
  60782. self.Math.fround = (function (array) { return function (x) {
  60783. return array[0] = x, array[0];
  60784. }; })(new Float32Array(1));
  60785. }
  60786. if (!self.Math.imul) {
  60787. self.Math.imul = function (a, b) {
  60788. var ah = (a >>> 16) & 0xffff;
  60789. var al = a & 0xffff;
  60790. var bh = (b >>> 16) & 0xffff;
  60791. var bl = b & 0xffff;
  60792. // the shift by 0 fixes the sign on the high part
  60793. // the final |0 converts the unsigned value into a signed value
  60794. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  60795. };
  60796. }
  60797. // Replace functions
  60798. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  60799. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  60800. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  60801. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  60802. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  60803. SIMDHelper._isEnabled = true;
  60804. };
  60805. return SIMDHelper;
  60806. }());
  60807. SIMDHelper._isEnabled = false;
  60808. BABYLON.SIMDHelper = SIMDHelper;
  60809. })(BABYLON || (BABYLON = {}));
  60810. //# sourceMappingURL=babylon.math.SIMD.js.map
  60811. var BABYLON;
  60812. (function (BABYLON) {
  60813. var VRDistortionCorrectionPostProcess = (function (_super) {
  60814. __extends(VRDistortionCorrectionPostProcess, _super);
  60815. //ANY
  60816. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  60817. var _this = _super.call(this, name, "vrDistortionCorrection", [
  60818. 'LensCenter',
  60819. 'Scale',
  60820. 'ScaleIn',
  60821. 'HmdWarpParam'
  60822. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  60823. _this._isRightEye = isRightEye;
  60824. _this._distortionFactors = vrMetrics.distortionK;
  60825. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  60826. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  60827. _this.onSizeChangedObservable.add(function () {
  60828. _this.aspectRatio = _this.width * .5 / _this.height;
  60829. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  60830. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  60831. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  60832. });
  60833. _this.onApplyObservable.add(function (effect) {
  60834. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  60835. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  60836. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  60837. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  60838. });
  60839. return _this;
  60840. }
  60841. return VRDistortionCorrectionPostProcess;
  60842. }(BABYLON.PostProcess));
  60843. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  60844. })(BABYLON || (BABYLON = {}));
  60845. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  60846. var BABYLON;
  60847. (function (BABYLON) {
  60848. var AnaglyphPostProcess = (function (_super) {
  60849. __extends(AnaglyphPostProcess, _super);
  60850. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  60851. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  60852. _this._passedProcess = rigCameras[0]._rigPostProcess;
  60853. _this.onApplyObservable.add(function (effect) {
  60854. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  60855. });
  60856. return _this;
  60857. }
  60858. return AnaglyphPostProcess;
  60859. }(BABYLON.PostProcess));
  60860. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  60861. })(BABYLON || (BABYLON = {}));
  60862. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  60863. var BABYLON;
  60864. (function (BABYLON) {
  60865. var StereoscopicInterlacePostProcess = (function (_super) {
  60866. __extends(StereoscopicInterlacePostProcess, _super);
  60867. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  60868. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  60869. _this._passedProcess = rigCameras[0]._rigPostProcess;
  60870. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  60871. _this.onSizeChangedObservable.add(function () {
  60872. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  60873. });
  60874. _this.onApplyObservable.add(function (effect) {
  60875. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  60876. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  60877. });
  60878. return _this;
  60879. }
  60880. return StereoscopicInterlacePostProcess;
  60881. }(BABYLON.PostProcess));
  60882. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  60883. })(BABYLON || (BABYLON = {}));
  60884. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  60885. var BABYLON;
  60886. (function (BABYLON) {
  60887. var FreeCameraDeviceOrientationInput = (function () {
  60888. function FreeCameraDeviceOrientationInput() {
  60889. var _this = this;
  60890. this._screenOrientationAngle = 0;
  60891. this._screenQuaternion = new BABYLON.Quaternion();
  60892. this._alpha = 0;
  60893. this._beta = 0;
  60894. this._gamma = 0;
  60895. this._orientationChanged = function () {
  60896. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  60897. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  60898. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  60899. };
  60900. this._deviceOrientation = function (evt) {
  60901. _this._alpha = evt.alpha;
  60902. _this._beta = evt.beta;
  60903. _this._gamma = evt.gamma;
  60904. };
  60905. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  60906. this._orientationChanged();
  60907. }
  60908. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  60909. get: function () {
  60910. return this._camera;
  60911. },
  60912. set: function (camera) {
  60913. this._camera = camera;
  60914. if (!this._camera.rotationQuaternion)
  60915. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  60916. },
  60917. enumerable: true,
  60918. configurable: true
  60919. });
  60920. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  60921. window.addEventListener("orientationchange", this._orientationChanged);
  60922. window.addEventListener("deviceorientation", this._deviceOrientation);
  60923. //In certain cases, the attach control is called AFTER orientation was changed,
  60924. //So this is needed.
  60925. this._orientationChanged();
  60926. };
  60927. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  60928. window.removeEventListener("orientationchange", this._orientationChanged);
  60929. window.removeEventListener("deviceorientation", this._deviceOrientation);
  60930. };
  60931. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  60932. //if no device orientation provided, don't update the rotation.
  60933. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  60934. if (!this._alpha)
  60935. return;
  60936. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  60937. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  60938. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  60939. //Mirror on XY Plane
  60940. this._camera.rotationQuaternion.z *= -1;
  60941. this._camera.rotationQuaternion.w *= -1;
  60942. };
  60943. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  60944. return "FreeCameraDeviceOrientationInput";
  60945. };
  60946. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  60947. return "deviceOrientation";
  60948. };
  60949. return FreeCameraDeviceOrientationInput;
  60950. }());
  60951. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  60952. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  60953. })(BABYLON || (BABYLON = {}));
  60954. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  60955. var BABYLON;
  60956. (function (BABYLON) {
  60957. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  60958. function ArcRotateCameraVRDeviceOrientationInput() {
  60959. this.alphaCorrection = 1;
  60960. this.betaCorrection = 1;
  60961. this.gammaCorrection = 1;
  60962. this._alpha = 0;
  60963. this._beta = 0;
  60964. this._gamma = 0;
  60965. this._dirty = false;
  60966. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  60967. }
  60968. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  60969. this.camera.attachControl(element, noPreventDefault);
  60970. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  60971. };
  60972. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  60973. var camera = this.camera;
  60974. this._alpha = +evt.alpha | 0;
  60975. this._beta = +evt.beta | 0;
  60976. this._gamma = +evt.gamma | 0;
  60977. this._dirty = true;
  60978. };
  60979. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  60980. if (this._dirty) {
  60981. this._dirty = false;
  60982. if (this._gamma < 0) {
  60983. this._gamma = 180 + this._gamma;
  60984. }
  60985. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  60986. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  60987. }
  60988. };
  60989. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  60990. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  60991. };
  60992. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  60993. return "ArcRotateCameraVRDeviceOrientationInput";
  60994. };
  60995. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  60996. return "VRDeviceOrientation";
  60997. };
  60998. return ArcRotateCameraVRDeviceOrientationInput;
  60999. }());
  61000. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  61001. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  61002. })(BABYLON || (BABYLON = {}));
  61003. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  61004. var BABYLON;
  61005. (function (BABYLON) {
  61006. var VRCameraMetrics = (function () {
  61007. function VRCameraMetrics() {
  61008. this.compensateDistortion = true;
  61009. }
  61010. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  61011. get: function () {
  61012. return this.hResolution / (2 * this.vResolution);
  61013. },
  61014. enumerable: true,
  61015. configurable: true
  61016. });
  61017. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  61018. get: function () {
  61019. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  61020. },
  61021. enumerable: true,
  61022. configurable: true
  61023. });
  61024. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  61025. get: function () {
  61026. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  61027. var h = (4 * meters) / this.hScreenSize;
  61028. return BABYLON.Matrix.Translation(h, 0, 0);
  61029. },
  61030. enumerable: true,
  61031. configurable: true
  61032. });
  61033. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  61034. get: function () {
  61035. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  61036. var h = (4 * meters) / this.hScreenSize;
  61037. return BABYLON.Matrix.Translation(-h, 0, 0);
  61038. },
  61039. enumerable: true,
  61040. configurable: true
  61041. });
  61042. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  61043. get: function () {
  61044. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  61045. },
  61046. enumerable: true,
  61047. configurable: true
  61048. });
  61049. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  61050. get: function () {
  61051. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  61052. },
  61053. enumerable: true,
  61054. configurable: true
  61055. });
  61056. VRCameraMetrics.GetDefault = function () {
  61057. var result = new VRCameraMetrics();
  61058. result.hResolution = 1280;
  61059. result.vResolution = 800;
  61060. result.hScreenSize = 0.149759993;
  61061. result.vScreenSize = 0.0935999975;
  61062. result.vScreenCenter = 0.0467999987;
  61063. result.eyeToScreenDistance = 0.0410000011;
  61064. result.lensSeparationDistance = 0.0635000020;
  61065. result.interpupillaryDistance = 0.0640000030;
  61066. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  61067. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  61068. result.postProcessScaleFactor = 1.714605507808412;
  61069. result.lensCenterOffset = 0.151976421;
  61070. return result;
  61071. };
  61072. return VRCameraMetrics;
  61073. }());
  61074. BABYLON.VRCameraMetrics = VRCameraMetrics;
  61075. })(BABYLON || (BABYLON = {}));
  61076. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  61077. var BABYLON;
  61078. (function (BABYLON) {
  61079. var WebVRFreeCamera = (function (_super) {
  61080. __extends(WebVRFreeCamera, _super);
  61081. function WebVRFreeCamera(name, position, scene, webVROptions) {
  61082. if (webVROptions === void 0) { webVROptions = {}; }
  61083. var _this = _super.call(this, name, position, scene) || this;
  61084. _this.webVROptions = webVROptions;
  61085. _this._vrDevice = null;
  61086. _this.rawPose = null;
  61087. _this._vrEnabled = false;
  61088. _this._specsVersion = 1.1;
  61089. _this._attached = false;
  61090. _this._positionOffset = BABYLON.Vector3.Zero();
  61091. _this._descendants = [];
  61092. _this.devicePosition = BABYLON.Vector3.Zero();
  61093. _this.deviceScaleFactor = 1;
  61094. _this.controllers = [];
  61095. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  61096. //legacy support - the compensation boolean was removed.
  61097. if (arguments.length === 5) {
  61098. _this.webVROptions = arguments[4];
  61099. }
  61100. // default webVR options
  61101. if (_this.webVROptions.trackPosition == undefined) {
  61102. _this.webVROptions.trackPosition = true;
  61103. }
  61104. if (_this.webVROptions.controllerMeshes == undefined) {
  61105. _this.webVROptions.controllerMeshes = true;
  61106. }
  61107. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  61108. _this.webVROptions.defaultLightningOnControllers = true;
  61109. }
  61110. _this.rotationQuaternion = new BABYLON.Quaternion();
  61111. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  61112. if (_this.webVROptions && _this.webVROptions.positionScale) {
  61113. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  61114. }
  61115. //enable VR
  61116. _this.getEngine().initWebVR();
  61117. //check specs version
  61118. if (!window.VRFrameData) {
  61119. _this._specsVersion = 1.0;
  61120. _this._frameData = {};
  61121. }
  61122. else {
  61123. _this._frameData = new VRFrameData();
  61124. }
  61125. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  61126. if (!device) {
  61127. return;
  61128. }
  61129. _this._vrEnabled = true;
  61130. _this._vrDevice = device;
  61131. //reset the rig parameters.
  61132. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  61133. if (_this._attached) {
  61134. _this.getEngine().enableVR(_this._vrDevice);
  61135. }
  61136. });
  61137. // try to attach the controllers, if found.
  61138. _this.initControllers();
  61139. /**
  61140. * The idea behind the following lines:
  61141. * objects that have the camera as parent should actually have the rig cameras as a parent.
  61142. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  61143. * the second will not show it correctly.
  61144. *
  61145. * To solve this - each object that has the camera as parent will be added to a protected array.
  61146. * When the rig camera renders, it will take this array and set all of those to be its children.
  61147. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  61148. * Amazing!
  61149. */
  61150. scene.onBeforeCameraRenderObservable.add(function (camera) {
  61151. if (camera.parent === _this && _this.rigParenting) {
  61152. _this._descendants = _this.getDescendants(true, function (n) {
  61153. // don't take the cameras or the controllers!
  61154. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  61155. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  61156. return !isController && !isRigCamera;
  61157. });
  61158. _this._descendants.forEach(function (node) {
  61159. node.parent = camera;
  61160. });
  61161. }
  61162. });
  61163. scene.onAfterCameraRenderObservable.add(function (camera) {
  61164. if (camera.parent === _this && _this.rigParenting) {
  61165. _this._descendants.forEach(function (node) {
  61166. node.parent = _this;
  61167. });
  61168. }
  61169. });
  61170. return _this;
  61171. }
  61172. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  61173. set: function (callback) {
  61174. this._onControllersAttached = callback;
  61175. // after setting - if the controllers are already set, execute the callback.
  61176. if (this.controllers.length >= 2) {
  61177. callback(this.controllers);
  61178. }
  61179. },
  61180. enumerable: true,
  61181. configurable: true
  61182. });
  61183. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  61184. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  61185. var gp = _a[_i];
  61186. if (gp.hand === name) {
  61187. return gp;
  61188. }
  61189. }
  61190. return undefined;
  61191. };
  61192. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  61193. get: function () {
  61194. if (!this._leftController) {
  61195. this._leftController = this.getControllerByName("left");
  61196. }
  61197. return this._leftController;
  61198. },
  61199. enumerable: true,
  61200. configurable: true
  61201. });
  61202. ;
  61203. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  61204. get: function () {
  61205. if (!this._rightController) {
  61206. this._rightController = this.getControllerByName("right");
  61207. }
  61208. return this._rightController;
  61209. },
  61210. enumerable: true,
  61211. configurable: true
  61212. });
  61213. ;
  61214. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  61215. if (length === void 0) { length = 100; }
  61216. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  61217. };
  61218. WebVRFreeCamera.prototype._checkInputs = function () {
  61219. if (this._vrEnabled) {
  61220. if (this._specsVersion === 1.1) {
  61221. this._vrDevice.getFrameData(this._frameData);
  61222. }
  61223. else {
  61224. //backwards comp
  61225. var pose = this._vrDevice.getPose();
  61226. this._frameData.pose = pose;
  61227. // calculate view and projection matrix
  61228. }
  61229. this.updateFromDevice(this._frameData.pose);
  61230. }
  61231. _super.prototype._checkInputs.call(this);
  61232. };
  61233. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  61234. if (poseData && poseData.orientation) {
  61235. this.rawPose = poseData;
  61236. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  61237. if (this.getScene().useRightHandedSystem) {
  61238. this.deviceRotationQuaternion.z *= -1;
  61239. this.deviceRotationQuaternion.w *= -1;
  61240. }
  61241. if (this.webVROptions.trackPosition && this.rawPose.position) {
  61242. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  61243. if (this.getScene().useRightHandedSystem) {
  61244. this.devicePosition.z *= -1;
  61245. }
  61246. }
  61247. }
  61248. };
  61249. /**
  61250. * WebVR's attach control will start broadcasting frames to the device.
  61251. * Note that in certain browsers (chrome for example) this function must be called
  61252. * within a user-interaction callback. Example:
  61253. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  61254. *
  61255. * @param {HTMLElement} element
  61256. * @param {boolean} [noPreventDefault]
  61257. *
  61258. * @memberOf WebVRFreeCamera
  61259. */
  61260. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  61261. _super.prototype.attachControl.call(this, element, noPreventDefault);
  61262. this._attached = true;
  61263. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  61264. if (this._vrEnabled) {
  61265. this.getEngine().enableVR(this._vrDevice);
  61266. }
  61267. };
  61268. WebVRFreeCamera.prototype.detachControl = function (element) {
  61269. _super.prototype.detachControl.call(this, element);
  61270. this._vrEnabled = false;
  61271. this._attached = false;
  61272. this.getEngine().disableVR();
  61273. };
  61274. WebVRFreeCamera.prototype.getClassName = function () {
  61275. return "WebVRFreeCamera";
  61276. };
  61277. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  61278. //uses the vrDisplay's "resetPose()".
  61279. //pitch and roll won't be affected.
  61280. this._vrDevice.resetPose();
  61281. };
  61282. WebVRFreeCamera.prototype._updateRigCameras = function () {
  61283. var camLeft = this._rigCameras[0];
  61284. var camRight = this._rigCameras[1];
  61285. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  61286. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  61287. camLeft.position.copyFrom(this.devicePosition);
  61288. camRight.position.copyFrom(this.devicePosition);
  61289. };
  61290. /**
  61291. * This function is called by the two RIG cameras.
  61292. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  61293. */
  61294. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  61295. var _this = this;
  61296. //WebVR 1.0
  61297. if (this._cameraRigParams["specs"] === 1.0) {
  61298. this._updateCameraRotationMatrix();
  61299. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  61300. // Computing target and final matrix
  61301. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  61302. if (this.getScene().useRightHandedSystem) {
  61303. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  61304. }
  61305. else {
  61306. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  61307. }
  61308. //now move the eye in the right direction
  61309. var eyeParams = this._cameraRigParams["eyeParameters"];
  61310. var offset = eyeParams.offset;
  61311. // it will actually always be 0, but just in case
  61312. if (this.getScene().useRightHandedSystem) {
  61313. offset[2] *= -1;
  61314. }
  61315. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  61316. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  61317. }
  61318. else {
  61319. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  61320. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  61321. if (!this.getScene().useRightHandedSystem) {
  61322. [2, 6, 8, 9, 14].forEach(function (num) {
  61323. _this._webvrViewMatrix.m[num] *= -1;
  61324. });
  61325. }
  61326. // update the camera rotation matrix
  61327. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  61328. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  61329. // Computing target and final matrix
  61330. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  61331. }
  61332. var parentCamera = this._cameraRigParams["parentCamera"];
  61333. // should the view matrix be updated with scale and position offset?
  61334. if (parentCamera.deviceScaleFactor !== 1) {
  61335. this._webvrViewMatrix.invert();
  61336. // scale the position, if set
  61337. if (parentCamera.deviceScaleFactor) {
  61338. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  61339. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  61340. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  61341. }
  61342. this._webvrViewMatrix.invert();
  61343. }
  61344. return this._webvrViewMatrix;
  61345. };
  61346. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  61347. var _this = this;
  61348. if (this._cameraRigParams["specs"] === 1.0) {
  61349. var eyeParams = this._cameraRigParams["eyeParameters"];
  61350. // deprecated!!
  61351. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  61352. }
  61353. else {
  61354. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  61355. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  61356. //babylon compatible matrix
  61357. if (!this.getScene().useRightHandedSystem) {
  61358. [8, 9, 10, 11].forEach(function (num) {
  61359. _this._projectionMatrix.m[num] *= -1;
  61360. });
  61361. }
  61362. }
  61363. return this._projectionMatrix;
  61364. };
  61365. WebVRFreeCamera.prototype.initControllers = function () {
  61366. var _this = this;
  61367. this.controllers = [];
  61368. new BABYLON.Gamepads(function (gp) {
  61369. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  61370. var webVrController = gp;
  61371. if (_this.webVROptions.controllerMeshes) {
  61372. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  61373. if (_this.webVROptions.defaultLightningOnControllers) {
  61374. if (!_this._lightOnControllers) {
  61375. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  61376. }
  61377. loadedMesh.getChildren().forEach(function (mesh) {
  61378. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  61379. });
  61380. }
  61381. });
  61382. }
  61383. webVrController.attachToPoseControlledCamera(_this);
  61384. // since this is async - sanity check. Is the controller already stored?
  61385. if (_this.controllers.indexOf(webVrController) === -1) {
  61386. //add to the controllers array
  61387. _this.controllers.push(webVrController);
  61388. //did we find enough controllers? Great! let the developer know.
  61389. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  61390. _this._onControllersAttached(_this.controllers);
  61391. }
  61392. }
  61393. }
  61394. });
  61395. };
  61396. return WebVRFreeCamera;
  61397. }(BABYLON.FreeCamera));
  61398. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  61399. })(BABYLON || (BABYLON = {}));
  61400. //# sourceMappingURL=babylon.webVRCamera.js.map
  61401. /// <reference path="babylon.freeCamera.ts" />
  61402. var BABYLON;
  61403. (function (BABYLON) {
  61404. // We're mainly based on the logic defined into the FreeCamera code
  61405. var DeviceOrientationCamera = (function (_super) {
  61406. __extends(DeviceOrientationCamera, _super);
  61407. function DeviceOrientationCamera(name, position, scene) {
  61408. var _this = _super.call(this, name, position, scene) || this;
  61409. _this._quaternionCache = new BABYLON.Quaternion();
  61410. _this.inputs.addDeviceOrientation();
  61411. return _this;
  61412. }
  61413. DeviceOrientationCamera.prototype.getClassName = function () {
  61414. return "DeviceOrientationCamera";
  61415. };
  61416. DeviceOrientationCamera.prototype._checkInputs = function () {
  61417. _super.prototype._checkInputs.call(this);
  61418. this._quaternionCache.copyFrom(this.rotationQuaternion);
  61419. if (this._initialQuaternion) {
  61420. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  61421. }
  61422. };
  61423. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  61424. var _this = this;
  61425. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  61426. //can only work if this camera has a rotation quaternion already.
  61427. if (!this.rotationQuaternion)
  61428. return;
  61429. if (!this._initialQuaternion) {
  61430. this._initialQuaternion = new BABYLON.Quaternion();
  61431. }
  61432. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  61433. ['x', 'y', 'z'].forEach(function (axisName) {
  61434. if (!axis[axisName]) {
  61435. _this._initialQuaternion[axisName] = 0;
  61436. }
  61437. else {
  61438. _this._initialQuaternion[axisName] *= -1;
  61439. }
  61440. });
  61441. this._initialQuaternion.normalize();
  61442. //force rotation update
  61443. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  61444. };
  61445. return DeviceOrientationCamera;
  61446. }(BABYLON.FreeCamera));
  61447. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  61448. })(BABYLON || (BABYLON = {}));
  61449. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  61450. var BABYLON;
  61451. (function (BABYLON) {
  61452. var VRDeviceOrientationFreeCamera = (function (_super) {
  61453. __extends(VRDeviceOrientationFreeCamera, _super);
  61454. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  61455. if (compensateDistortion === void 0) { compensateDistortion = true; }
  61456. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  61457. var _this = _super.call(this, name, position, scene) || this;
  61458. vrCameraMetrics.compensateDistortion = compensateDistortion;
  61459. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  61460. return _this;
  61461. }
  61462. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  61463. return "VRDeviceOrientationFreeCamera";
  61464. };
  61465. return VRDeviceOrientationFreeCamera;
  61466. }(BABYLON.DeviceOrientationCamera));
  61467. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  61468. var VRDeviceOrientationGamepadCamera = (function (_super) {
  61469. __extends(VRDeviceOrientationGamepadCamera, _super);
  61470. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  61471. if (compensateDistortion === void 0) { compensateDistortion = true; }
  61472. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  61473. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  61474. _this.inputs.addGamepad();
  61475. return _this;
  61476. }
  61477. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  61478. return "VRDeviceOrientationGamepadCamera";
  61479. };
  61480. return VRDeviceOrientationGamepadCamera;
  61481. }(VRDeviceOrientationFreeCamera));
  61482. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  61483. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  61484. __extends(VRDeviceOrientationArcRotateCamera, _super);
  61485. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  61486. if (compensateDistortion === void 0) { compensateDistortion = true; }
  61487. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  61488. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  61489. vrCameraMetrics.compensateDistortion = compensateDistortion;
  61490. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  61491. _this.inputs.addVRDeviceOrientation();
  61492. return _this;
  61493. }
  61494. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  61495. return "VRDeviceOrientationArcRotateCamera";
  61496. };
  61497. return VRDeviceOrientationArcRotateCamera;
  61498. }(BABYLON.ArcRotateCamera));
  61499. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  61500. })(BABYLON || (BABYLON = {}));
  61501. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  61502. /// <reference path="babylon.freeCamera.ts" />
  61503. /// <reference path="babylon.arcRotateCamera.ts" />
  61504. /// <reference path="babylon.gamepadCamera.ts" />
  61505. /// <reference path="babylon.universalCamera.ts" />
  61506. var BABYLON;
  61507. (function (BABYLON) {
  61508. var AnaglyphFreeCamera = (function (_super) {
  61509. __extends(AnaglyphFreeCamera, _super);
  61510. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  61511. var _this = _super.call(this, name, position, scene) || this;
  61512. _this.interaxialDistance = interaxialDistance;
  61513. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  61514. return _this;
  61515. }
  61516. AnaglyphFreeCamera.prototype.getClassName = function () {
  61517. return "AnaglyphFreeCamera";
  61518. };
  61519. return AnaglyphFreeCamera;
  61520. }(BABYLON.FreeCamera));
  61521. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  61522. var AnaglyphArcRotateCamera = (function (_super) {
  61523. __extends(AnaglyphArcRotateCamera, _super);
  61524. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  61525. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  61526. _this.interaxialDistance = interaxialDistance;
  61527. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  61528. return _this;
  61529. }
  61530. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  61531. return "AnaglyphArcRotateCamera";
  61532. };
  61533. return AnaglyphArcRotateCamera;
  61534. }(BABYLON.ArcRotateCamera));
  61535. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  61536. var AnaglyphGamepadCamera = (function (_super) {
  61537. __extends(AnaglyphGamepadCamera, _super);
  61538. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  61539. var _this = _super.call(this, name, position, scene) || this;
  61540. _this.interaxialDistance = interaxialDistance;
  61541. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  61542. return _this;
  61543. }
  61544. AnaglyphGamepadCamera.prototype.getClassName = function () {
  61545. return "AnaglyphGamepadCamera";
  61546. };
  61547. return AnaglyphGamepadCamera;
  61548. }(BABYLON.GamepadCamera));
  61549. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  61550. var AnaglyphUniversalCamera = (function (_super) {
  61551. __extends(AnaglyphUniversalCamera, _super);
  61552. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  61553. var _this = _super.call(this, name, position, scene) || this;
  61554. _this.interaxialDistance = interaxialDistance;
  61555. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  61556. return _this;
  61557. }
  61558. AnaglyphUniversalCamera.prototype.getClassName = function () {
  61559. return "AnaglyphUniversalCamera";
  61560. };
  61561. return AnaglyphUniversalCamera;
  61562. }(BABYLON.UniversalCamera));
  61563. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  61564. var StereoscopicFreeCamera = (function (_super) {
  61565. __extends(StereoscopicFreeCamera, _super);
  61566. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  61567. var _this = _super.call(this, name, position, scene) || this;
  61568. _this.interaxialDistance = interaxialDistance;
  61569. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  61570. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  61571. return _this;
  61572. }
  61573. StereoscopicFreeCamera.prototype.getClassName = function () {
  61574. return "StereoscopicFreeCamera";
  61575. };
  61576. return StereoscopicFreeCamera;
  61577. }(BABYLON.FreeCamera));
  61578. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  61579. var StereoscopicArcRotateCamera = (function (_super) {
  61580. __extends(StereoscopicArcRotateCamera, _super);
  61581. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  61582. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  61583. _this.interaxialDistance = interaxialDistance;
  61584. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  61585. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  61586. return _this;
  61587. }
  61588. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  61589. return "StereoscopicArcRotateCamera";
  61590. };
  61591. return StereoscopicArcRotateCamera;
  61592. }(BABYLON.ArcRotateCamera));
  61593. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  61594. var StereoscopicGamepadCamera = (function (_super) {
  61595. __extends(StereoscopicGamepadCamera, _super);
  61596. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  61597. var _this = _super.call(this, name, position, scene) || this;
  61598. _this.interaxialDistance = interaxialDistance;
  61599. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  61600. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  61601. return _this;
  61602. }
  61603. StereoscopicGamepadCamera.prototype.getClassName = function () {
  61604. return "StereoscopicGamepadCamera";
  61605. };
  61606. return StereoscopicGamepadCamera;
  61607. }(BABYLON.GamepadCamera));
  61608. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  61609. var StereoscopicUniversalCamera = (function (_super) {
  61610. __extends(StereoscopicUniversalCamera, _super);
  61611. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  61612. var _this = _super.call(this, name, position, scene) || this;
  61613. _this.interaxialDistance = interaxialDistance;
  61614. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  61615. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  61616. return _this;
  61617. }
  61618. StereoscopicUniversalCamera.prototype.getClassName = function () {
  61619. return "StereoscopicUniversalCamera";
  61620. };
  61621. return StereoscopicUniversalCamera;
  61622. }(BABYLON.UniversalCamera));
  61623. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  61624. })(BABYLON || (BABYLON = {}));
  61625. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  61626. // Mainly based on these 2 articles :
  61627. // 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
  61628. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  61629. var BABYLON;
  61630. (function (BABYLON) {
  61631. var JoystickAxis;
  61632. (function (JoystickAxis) {
  61633. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  61634. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  61635. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  61636. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  61637. var VirtualJoystick = (function () {
  61638. function VirtualJoystick(leftJoystick) {
  61639. var _this = this;
  61640. if (leftJoystick) {
  61641. this._leftJoystick = true;
  61642. }
  61643. else {
  61644. this._leftJoystick = false;
  61645. }
  61646. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  61647. VirtualJoystick._globalJoystickIndex++;
  61648. // By default left & right arrow keys are moving the X
  61649. // and up & down keys are moving the Y
  61650. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  61651. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  61652. this.reverseLeftRight = false;
  61653. this.reverseUpDown = false;
  61654. // collections of pointers
  61655. this._touches = new BABYLON.StringDictionary();
  61656. this.deltaPosition = BABYLON.Vector3.Zero();
  61657. this._joystickSensibility = 25;
  61658. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  61659. this._rotationSpeed = 25;
  61660. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  61661. this._rotateOnAxisRelativeToMesh = false;
  61662. this._onResize = function (evt) {
  61663. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  61664. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  61665. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  61666. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  61667. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  61668. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  61669. };
  61670. // injecting a canvas element on top of the canvas 3D game
  61671. if (!VirtualJoystick.vjCanvas) {
  61672. window.addEventListener("resize", this._onResize, false);
  61673. VirtualJoystick.vjCanvas = document.createElement("canvas");
  61674. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  61675. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  61676. VirtualJoystick.vjCanvas.width = window.innerWidth;
  61677. VirtualJoystick.vjCanvas.height = window.innerHeight;
  61678. VirtualJoystick.vjCanvas.style.width = "100%";
  61679. VirtualJoystick.vjCanvas.style.height = "100%";
  61680. VirtualJoystick.vjCanvas.style.position = "absolute";
  61681. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  61682. VirtualJoystick.vjCanvas.style.top = "0px";
  61683. VirtualJoystick.vjCanvas.style.left = "0px";
  61684. VirtualJoystick.vjCanvas.style.zIndex = "5";
  61685. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  61686. // Support for jQuery PEP polyfill
  61687. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  61688. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  61689. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  61690. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  61691. document.body.appendChild(VirtualJoystick.vjCanvas);
  61692. }
  61693. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  61694. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  61695. this.pressed = false;
  61696. // default joystick color
  61697. this._joystickColor = "cyan";
  61698. this._joystickPointerID = -1;
  61699. // current joystick position
  61700. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  61701. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  61702. // origin joystick position
  61703. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  61704. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  61705. this._onPointerDownHandlerRef = function (evt) {
  61706. _this._onPointerDown(evt);
  61707. };
  61708. this._onPointerMoveHandlerRef = function (evt) {
  61709. _this._onPointerMove(evt);
  61710. };
  61711. this._onPointerOutHandlerRef = function (evt) {
  61712. _this._onPointerUp(evt);
  61713. };
  61714. this._onPointerUpHandlerRef = function (evt) {
  61715. _this._onPointerUp(evt);
  61716. };
  61717. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  61718. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  61719. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  61720. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  61721. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  61722. evt.preventDefault(); // Disables system menu
  61723. }, false);
  61724. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  61725. }
  61726. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  61727. this._joystickSensibility = newJoystickSensibility;
  61728. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  61729. };
  61730. VirtualJoystick.prototype._onPointerDown = function (e) {
  61731. var positionOnScreenCondition;
  61732. e.preventDefault();
  61733. if (this._leftJoystick === true) {
  61734. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  61735. }
  61736. else {
  61737. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  61738. }
  61739. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  61740. // First contact will be dedicated to the virtual joystick
  61741. this._joystickPointerID = e.pointerId;
  61742. this._joystickPointerStartPos.x = e.clientX;
  61743. this._joystickPointerStartPos.y = e.clientY;
  61744. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  61745. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  61746. this._deltaJoystickVector.x = 0;
  61747. this._deltaJoystickVector.y = 0;
  61748. this.pressed = true;
  61749. this._touches.add(e.pointerId.toString(), e);
  61750. }
  61751. else {
  61752. // You can only trigger the action buttons with a joystick declared
  61753. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  61754. this._action();
  61755. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  61756. }
  61757. }
  61758. };
  61759. VirtualJoystick.prototype._onPointerMove = function (e) {
  61760. // If the current pointer is the one associated to the joystick (first touch contact)
  61761. if (this._joystickPointerID == e.pointerId) {
  61762. this._joystickPointerPos.x = e.clientX;
  61763. this._joystickPointerPos.y = e.clientY;
  61764. this._deltaJoystickVector = this._joystickPointerPos.clone();
  61765. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  61766. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  61767. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  61768. switch (this._axisTargetedByLeftAndRight) {
  61769. case JoystickAxis.X:
  61770. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  61771. break;
  61772. case JoystickAxis.Y:
  61773. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  61774. break;
  61775. case JoystickAxis.Z:
  61776. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  61777. break;
  61778. }
  61779. var directionUpDown = this.reverseUpDown ? 1 : -1;
  61780. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  61781. switch (this._axisTargetedByUpAndDown) {
  61782. case JoystickAxis.X:
  61783. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  61784. break;
  61785. case JoystickAxis.Y:
  61786. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  61787. break;
  61788. case JoystickAxis.Z:
  61789. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  61790. break;
  61791. }
  61792. }
  61793. else {
  61794. var data = this._touches.get(e.pointerId.toString());
  61795. if (data) {
  61796. data.x = e.clientX;
  61797. data.y = e.clientY;
  61798. }
  61799. }
  61800. };
  61801. VirtualJoystick.prototype._onPointerUp = function (e) {
  61802. if (this._joystickPointerID == e.pointerId) {
  61803. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  61804. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  61805. this._joystickPointerID = -1;
  61806. this.pressed = false;
  61807. }
  61808. else {
  61809. var touch = this._touches.get(e.pointerId.toString());
  61810. if (touch) {
  61811. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  61812. }
  61813. }
  61814. this._deltaJoystickVector.x = 0;
  61815. this._deltaJoystickVector.y = 0;
  61816. this._touches.remove(e.pointerId.toString());
  61817. };
  61818. /**
  61819. * Change the color of the virtual joystick
  61820. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  61821. */
  61822. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  61823. this._joystickColor = newColor;
  61824. };
  61825. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  61826. this._action = action;
  61827. };
  61828. // Define which axis you'd like to control for left & right
  61829. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  61830. switch (axis) {
  61831. case JoystickAxis.X:
  61832. case JoystickAxis.Y:
  61833. case JoystickAxis.Z:
  61834. this._axisTargetedByLeftAndRight = axis;
  61835. break;
  61836. default:
  61837. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  61838. break;
  61839. }
  61840. };
  61841. // Define which axis you'd like to control for up & down
  61842. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  61843. switch (axis) {
  61844. case JoystickAxis.X:
  61845. case JoystickAxis.Y:
  61846. case JoystickAxis.Z:
  61847. this._axisTargetedByUpAndDown = axis;
  61848. break;
  61849. default:
  61850. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  61851. break;
  61852. }
  61853. };
  61854. VirtualJoystick.prototype._clearCanvas = function () {
  61855. if (this._leftJoystick) {
  61856. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  61857. }
  61858. else {
  61859. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  61860. }
  61861. };
  61862. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  61863. var _this = this;
  61864. if (this.pressed) {
  61865. this._touches.forEach(function (key, touch) {
  61866. if (touch.pointerId === _this._joystickPointerID) {
  61867. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  61868. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  61869. VirtualJoystick.vjCanvasContext.beginPath();
  61870. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  61871. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  61872. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  61873. VirtualJoystick.vjCanvasContext.stroke();
  61874. VirtualJoystick.vjCanvasContext.closePath();
  61875. VirtualJoystick.vjCanvasContext.beginPath();
  61876. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  61877. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  61878. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  61879. VirtualJoystick.vjCanvasContext.stroke();
  61880. VirtualJoystick.vjCanvasContext.closePath();
  61881. VirtualJoystick.vjCanvasContext.beginPath();
  61882. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  61883. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  61884. VirtualJoystick.vjCanvasContext.stroke();
  61885. VirtualJoystick.vjCanvasContext.closePath();
  61886. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  61887. }
  61888. else {
  61889. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  61890. VirtualJoystick.vjCanvasContext.beginPath();
  61891. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  61892. VirtualJoystick.vjCanvasContext.beginPath();
  61893. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  61894. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  61895. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  61896. VirtualJoystick.vjCanvasContext.stroke();
  61897. VirtualJoystick.vjCanvasContext.closePath();
  61898. touch.prevX = touch.x;
  61899. touch.prevY = touch.y;
  61900. }
  61901. ;
  61902. });
  61903. }
  61904. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  61905. };
  61906. VirtualJoystick.prototype.releaseCanvas = function () {
  61907. if (VirtualJoystick.vjCanvas) {
  61908. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  61909. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  61910. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  61911. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  61912. window.removeEventListener("resize", this._onResize);
  61913. document.body.removeChild(VirtualJoystick.vjCanvas);
  61914. VirtualJoystick.vjCanvas = null;
  61915. }
  61916. };
  61917. return VirtualJoystick;
  61918. }());
  61919. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  61920. VirtualJoystick._globalJoystickIndex = 0;
  61921. BABYLON.VirtualJoystick = VirtualJoystick;
  61922. })(BABYLON || (BABYLON = {}));
  61923. //# sourceMappingURL=babylon.virtualJoystick.js.map
  61924. var BABYLON;
  61925. (function (BABYLON) {
  61926. // We're mainly based on the logic defined into the FreeCamera code
  61927. var VirtualJoysticksCamera = (function (_super) {
  61928. __extends(VirtualJoysticksCamera, _super);
  61929. function VirtualJoysticksCamera(name, position, scene) {
  61930. var _this = _super.call(this, name, position, scene) || this;
  61931. _this.inputs.addVirtualJoystick();
  61932. return _this;
  61933. }
  61934. VirtualJoysticksCamera.prototype.getClassName = function () {
  61935. return "VirtualJoysticksCamera";
  61936. };
  61937. return VirtualJoysticksCamera;
  61938. }(BABYLON.FreeCamera));
  61939. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  61940. })(BABYLON || (BABYLON = {}));
  61941. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  61942. var BABYLON;
  61943. (function (BABYLON) {
  61944. var FreeCameraVirtualJoystickInput = (function () {
  61945. function FreeCameraVirtualJoystickInput() {
  61946. }
  61947. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  61948. return this._leftjoystick;
  61949. };
  61950. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  61951. return this._rightjoystick;
  61952. };
  61953. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  61954. if (this._leftjoystick) {
  61955. var camera = this.camera;
  61956. var speed = camera._computeLocalCameraSpeed() * 50;
  61957. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  61958. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  61959. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  61960. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  61961. if (!this._leftjoystick.pressed) {
  61962. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  61963. }
  61964. if (!this._rightjoystick.pressed) {
  61965. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  61966. }
  61967. }
  61968. };
  61969. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  61970. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  61971. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  61972. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  61973. this._leftjoystick.setJoystickSensibility(0.15);
  61974. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  61975. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  61976. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  61977. this._rightjoystick.reverseUpDown = true;
  61978. this._rightjoystick.setJoystickSensibility(0.05);
  61979. this._rightjoystick.setJoystickColor("yellow");
  61980. };
  61981. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  61982. this._leftjoystick.releaseCanvas();
  61983. this._rightjoystick.releaseCanvas();
  61984. };
  61985. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  61986. return "FreeCameraVirtualJoystickInput";
  61987. };
  61988. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  61989. return "virtualJoystick";
  61990. };
  61991. return FreeCameraVirtualJoystickInput;
  61992. }());
  61993. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  61994. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  61995. })(BABYLON || (BABYLON = {}));
  61996. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  61997. var BABYLON;
  61998. (function (BABYLON) {
  61999. var SimplificationSettings = (function () {
  62000. function SimplificationSettings(quality, distance, optimizeMesh) {
  62001. this.quality = quality;
  62002. this.distance = distance;
  62003. this.optimizeMesh = optimizeMesh;
  62004. }
  62005. return SimplificationSettings;
  62006. }());
  62007. BABYLON.SimplificationSettings = SimplificationSettings;
  62008. var SimplificationQueue = (function () {
  62009. function SimplificationQueue() {
  62010. this.running = false;
  62011. this._simplificationArray = [];
  62012. }
  62013. SimplificationQueue.prototype.addTask = function (task) {
  62014. this._simplificationArray.push(task);
  62015. };
  62016. SimplificationQueue.prototype.executeNext = function () {
  62017. var task = this._simplificationArray.pop();
  62018. if (task) {
  62019. this.running = true;
  62020. this.runSimplification(task);
  62021. }
  62022. else {
  62023. this.running = false;
  62024. }
  62025. };
  62026. SimplificationQueue.prototype.runSimplification = function (task) {
  62027. var _this = this;
  62028. if (task.parallelProcessing) {
  62029. //parallel simplifier
  62030. task.settings.forEach(function (setting) {
  62031. var simplifier = _this.getSimplifier(task);
  62032. simplifier.simplify(setting, function (newMesh) {
  62033. task.mesh.addLODLevel(setting.distance, newMesh);
  62034. newMesh.isVisible = true;
  62035. //check if it is the last
  62036. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  62037. //all done, run the success callback.
  62038. task.successCallback();
  62039. }
  62040. _this.executeNext();
  62041. });
  62042. });
  62043. }
  62044. else {
  62045. //single simplifier.
  62046. var simplifier = this.getSimplifier(task);
  62047. var runDecimation = function (setting, callback) {
  62048. simplifier.simplify(setting, function (newMesh) {
  62049. task.mesh.addLODLevel(setting.distance, newMesh);
  62050. newMesh.isVisible = true;
  62051. //run the next quality level
  62052. callback();
  62053. });
  62054. };
  62055. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  62056. runDecimation(task.settings[loop.index], function () {
  62057. loop.executeNext();
  62058. });
  62059. }, function () {
  62060. //execution ended, run the success callback.
  62061. if (task.successCallback) {
  62062. task.successCallback();
  62063. }
  62064. _this.executeNext();
  62065. });
  62066. }
  62067. };
  62068. SimplificationQueue.prototype.getSimplifier = function (task) {
  62069. switch (task.simplificationType) {
  62070. case SimplificationType.QUADRATIC:
  62071. default:
  62072. return new QuadraticErrorSimplification(task.mesh);
  62073. }
  62074. };
  62075. return SimplificationQueue;
  62076. }());
  62077. BABYLON.SimplificationQueue = SimplificationQueue;
  62078. /**
  62079. * The implemented types of simplification.
  62080. * At the moment only Quadratic Error Decimation is implemented.
  62081. */
  62082. var SimplificationType;
  62083. (function (SimplificationType) {
  62084. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  62085. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  62086. var DecimationTriangle = (function () {
  62087. function DecimationTriangle(vertices) {
  62088. this.vertices = vertices;
  62089. this.error = new Array(4);
  62090. this.deleted = false;
  62091. this.isDirty = false;
  62092. this.deletePending = false;
  62093. this.borderFactor = 0;
  62094. }
  62095. return DecimationTriangle;
  62096. }());
  62097. BABYLON.DecimationTriangle = DecimationTriangle;
  62098. var DecimationVertex = (function () {
  62099. function DecimationVertex(position, id) {
  62100. this.position = position;
  62101. this.id = id;
  62102. this.isBorder = true;
  62103. this.q = new QuadraticMatrix();
  62104. this.triangleCount = 0;
  62105. this.triangleStart = 0;
  62106. this.originalOffsets = [];
  62107. }
  62108. DecimationVertex.prototype.updatePosition = function (newPosition) {
  62109. this.position.copyFrom(newPosition);
  62110. };
  62111. return DecimationVertex;
  62112. }());
  62113. BABYLON.DecimationVertex = DecimationVertex;
  62114. var QuadraticMatrix = (function () {
  62115. function QuadraticMatrix(data) {
  62116. this.data = new Array(10);
  62117. for (var i = 0; i < 10; ++i) {
  62118. if (data && data[i]) {
  62119. this.data[i] = data[i];
  62120. }
  62121. else {
  62122. this.data[i] = 0;
  62123. }
  62124. }
  62125. }
  62126. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  62127. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  62128. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  62129. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  62130. return det;
  62131. };
  62132. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  62133. for (var i = 0; i < 10; ++i) {
  62134. this.data[i] += matrix.data[i];
  62135. }
  62136. };
  62137. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  62138. for (var i = 0; i < 10; ++i) {
  62139. this.data[i] += data[i];
  62140. }
  62141. };
  62142. QuadraticMatrix.prototype.add = function (matrix) {
  62143. var m = new QuadraticMatrix();
  62144. for (var i = 0; i < 10; ++i) {
  62145. m.data[i] = this.data[i] + matrix.data[i];
  62146. }
  62147. return m;
  62148. };
  62149. QuadraticMatrix.FromData = function (a, b, c, d) {
  62150. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  62151. };
  62152. //returning an array to avoid garbage collection
  62153. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  62154. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  62155. };
  62156. return QuadraticMatrix;
  62157. }());
  62158. BABYLON.QuadraticMatrix = QuadraticMatrix;
  62159. var Reference = (function () {
  62160. function Reference(vertexId, triangleId) {
  62161. this.vertexId = vertexId;
  62162. this.triangleId = triangleId;
  62163. }
  62164. return Reference;
  62165. }());
  62166. BABYLON.Reference = Reference;
  62167. /**
  62168. * An implementation of the Quadratic Error simplification algorithm.
  62169. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  62170. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  62171. * @author RaananW
  62172. */
  62173. var QuadraticErrorSimplification = (function () {
  62174. function QuadraticErrorSimplification(_mesh) {
  62175. this._mesh = _mesh;
  62176. this.initialized = false;
  62177. this.syncIterations = 5000;
  62178. this.aggressiveness = 7;
  62179. this.decimationIterations = 100;
  62180. this.boundingBoxEpsilon = BABYLON.Epsilon;
  62181. }
  62182. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  62183. var _this = this;
  62184. this.initDecimatedMesh();
  62185. //iterating through the submeshes array, one after the other.
  62186. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  62187. _this.initWithMesh(loop.index, function () {
  62188. _this.runDecimation(settings, loop.index, function () {
  62189. loop.executeNext();
  62190. });
  62191. }, settings.optimizeMesh);
  62192. }, function () {
  62193. setTimeout(function () {
  62194. successCallback(_this._reconstructedMesh);
  62195. }, 0);
  62196. });
  62197. };
  62198. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  62199. var _this = this;
  62200. var gCount = 0;
  62201. triangle.vertices.forEach(function (vertex) {
  62202. var count = 0;
  62203. var vPos = vertex.position;
  62204. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  62205. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  62206. ++count;
  62207. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  62208. ++count;
  62209. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  62210. ++count;
  62211. if (count > 1) {
  62212. ++gCount;
  62213. }
  62214. ;
  62215. });
  62216. if (gCount > 1) {
  62217. console.log(triangle, gCount);
  62218. }
  62219. return gCount > 1;
  62220. };
  62221. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  62222. var _this = this;
  62223. var targetCount = ~~(this.triangles.length * settings.quality);
  62224. var deletedTriangles = 0;
  62225. var triangleCount = this.triangles.length;
  62226. var iterationFunction = function (iteration, callback) {
  62227. setTimeout(function () {
  62228. if (iteration % 5 === 0) {
  62229. _this.updateMesh(iteration === 0);
  62230. }
  62231. for (var i = 0; i < _this.triangles.length; ++i) {
  62232. _this.triangles[i].isDirty = false;
  62233. }
  62234. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  62235. var trianglesIterator = function (i) {
  62236. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  62237. var t = _this.triangles[tIdx];
  62238. if (!t)
  62239. return;
  62240. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  62241. return;
  62242. }
  62243. for (var j = 0; j < 3; ++j) {
  62244. if (t.error[j] < threshold) {
  62245. var deleted0 = [];
  62246. var deleted1 = [];
  62247. var v0 = t.vertices[j];
  62248. var v1 = t.vertices[(j + 1) % 3];
  62249. if (v0.isBorder || v1.isBorder)
  62250. continue;
  62251. var p = BABYLON.Vector3.Zero();
  62252. var n = BABYLON.Vector3.Zero();
  62253. var uv = BABYLON.Vector2.Zero();
  62254. var color = new BABYLON.Color4(0, 0, 0, 1);
  62255. _this.calculateError(v0, v1, p, n, uv, color);
  62256. var delTr = [];
  62257. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  62258. continue;
  62259. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  62260. continue;
  62261. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  62262. continue;
  62263. var uniqueArray = [];
  62264. delTr.forEach(function (deletedT) {
  62265. if (uniqueArray.indexOf(deletedT) === -1) {
  62266. deletedT.deletePending = true;
  62267. uniqueArray.push(deletedT);
  62268. }
  62269. });
  62270. if (uniqueArray.length % 2 !== 0) {
  62271. continue;
  62272. }
  62273. v0.q = v1.q.add(v0.q);
  62274. v0.updatePosition(p);
  62275. var tStart = _this.references.length;
  62276. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  62277. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  62278. var tCount = _this.references.length - tStart;
  62279. if (tCount <= v0.triangleCount) {
  62280. if (tCount) {
  62281. for (var c = 0; c < tCount; c++) {
  62282. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  62283. }
  62284. }
  62285. }
  62286. else {
  62287. v0.triangleStart = tStart;
  62288. }
  62289. v0.triangleCount = tCount;
  62290. break;
  62291. }
  62292. }
  62293. };
  62294. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  62295. }, 0);
  62296. };
  62297. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  62298. if (triangleCount - deletedTriangles <= targetCount)
  62299. loop.breakLoop();
  62300. else {
  62301. iterationFunction(loop.index, function () {
  62302. loop.executeNext();
  62303. });
  62304. }
  62305. }, function () {
  62306. setTimeout(function () {
  62307. //reconstruct this part of the mesh
  62308. _this.reconstructMesh(submeshIndex);
  62309. successCallback();
  62310. }, 0);
  62311. });
  62312. };
  62313. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  62314. var _this = this;
  62315. this.vertices = [];
  62316. this.triangles = [];
  62317. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62318. var indices = this._mesh.getIndices();
  62319. var submesh = this._mesh.subMeshes[submeshIndex];
  62320. var findInVertices = function (positionToSearch) {
  62321. if (optimizeMesh) {
  62322. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  62323. if (_this.vertices[ii].position.equals(positionToSearch)) {
  62324. return _this.vertices[ii];
  62325. }
  62326. }
  62327. }
  62328. return null;
  62329. };
  62330. var vertexReferences = [];
  62331. var vertexInit = function (i) {
  62332. var offset = i + submesh.verticesStart;
  62333. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  62334. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  62335. vertex.originalOffsets.push(offset);
  62336. if (vertex.id === _this.vertices.length) {
  62337. _this.vertices.push(vertex);
  62338. }
  62339. vertexReferences.push(vertex.id);
  62340. };
  62341. //var totalVertices = mesh.getTotalVertices();
  62342. var totalVertices = submesh.verticesCount;
  62343. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  62344. var indicesInit = function (i) {
  62345. var offset = (submesh.indexStart / 3) + i;
  62346. var pos = (offset * 3);
  62347. var i0 = indices[pos + 0];
  62348. var i1 = indices[pos + 1];
  62349. var i2 = indices[pos + 2];
  62350. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  62351. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  62352. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  62353. var triangle = new DecimationTriangle([v0, v1, v2]);
  62354. triangle.originalOffset = pos;
  62355. _this.triangles.push(triangle);
  62356. };
  62357. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  62358. _this.init(callback);
  62359. });
  62360. });
  62361. };
  62362. QuadraticErrorSimplification.prototype.init = function (callback) {
  62363. var _this = this;
  62364. var triangleInit1 = function (i) {
  62365. var t = _this.triangles[i];
  62366. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  62367. for (var j = 0; j < 3; j++) {
  62368. 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))));
  62369. }
  62370. };
  62371. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  62372. var triangleInit2 = function (i) {
  62373. var t = _this.triangles[i];
  62374. for (var j = 0; j < 3; ++j) {
  62375. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  62376. }
  62377. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  62378. };
  62379. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  62380. _this.initialized = true;
  62381. callback();
  62382. });
  62383. });
  62384. };
  62385. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  62386. var newTriangles = [];
  62387. var i;
  62388. for (i = 0; i < this.vertices.length; ++i) {
  62389. this.vertices[i].triangleCount = 0;
  62390. }
  62391. var t;
  62392. var j;
  62393. for (i = 0; i < this.triangles.length; ++i) {
  62394. if (!this.triangles[i].deleted) {
  62395. t = this.triangles[i];
  62396. for (j = 0; j < 3; ++j) {
  62397. t.vertices[j].triangleCount = 1;
  62398. }
  62399. newTriangles.push(t);
  62400. }
  62401. }
  62402. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  62403. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  62404. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  62405. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  62406. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62407. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62408. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62409. var vertexCount = 0;
  62410. for (i = 0; i < this.vertices.length; ++i) {
  62411. var vertex = this.vertices[i];
  62412. vertex.id = vertexCount;
  62413. if (vertex.triangleCount) {
  62414. vertex.originalOffsets.forEach(function (originalOffset) {
  62415. newPositionData.push(vertex.position.x);
  62416. newPositionData.push(vertex.position.y);
  62417. newPositionData.push(vertex.position.z);
  62418. newNormalData.push(normalData[originalOffset * 3]);
  62419. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  62420. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  62421. if (uvs && uvs.length) {
  62422. newUVsData.push(uvs[(originalOffset * 2)]);
  62423. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  62424. }
  62425. else if (colorsData && colorsData.length) {
  62426. newColorsData.push(colorsData[(originalOffset * 4)]);
  62427. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  62428. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  62429. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  62430. }
  62431. ++vertexCount;
  62432. });
  62433. }
  62434. }
  62435. var startingIndex = this._reconstructedMesh.getTotalIndices();
  62436. var startingVertex = this._reconstructedMesh.getTotalVertices();
  62437. var submeshesArray = this._reconstructedMesh.subMeshes;
  62438. this._reconstructedMesh.subMeshes = [];
  62439. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  62440. var originalIndices = this._mesh.getIndices();
  62441. for (i = 0; i < newTriangles.length; ++i) {
  62442. t = newTriangles[i]; //now get the new referencing point for each vertex
  62443. [0, 1, 2].forEach(function (idx) {
  62444. var id = originalIndices[t.originalOffset + idx];
  62445. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  62446. if (offset < 0)
  62447. offset = 0;
  62448. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  62449. });
  62450. }
  62451. //overwriting the old vertex buffers and indices.
  62452. this._reconstructedMesh.setIndices(newIndicesArray);
  62453. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  62454. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  62455. if (newUVsData.length > 0)
  62456. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  62457. if (newColorsData.length > 0)
  62458. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  62459. //create submesh
  62460. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  62461. if (submeshIndex > 0) {
  62462. this._reconstructedMesh.subMeshes = [];
  62463. submeshesArray.forEach(function (submesh) {
  62464. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  62465. });
  62466. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  62467. }
  62468. };
  62469. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  62470. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  62471. this._reconstructedMesh.material = this._mesh.material;
  62472. this._reconstructedMesh.parent = this._mesh.parent;
  62473. this._reconstructedMesh.isVisible = false;
  62474. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  62475. };
  62476. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  62477. for (var i = 0; i < vertex1.triangleCount; ++i) {
  62478. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  62479. if (t.deleted)
  62480. continue;
  62481. var s = this.references[vertex1.triangleStart + i].vertexId;
  62482. var v1 = t.vertices[(s + 1) % 3];
  62483. var v2 = t.vertices[(s + 2) % 3];
  62484. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  62485. deletedArray[i] = true;
  62486. delTr.push(t);
  62487. continue;
  62488. }
  62489. var d1 = v1.position.subtract(point);
  62490. d1 = d1.normalize();
  62491. var d2 = v2.position.subtract(point);
  62492. d2 = d2.normalize();
  62493. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  62494. return true;
  62495. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  62496. deletedArray[i] = false;
  62497. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  62498. return true;
  62499. }
  62500. return false;
  62501. };
  62502. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  62503. var newDeleted = deletedTriangles;
  62504. for (var i = 0; i < vertex.triangleCount; ++i) {
  62505. var ref = this.references[vertex.triangleStart + i];
  62506. var t = this.triangles[ref.triangleId];
  62507. if (t.deleted)
  62508. continue;
  62509. if (deletedArray[i] && t.deletePending) {
  62510. t.deleted = true;
  62511. newDeleted++;
  62512. continue;
  62513. }
  62514. t.vertices[ref.vertexId] = origVertex;
  62515. t.isDirty = true;
  62516. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  62517. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  62518. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  62519. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  62520. this.references.push(ref);
  62521. }
  62522. return newDeleted;
  62523. };
  62524. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  62525. for (var i = 0; i < this.vertices.length; ++i) {
  62526. var vCount = [];
  62527. var vId = [];
  62528. var v = this.vertices[i];
  62529. var j;
  62530. for (j = 0; j < v.triangleCount; ++j) {
  62531. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  62532. for (var ii = 0; ii < 3; ii++) {
  62533. var ofs = 0;
  62534. var vv = triangle.vertices[ii];
  62535. while (ofs < vCount.length) {
  62536. if (vId[ofs] === vv.id)
  62537. break;
  62538. ++ofs;
  62539. }
  62540. if (ofs === vCount.length) {
  62541. vCount.push(1);
  62542. vId.push(vv.id);
  62543. }
  62544. else {
  62545. vCount[ofs]++;
  62546. }
  62547. }
  62548. }
  62549. for (j = 0; j < vCount.length; ++j) {
  62550. if (vCount[j] === 1) {
  62551. this.vertices[vId[j]].isBorder = true;
  62552. }
  62553. else {
  62554. this.vertices[vId[j]].isBorder = false;
  62555. }
  62556. }
  62557. }
  62558. };
  62559. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  62560. if (identifyBorders === void 0) { identifyBorders = false; }
  62561. var i;
  62562. if (!identifyBorders) {
  62563. var newTrianglesVector = [];
  62564. for (i = 0; i < this.triangles.length; ++i) {
  62565. if (!this.triangles[i].deleted) {
  62566. newTrianglesVector.push(this.triangles[i]);
  62567. }
  62568. }
  62569. this.triangles = newTrianglesVector;
  62570. }
  62571. for (i = 0; i < this.vertices.length; ++i) {
  62572. this.vertices[i].triangleCount = 0;
  62573. this.vertices[i].triangleStart = 0;
  62574. }
  62575. var t;
  62576. var j;
  62577. var v;
  62578. for (i = 0; i < this.triangles.length; ++i) {
  62579. t = this.triangles[i];
  62580. for (j = 0; j < 3; ++j) {
  62581. v = t.vertices[j];
  62582. v.triangleCount++;
  62583. }
  62584. }
  62585. var tStart = 0;
  62586. for (i = 0; i < this.vertices.length; ++i) {
  62587. this.vertices[i].triangleStart = tStart;
  62588. tStart += this.vertices[i].triangleCount;
  62589. this.vertices[i].triangleCount = 0;
  62590. }
  62591. var newReferences = new Array(this.triangles.length * 3);
  62592. for (i = 0; i < this.triangles.length; ++i) {
  62593. t = this.triangles[i];
  62594. for (j = 0; j < 3; ++j) {
  62595. v = t.vertices[j];
  62596. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  62597. v.triangleCount++;
  62598. }
  62599. }
  62600. this.references = newReferences;
  62601. if (identifyBorders) {
  62602. this.identifyBorder();
  62603. }
  62604. };
  62605. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  62606. var x = point.x;
  62607. var y = point.y;
  62608. var z = point.z;
  62609. 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
  62610. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  62611. };
  62612. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  62613. var q = vertex1.q.add(vertex2.q);
  62614. var border = vertex1.isBorder && vertex2.isBorder;
  62615. var error = 0;
  62616. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  62617. if (qDet !== 0 && !border) {
  62618. if (!pointResult) {
  62619. pointResult = BABYLON.Vector3.Zero();
  62620. }
  62621. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  62622. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  62623. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  62624. error = this.vertexError(q, pointResult);
  62625. }
  62626. else {
  62627. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  62628. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  62629. var error1 = this.vertexError(q, vertex1.position);
  62630. var error2 = this.vertexError(q, vertex2.position);
  62631. var error3 = this.vertexError(q, p3);
  62632. error = Math.min(error1, error2, error3);
  62633. if (error === error1) {
  62634. if (pointResult) {
  62635. pointResult.copyFrom(vertex1.position);
  62636. }
  62637. }
  62638. else if (error === error2) {
  62639. if (pointResult) {
  62640. pointResult.copyFrom(vertex2.position);
  62641. }
  62642. }
  62643. else {
  62644. if (pointResult) {
  62645. pointResult.copyFrom(p3);
  62646. }
  62647. }
  62648. }
  62649. return error;
  62650. };
  62651. return QuadraticErrorSimplification;
  62652. }());
  62653. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  62654. })(BABYLON || (BABYLON = {}));
  62655. //# sourceMappingURL=babylon.meshSimplification.js.map
  62656. var BABYLON;
  62657. (function (BABYLON) {
  62658. var Internals;
  62659. (function (Internals) {
  62660. var MeshLODLevel = (function () {
  62661. function MeshLODLevel(distance, mesh) {
  62662. this.distance = distance;
  62663. this.mesh = mesh;
  62664. }
  62665. return MeshLODLevel;
  62666. }());
  62667. Internals.MeshLODLevel = MeshLODLevel;
  62668. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62669. })(BABYLON || (BABYLON = {}));
  62670. //# sourceMappingURL=babylon.meshLODLevel.js.map
  62671. var BABYLON;
  62672. (function (BABYLON) {
  62673. // Standard optimizations
  62674. var SceneOptimization = (function () {
  62675. function SceneOptimization(priority) {
  62676. if (priority === void 0) { priority = 0; }
  62677. this.priority = priority;
  62678. this.apply = function (scene) {
  62679. return true; // Return true if everything that can be done was applied
  62680. };
  62681. }
  62682. return SceneOptimization;
  62683. }());
  62684. BABYLON.SceneOptimization = SceneOptimization;
  62685. var TextureOptimization = (function (_super) {
  62686. __extends(TextureOptimization, _super);
  62687. function TextureOptimization(priority, maximumSize) {
  62688. if (priority === void 0) { priority = 0; }
  62689. if (maximumSize === void 0) { maximumSize = 1024; }
  62690. var _this = _super.call(this, priority) || this;
  62691. _this.priority = priority;
  62692. _this.maximumSize = maximumSize;
  62693. _this.apply = function (scene) {
  62694. var allDone = true;
  62695. for (var index = 0; index < scene.textures.length; index++) {
  62696. var texture = scene.textures[index];
  62697. if (!texture.canRescale) {
  62698. continue;
  62699. }
  62700. var currentSize = texture.getSize();
  62701. var maxDimension = Math.max(currentSize.width, currentSize.height);
  62702. if (maxDimension > _this.maximumSize) {
  62703. texture.scale(0.5);
  62704. allDone = false;
  62705. }
  62706. }
  62707. return allDone;
  62708. };
  62709. return _this;
  62710. }
  62711. return TextureOptimization;
  62712. }(SceneOptimization));
  62713. BABYLON.TextureOptimization = TextureOptimization;
  62714. var HardwareScalingOptimization = (function (_super) {
  62715. __extends(HardwareScalingOptimization, _super);
  62716. function HardwareScalingOptimization(priority, maximumScale) {
  62717. if (priority === void 0) { priority = 0; }
  62718. if (maximumScale === void 0) { maximumScale = 2; }
  62719. var _this = _super.call(this, priority) || this;
  62720. _this.priority = priority;
  62721. _this.maximumScale = maximumScale;
  62722. _this._currentScale = 1;
  62723. _this.apply = function (scene) {
  62724. _this._currentScale++;
  62725. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  62726. return _this._currentScale >= _this.maximumScale;
  62727. };
  62728. return _this;
  62729. }
  62730. return HardwareScalingOptimization;
  62731. }(SceneOptimization));
  62732. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  62733. var ShadowsOptimization = (function (_super) {
  62734. __extends(ShadowsOptimization, _super);
  62735. function ShadowsOptimization() {
  62736. var _this = _super !== null && _super.apply(this, arguments) || this;
  62737. _this.apply = function (scene) {
  62738. scene.shadowsEnabled = false;
  62739. return true;
  62740. };
  62741. return _this;
  62742. }
  62743. return ShadowsOptimization;
  62744. }(SceneOptimization));
  62745. BABYLON.ShadowsOptimization = ShadowsOptimization;
  62746. var PostProcessesOptimization = (function (_super) {
  62747. __extends(PostProcessesOptimization, _super);
  62748. function PostProcessesOptimization() {
  62749. var _this = _super !== null && _super.apply(this, arguments) || this;
  62750. _this.apply = function (scene) {
  62751. scene.postProcessesEnabled = false;
  62752. return true;
  62753. };
  62754. return _this;
  62755. }
  62756. return PostProcessesOptimization;
  62757. }(SceneOptimization));
  62758. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  62759. var LensFlaresOptimization = (function (_super) {
  62760. __extends(LensFlaresOptimization, _super);
  62761. function LensFlaresOptimization() {
  62762. var _this = _super !== null && _super.apply(this, arguments) || this;
  62763. _this.apply = function (scene) {
  62764. scene.lensFlaresEnabled = false;
  62765. return true;
  62766. };
  62767. return _this;
  62768. }
  62769. return LensFlaresOptimization;
  62770. }(SceneOptimization));
  62771. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  62772. var ParticlesOptimization = (function (_super) {
  62773. __extends(ParticlesOptimization, _super);
  62774. function ParticlesOptimization() {
  62775. var _this = _super !== null && _super.apply(this, arguments) || this;
  62776. _this.apply = function (scene) {
  62777. scene.particlesEnabled = false;
  62778. return true;
  62779. };
  62780. return _this;
  62781. }
  62782. return ParticlesOptimization;
  62783. }(SceneOptimization));
  62784. BABYLON.ParticlesOptimization = ParticlesOptimization;
  62785. var RenderTargetsOptimization = (function (_super) {
  62786. __extends(RenderTargetsOptimization, _super);
  62787. function RenderTargetsOptimization() {
  62788. var _this = _super !== null && _super.apply(this, arguments) || this;
  62789. _this.apply = function (scene) {
  62790. scene.renderTargetsEnabled = false;
  62791. return true;
  62792. };
  62793. return _this;
  62794. }
  62795. return RenderTargetsOptimization;
  62796. }(SceneOptimization));
  62797. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  62798. var MergeMeshesOptimization = (function (_super) {
  62799. __extends(MergeMeshesOptimization, _super);
  62800. function MergeMeshesOptimization() {
  62801. var _this = _super !== null && _super.apply(this, arguments) || this;
  62802. _this._canBeMerged = function (abstractMesh) {
  62803. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  62804. return false;
  62805. }
  62806. var mesh = abstractMesh;
  62807. if (!mesh.isVisible || !mesh.isEnabled()) {
  62808. return false;
  62809. }
  62810. if (mesh.instances.length > 0) {
  62811. return false;
  62812. }
  62813. if (mesh.skeleton || mesh.hasLODLevels) {
  62814. return false;
  62815. }
  62816. if (mesh.parent) {
  62817. return false;
  62818. }
  62819. return true;
  62820. };
  62821. _this.apply = function (scene, updateSelectionTree) {
  62822. var globalPool = scene.meshes.slice(0);
  62823. var globalLength = globalPool.length;
  62824. for (var index = 0; index < globalLength; index++) {
  62825. var currentPool = new Array();
  62826. var current = globalPool[index];
  62827. // Checks
  62828. if (!_this._canBeMerged(current)) {
  62829. continue;
  62830. }
  62831. currentPool.push(current);
  62832. // Find compatible meshes
  62833. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  62834. var otherMesh = globalPool[subIndex];
  62835. if (!_this._canBeMerged(otherMesh)) {
  62836. continue;
  62837. }
  62838. if (otherMesh.material !== current.material) {
  62839. continue;
  62840. }
  62841. if (otherMesh.checkCollisions !== current.checkCollisions) {
  62842. continue;
  62843. }
  62844. currentPool.push(otherMesh);
  62845. globalLength--;
  62846. globalPool.splice(subIndex, 1);
  62847. subIndex--;
  62848. }
  62849. if (currentPool.length < 2) {
  62850. continue;
  62851. }
  62852. // Merge meshes
  62853. BABYLON.Mesh.MergeMeshes(currentPool);
  62854. }
  62855. if (updateSelectionTree != undefined) {
  62856. if (updateSelectionTree) {
  62857. scene.createOrUpdateSelectionOctree();
  62858. }
  62859. }
  62860. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  62861. scene.createOrUpdateSelectionOctree();
  62862. }
  62863. return true;
  62864. };
  62865. return _this;
  62866. }
  62867. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  62868. get: function () {
  62869. return MergeMeshesOptimization._UpdateSelectionTree;
  62870. },
  62871. set: function (value) {
  62872. MergeMeshesOptimization._UpdateSelectionTree = value;
  62873. },
  62874. enumerable: true,
  62875. configurable: true
  62876. });
  62877. return MergeMeshesOptimization;
  62878. }(SceneOptimization));
  62879. MergeMeshesOptimization._UpdateSelectionTree = false;
  62880. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  62881. // Options
  62882. var SceneOptimizerOptions = (function () {
  62883. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  62884. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  62885. if (trackerDuration === void 0) { trackerDuration = 2000; }
  62886. this.targetFrameRate = targetFrameRate;
  62887. this.trackerDuration = trackerDuration;
  62888. this.optimizations = new Array();
  62889. }
  62890. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  62891. var result = new SceneOptimizerOptions(targetFrameRate);
  62892. var priority = 0;
  62893. result.optimizations.push(new MergeMeshesOptimization(priority));
  62894. result.optimizations.push(new ShadowsOptimization(priority));
  62895. result.optimizations.push(new LensFlaresOptimization(priority));
  62896. // Next priority
  62897. priority++;
  62898. result.optimizations.push(new PostProcessesOptimization(priority));
  62899. result.optimizations.push(new ParticlesOptimization(priority));
  62900. // Next priority
  62901. priority++;
  62902. result.optimizations.push(new TextureOptimization(priority, 1024));
  62903. return result;
  62904. };
  62905. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  62906. var result = new SceneOptimizerOptions(targetFrameRate);
  62907. var priority = 0;
  62908. result.optimizations.push(new MergeMeshesOptimization(priority));
  62909. result.optimizations.push(new ShadowsOptimization(priority));
  62910. result.optimizations.push(new LensFlaresOptimization(priority));
  62911. // Next priority
  62912. priority++;
  62913. result.optimizations.push(new PostProcessesOptimization(priority));
  62914. result.optimizations.push(new ParticlesOptimization(priority));
  62915. // Next priority
  62916. priority++;
  62917. result.optimizations.push(new TextureOptimization(priority, 512));
  62918. // Next priority
  62919. priority++;
  62920. result.optimizations.push(new RenderTargetsOptimization(priority));
  62921. // Next priority
  62922. priority++;
  62923. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  62924. return result;
  62925. };
  62926. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  62927. var result = new SceneOptimizerOptions(targetFrameRate);
  62928. var priority = 0;
  62929. result.optimizations.push(new MergeMeshesOptimization(priority));
  62930. result.optimizations.push(new ShadowsOptimization(priority));
  62931. result.optimizations.push(new LensFlaresOptimization(priority));
  62932. // Next priority
  62933. priority++;
  62934. result.optimizations.push(new PostProcessesOptimization(priority));
  62935. result.optimizations.push(new ParticlesOptimization(priority));
  62936. // Next priority
  62937. priority++;
  62938. result.optimizations.push(new TextureOptimization(priority, 256));
  62939. // Next priority
  62940. priority++;
  62941. result.optimizations.push(new RenderTargetsOptimization(priority));
  62942. // Next priority
  62943. priority++;
  62944. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  62945. return result;
  62946. };
  62947. return SceneOptimizerOptions;
  62948. }());
  62949. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  62950. // Scene optimizer tool
  62951. var SceneOptimizer = (function () {
  62952. function SceneOptimizer() {
  62953. }
  62954. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  62955. // TODO: add an epsilon
  62956. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  62957. if (onSuccess) {
  62958. onSuccess();
  62959. }
  62960. return;
  62961. }
  62962. // Apply current level of optimizations
  62963. var allDone = true;
  62964. var noOptimizationApplied = true;
  62965. for (var index = 0; index < options.optimizations.length; index++) {
  62966. var optimization = options.optimizations[index];
  62967. if (optimization.priority === currentPriorityLevel) {
  62968. noOptimizationApplied = false;
  62969. allDone = allDone && optimization.apply(scene);
  62970. }
  62971. }
  62972. // If no optimization was applied, this is a failure :(
  62973. if (noOptimizationApplied) {
  62974. if (onFailure) {
  62975. onFailure();
  62976. }
  62977. return;
  62978. }
  62979. // If all optimizations were done, move to next level
  62980. if (allDone) {
  62981. currentPriorityLevel++;
  62982. }
  62983. // Let's the system running for a specific amount of time before checking FPS
  62984. scene.executeWhenReady(function () {
  62985. setTimeout(function () {
  62986. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  62987. }, options.trackerDuration);
  62988. });
  62989. };
  62990. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  62991. if (!options) {
  62992. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  62993. }
  62994. // Let's the system running for a specific amount of time before checking FPS
  62995. scene.executeWhenReady(function () {
  62996. setTimeout(function () {
  62997. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  62998. }, options.trackerDuration);
  62999. });
  63000. };
  63001. return SceneOptimizer;
  63002. }());
  63003. BABYLON.SceneOptimizer = SceneOptimizer;
  63004. })(BABYLON || (BABYLON = {}));
  63005. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  63006. var BABYLON;
  63007. (function (BABYLON) {
  63008. var OutlineRenderer = (function () {
  63009. function OutlineRenderer(scene) {
  63010. this._scene = scene;
  63011. }
  63012. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  63013. var _this = this;
  63014. if (useOverlay === void 0) { useOverlay = false; }
  63015. var scene = this._scene;
  63016. var engine = this._scene.getEngine();
  63017. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  63018. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  63019. return;
  63020. }
  63021. var mesh = subMesh.getRenderingMesh();
  63022. var material = subMesh.getMaterial();
  63023. engine.enableEffect(this._effect);
  63024. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  63025. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  63026. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  63027. // Bones
  63028. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63029. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  63030. }
  63031. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  63032. // Alpha test
  63033. if (material && material.needAlphaTesting()) {
  63034. var alphaTexture = material.getAlphaTestTexture();
  63035. this._effect.setTexture("diffuseSampler", alphaTexture);
  63036. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  63037. }
  63038. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  63039. };
  63040. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  63041. var defines = [];
  63042. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  63043. var mesh = subMesh.getMesh();
  63044. var material = subMesh.getMaterial();
  63045. // Alpha test
  63046. if (material && material.needAlphaTesting()) {
  63047. defines.push("#define ALPHATEST");
  63048. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63049. attribs.push(BABYLON.VertexBuffer.UVKind);
  63050. defines.push("#define UV1");
  63051. }
  63052. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  63053. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63054. defines.push("#define UV2");
  63055. }
  63056. }
  63057. // Bones
  63058. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63059. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63060. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63061. if (mesh.numBoneInfluencers > 4) {
  63062. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63063. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63064. }
  63065. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63066. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  63067. }
  63068. else {
  63069. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63070. }
  63071. // Instances
  63072. if (useInstances) {
  63073. defines.push("#define INSTANCES");
  63074. attribs.push("world0");
  63075. attribs.push("world1");
  63076. attribs.push("world2");
  63077. attribs.push("world3");
  63078. }
  63079. // Get correct effect
  63080. var join = defines.join("\n");
  63081. if (this._cachedDefines !== join) {
  63082. this._cachedDefines = join;
  63083. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  63084. }
  63085. return this._effect.isReady();
  63086. };
  63087. return OutlineRenderer;
  63088. }());
  63089. BABYLON.OutlineRenderer = OutlineRenderer;
  63090. })(BABYLON || (BABYLON = {}));
  63091. //# sourceMappingURL=babylon.outlineRenderer.js.map
  63092. var BABYLON;
  63093. (function (BABYLON) {
  63094. var FaceAdjacencies = (function () {
  63095. function FaceAdjacencies() {
  63096. this.edges = new Array();
  63097. this.edgesConnectedCount = 0;
  63098. }
  63099. return FaceAdjacencies;
  63100. }());
  63101. var EdgesRenderer = (function () {
  63102. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  63103. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  63104. if (epsilon === void 0) { epsilon = 0.95; }
  63105. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  63106. this.edgesWidthScalerForOrthographic = 1000.0;
  63107. this.edgesWidthScalerForPerspective = 50.0;
  63108. this._linesPositions = new Array();
  63109. this._linesNormals = new Array();
  63110. this._linesIndices = new Array();
  63111. this._buffers = {};
  63112. this._checkVerticesInsteadOfIndices = false;
  63113. this._source = source;
  63114. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  63115. this._epsilon = epsilon;
  63116. this._prepareRessources();
  63117. this._generateEdgesLines();
  63118. }
  63119. EdgesRenderer.prototype._prepareRessources = function () {
  63120. if (this._lineShader) {
  63121. return;
  63122. }
  63123. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  63124. attributes: ["position", "normal"],
  63125. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  63126. });
  63127. this._lineShader.disableDepthWrite = true;
  63128. this._lineShader.backFaceCulling = false;
  63129. };
  63130. EdgesRenderer.prototype.dispose = function () {
  63131. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  63132. if (buffer) {
  63133. buffer.dispose();
  63134. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  63135. }
  63136. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  63137. if (buffer) {
  63138. buffer.dispose();
  63139. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  63140. }
  63141. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  63142. this._lineShader.dispose();
  63143. };
  63144. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  63145. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  63146. return 0;
  63147. }
  63148. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  63149. return 1;
  63150. }
  63151. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  63152. return 2;
  63153. }
  63154. return -1;
  63155. };
  63156. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  63157. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  63158. return 0;
  63159. }
  63160. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  63161. return 1;
  63162. }
  63163. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  63164. return 2;
  63165. }
  63166. return -1;
  63167. };
  63168. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  63169. var needToCreateLine;
  63170. if (edge === undefined) {
  63171. needToCreateLine = true;
  63172. }
  63173. else {
  63174. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  63175. needToCreateLine = dotProduct < this._epsilon;
  63176. }
  63177. if (needToCreateLine) {
  63178. var offset = this._linesPositions.length / 3;
  63179. var normal = p0.subtract(p1);
  63180. normal.normalize();
  63181. // Positions
  63182. this._linesPositions.push(p0.x);
  63183. this._linesPositions.push(p0.y);
  63184. this._linesPositions.push(p0.z);
  63185. this._linesPositions.push(p0.x);
  63186. this._linesPositions.push(p0.y);
  63187. this._linesPositions.push(p0.z);
  63188. this._linesPositions.push(p1.x);
  63189. this._linesPositions.push(p1.y);
  63190. this._linesPositions.push(p1.z);
  63191. this._linesPositions.push(p1.x);
  63192. this._linesPositions.push(p1.y);
  63193. this._linesPositions.push(p1.z);
  63194. // Normals
  63195. this._linesNormals.push(p1.x);
  63196. this._linesNormals.push(p1.y);
  63197. this._linesNormals.push(p1.z);
  63198. this._linesNormals.push(-1);
  63199. this._linesNormals.push(p1.x);
  63200. this._linesNormals.push(p1.y);
  63201. this._linesNormals.push(p1.z);
  63202. this._linesNormals.push(1);
  63203. this._linesNormals.push(p0.x);
  63204. this._linesNormals.push(p0.y);
  63205. this._linesNormals.push(p0.z);
  63206. this._linesNormals.push(-1);
  63207. this._linesNormals.push(p0.x);
  63208. this._linesNormals.push(p0.y);
  63209. this._linesNormals.push(p0.z);
  63210. this._linesNormals.push(1);
  63211. // Indices
  63212. this._linesIndices.push(offset);
  63213. this._linesIndices.push(offset + 1);
  63214. this._linesIndices.push(offset + 2);
  63215. this._linesIndices.push(offset);
  63216. this._linesIndices.push(offset + 2);
  63217. this._linesIndices.push(offset + 3);
  63218. }
  63219. };
  63220. EdgesRenderer.prototype._generateEdgesLines = function () {
  63221. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63222. var indices = this._source.getIndices();
  63223. // First let's find adjacencies
  63224. var adjacencies = new Array();
  63225. var faceNormals = new Array();
  63226. var index;
  63227. var faceAdjacencies;
  63228. // Prepare faces
  63229. for (index = 0; index < indices.length; index += 3) {
  63230. faceAdjacencies = new FaceAdjacencies();
  63231. var p0Index = indices[index];
  63232. var p1Index = indices[index + 1];
  63233. var p2Index = indices[index + 2];
  63234. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  63235. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  63236. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  63237. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  63238. faceNormal.normalize();
  63239. faceNormals.push(faceNormal);
  63240. adjacencies.push(faceAdjacencies);
  63241. }
  63242. // Scan
  63243. for (index = 0; index < adjacencies.length; index++) {
  63244. faceAdjacencies = adjacencies[index];
  63245. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  63246. var otherFaceAdjacencies = adjacencies[otherIndex];
  63247. if (faceAdjacencies.edgesConnectedCount === 3) {
  63248. break;
  63249. }
  63250. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  63251. continue;
  63252. }
  63253. var otherP0 = indices[otherIndex * 3];
  63254. var otherP1 = indices[otherIndex * 3 + 1];
  63255. var otherP2 = indices[otherIndex * 3 + 2];
  63256. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  63257. var otherEdgeIndex;
  63258. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  63259. continue;
  63260. }
  63261. switch (edgeIndex) {
  63262. case 0:
  63263. if (this._checkVerticesInsteadOfIndices) {
  63264. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  63265. }
  63266. else {
  63267. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  63268. }
  63269. break;
  63270. case 1:
  63271. if (this._checkVerticesInsteadOfIndices) {
  63272. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  63273. }
  63274. else {
  63275. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  63276. }
  63277. break;
  63278. case 2:
  63279. if (this._checkVerticesInsteadOfIndices) {
  63280. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  63281. }
  63282. else {
  63283. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  63284. }
  63285. break;
  63286. }
  63287. if (otherEdgeIndex === -1) {
  63288. continue;
  63289. }
  63290. faceAdjacencies.edges[edgeIndex] = otherIndex;
  63291. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  63292. faceAdjacencies.edgesConnectedCount++;
  63293. otherFaceAdjacencies.edgesConnectedCount++;
  63294. if (faceAdjacencies.edgesConnectedCount === 3) {
  63295. break;
  63296. }
  63297. }
  63298. }
  63299. }
  63300. // Create lines
  63301. for (index = 0; index < adjacencies.length; index++) {
  63302. // 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
  63303. var current = adjacencies[index];
  63304. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  63305. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  63306. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  63307. }
  63308. // Merge into a single mesh
  63309. var engine = this._source.getScene().getEngine();
  63310. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  63311. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  63312. this._ib = engine.createIndexBuffer(this._linesIndices);
  63313. this._indicesCount = this._linesIndices.length;
  63314. };
  63315. EdgesRenderer.prototype.render = function () {
  63316. if (!this._lineShader.isReady()) {
  63317. return;
  63318. }
  63319. var scene = this._source.getScene();
  63320. var engine = scene.getEngine();
  63321. this._lineShader._preBind();
  63322. // VBOs
  63323. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  63324. scene.resetCachedMaterial();
  63325. this._lineShader.setColor4("color", this._source.edgesColor);
  63326. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  63327. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  63328. }
  63329. else {
  63330. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  63331. }
  63332. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  63333. this._lineShader.bind(this._source.getWorldMatrix());
  63334. // Draw order
  63335. engine.draw(true, 0, this._indicesCount);
  63336. this._lineShader.unbind();
  63337. engine.setDepthWrite(true);
  63338. };
  63339. return EdgesRenderer;
  63340. }());
  63341. BABYLON.EdgesRenderer = EdgesRenderer;
  63342. })(BABYLON || (BABYLON = {}));
  63343. //# sourceMappingURL=babylon.edgesRenderer.js.map
  63344. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  63345. /// <reference path="..\Math\babylon.math.ts" />
  63346. var BABYLON;
  63347. (function (BABYLON) {
  63348. /**
  63349. * Special Glow Blur post process only blurring the alpha channel
  63350. * It enforces keeping the most luminous color in the color channel.
  63351. */
  63352. var GlowBlurPostProcess = (function (_super) {
  63353. __extends(GlowBlurPostProcess, _super);
  63354. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  63355. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63356. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  63357. _this.direction = direction;
  63358. _this.kernel = kernel;
  63359. _this.onApplyObservable.add(function (effect) {
  63360. effect.setFloat2("screenSize", _this.width, _this.height);
  63361. effect.setVector2("direction", _this.direction);
  63362. effect.setFloat("blurWidth", _this.kernel);
  63363. });
  63364. return _this;
  63365. }
  63366. return GlowBlurPostProcess;
  63367. }(BABYLON.PostProcess));
  63368. /**
  63369. * The highlight layer Helps adding a glow effect around a mesh.
  63370. *
  63371. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  63372. * glowy meshes to your scene.
  63373. *
  63374. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  63375. */
  63376. var HighlightLayer = (function () {
  63377. /**
  63378. * Instantiates a new highlight Layer and references it to the scene..
  63379. * @param name The name of the layer
  63380. * @param scene The scene to use the layer in
  63381. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  63382. */
  63383. function HighlightLayer(name, scene, options) {
  63384. this.name = name;
  63385. this._vertexBuffers = {};
  63386. this._mainTextureDesiredSize = { width: 0, height: 0 };
  63387. this._meshes = {};
  63388. this._maxSize = 0;
  63389. this._shouldRender = false;
  63390. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  63391. this._excludedMeshes = {};
  63392. /**
  63393. * Specifies whether or not the inner glow is ACTIVE in the layer.
  63394. */
  63395. this.innerGlow = true;
  63396. /**
  63397. * Specifies whether or not the outer glow is ACTIVE in the layer.
  63398. */
  63399. this.outerGlow = true;
  63400. /**
  63401. * Specifies wether the highlight layer is enabled or not.
  63402. */
  63403. this.isEnabled = true;
  63404. /**
  63405. * An event triggered when the highlight layer has been disposed.
  63406. * @type {BABYLON.Observable}
  63407. */
  63408. this.onDisposeObservable = new BABYLON.Observable();
  63409. /**
  63410. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  63411. * @type {BABYLON.Observable}
  63412. */
  63413. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  63414. /**
  63415. * An event triggered when the highlight layer is being blurred.
  63416. * @type {BABYLON.Observable}
  63417. */
  63418. this.onBeforeBlurObservable = new BABYLON.Observable();
  63419. /**
  63420. * An event triggered when the highlight layer has been blurred.
  63421. * @type {BABYLON.Observable}
  63422. */
  63423. this.onAfterBlurObservable = new BABYLON.Observable();
  63424. /**
  63425. * An event triggered when the glowing blurred texture is being merged in the scene.
  63426. * @type {BABYLON.Observable}
  63427. */
  63428. this.onBeforeComposeObservable = new BABYLON.Observable();
  63429. /**
  63430. * An event triggered when the glowing blurred texture has been merged in the scene.
  63431. * @type {BABYLON.Observable}
  63432. */
  63433. this.onAfterComposeObservable = new BABYLON.Observable();
  63434. /**
  63435. * An event triggered when the highlight layer changes its size.
  63436. * @type {BABYLON.Observable}
  63437. */
  63438. this.onSizeChangedObservable = new BABYLON.Observable();
  63439. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63440. var engine = scene.getEngine();
  63441. this._engine = engine;
  63442. this._maxSize = this._engine.getCaps().maxTextureSize;
  63443. this._scene.highlightLayers.push(this);
  63444. // Warn on stencil.
  63445. if (!this._engine.isStencilEnable) {
  63446. 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 }");
  63447. }
  63448. // Adapt options
  63449. this._options = options || {
  63450. mainTextureRatio: 0.25,
  63451. blurTextureSizeRatio: 0.5,
  63452. blurHorizontalSize: 1,
  63453. blurVerticalSize: 1,
  63454. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  63455. };
  63456. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  63457. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  63458. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  63459. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  63460. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  63461. // VBO
  63462. var vertices = [];
  63463. vertices.push(1, 1);
  63464. vertices.push(-1, 1);
  63465. vertices.push(-1, -1);
  63466. vertices.push(1, -1);
  63467. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63468. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  63469. // Indices
  63470. var indices = [];
  63471. indices.push(0);
  63472. indices.push(1);
  63473. indices.push(2);
  63474. indices.push(0);
  63475. indices.push(2);
  63476. indices.push(3);
  63477. this._indexBuffer = engine.createIndexBuffer(indices);
  63478. // Effect
  63479. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  63480. // Render target
  63481. this.setMainTextureSize();
  63482. // Create Textures and post processes
  63483. this.createTextureAndPostProcesses();
  63484. }
  63485. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  63486. /**
  63487. * Gets the horizontal size of the blur.
  63488. */
  63489. get: function () {
  63490. return this._horizontalBlurPostprocess.kernel;
  63491. },
  63492. /**
  63493. * Specifies the horizontal size of the blur.
  63494. */
  63495. set: function (value) {
  63496. this._horizontalBlurPostprocess.kernel = value;
  63497. },
  63498. enumerable: true,
  63499. configurable: true
  63500. });
  63501. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  63502. /**
  63503. * Gets the vertical size of the blur.
  63504. */
  63505. get: function () {
  63506. return this._verticalBlurPostprocess.kernel;
  63507. },
  63508. /**
  63509. * Specifies the vertical size of the blur.
  63510. */
  63511. set: function (value) {
  63512. this._verticalBlurPostprocess.kernel = value;
  63513. },
  63514. enumerable: true,
  63515. configurable: true
  63516. });
  63517. Object.defineProperty(HighlightLayer.prototype, "camera", {
  63518. /**
  63519. * Gets the camera attached to the layer.
  63520. */
  63521. get: function () {
  63522. return this._options.camera;
  63523. },
  63524. enumerable: true,
  63525. configurable: true
  63526. });
  63527. /**
  63528. * Creates the render target textures and post processes used in the highlight layer.
  63529. */
  63530. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  63531. var _this = this;
  63532. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  63533. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  63534. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  63535. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  63536. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  63537. width: this._mainTextureDesiredSize.width,
  63538. height: this._mainTextureDesiredSize.height
  63539. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63540. this._mainTexture.activeCamera = this._options.camera;
  63541. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63542. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63543. this._mainTexture.anisotropicFilteringLevel = 1;
  63544. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63545. this._mainTexture.renderParticles = false;
  63546. this._mainTexture.renderList = null;
  63547. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  63548. width: blurTextureWidth,
  63549. height: blurTextureHeight
  63550. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63551. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63552. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63553. this._blurTexture.anisotropicFilteringLevel = 16;
  63554. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  63555. this._blurTexture.renderParticles = false;
  63556. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  63557. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  63558. effect.setTexture("textureSampler", _this._mainTexture);
  63559. });
  63560. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  63561. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  63562. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  63563. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  63564. });
  63565. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  63566. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  63567. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  63568. });
  63569. }
  63570. else {
  63571. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  63572. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  63573. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  63574. });
  63575. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  63576. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  63577. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  63578. });
  63579. }
  63580. this._mainTexture.onAfterUnbindObservable.add(function () {
  63581. _this.onBeforeBlurObservable.notifyObservers(_this);
  63582. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  63583. _this.onAfterBlurObservable.notifyObservers(_this);
  63584. });
  63585. // Custom render function
  63586. var renderSubMesh = function (subMesh) {
  63587. var mesh = subMesh.getRenderingMesh();
  63588. var scene = _this._scene;
  63589. var engine = scene.getEngine();
  63590. // Culling
  63591. engine.setState(subMesh.getMaterial().backFaceCulling);
  63592. // Managing instances
  63593. var batch = mesh._getInstancesRenderList(subMesh._id);
  63594. if (batch.mustReturn) {
  63595. return;
  63596. }
  63597. // Excluded Mesh
  63598. if (_this._excludedMeshes[mesh.uniqueId]) {
  63599. return;
  63600. }
  63601. ;
  63602. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  63603. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  63604. var material = subMesh.getMaterial();
  63605. var emissiveTexture = null;
  63606. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  63607. emissiveTexture = material.emissiveTexture;
  63608. }
  63609. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  63610. engine.enableEffect(_this._glowMapGenerationEffect);
  63611. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  63612. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  63613. if (highlightLayerMesh) {
  63614. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  63615. }
  63616. else {
  63617. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  63618. }
  63619. // Alpha test
  63620. if (material && material.needAlphaTesting()) {
  63621. var alphaTexture = material.getAlphaTestTexture();
  63622. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  63623. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  63624. }
  63625. // Glow emissive only
  63626. if (emissiveTexture) {
  63627. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  63628. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  63629. }
  63630. // Bones
  63631. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63632. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  63633. }
  63634. // Draw
  63635. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  63636. }
  63637. else {
  63638. // Need to reset refresh rate of the shadowMap
  63639. _this._mainTexture.resetRefreshCounter();
  63640. }
  63641. };
  63642. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  63643. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  63644. var index;
  63645. for (index = 0; index < opaqueSubMeshes.length; index++) {
  63646. renderSubMesh(opaqueSubMeshes.data[index]);
  63647. }
  63648. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  63649. renderSubMesh(alphaTestSubMeshes.data[index]);
  63650. }
  63651. for (index = 0; index < transparentSubMeshes.length; index++) {
  63652. renderSubMesh(transparentSubMeshes.data[index]);
  63653. }
  63654. };
  63655. this._mainTexture.onClearObservable.add(function (engine) {
  63656. engine.clear(HighlightLayer.neutralColor, true, true, true);
  63657. });
  63658. };
  63659. /**
  63660. * Checks for the readiness of the element composing the layer.
  63661. * @param subMesh the mesh to check for
  63662. * @param useInstances specify wether or not to use instances to render the mesh
  63663. * @param emissiveTexture the associated emissive texture used to generate the glow
  63664. * @return true if ready otherwise, false
  63665. */
  63666. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  63667. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  63668. return false;
  63669. }
  63670. var defines = [];
  63671. var attribs = [BABYLON.VertexBuffer.PositionKind];
  63672. var mesh = subMesh.getMesh();
  63673. var material = subMesh.getMaterial();
  63674. var uv1 = false;
  63675. var uv2 = false;
  63676. // Alpha test
  63677. if (material && material.needAlphaTesting()) {
  63678. var alphaTexture = material.getAlphaTestTexture();
  63679. if (alphaTexture) {
  63680. defines.push("#define ALPHATEST");
  63681. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  63682. alphaTexture.coordinatesIndex === 1) {
  63683. defines.push("#define DIFFUSEUV2");
  63684. uv2 = true;
  63685. }
  63686. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63687. defines.push("#define DIFFUSEUV1");
  63688. uv1 = true;
  63689. }
  63690. }
  63691. }
  63692. // Emissive
  63693. if (emissiveTexture) {
  63694. defines.push("#define EMISSIVE");
  63695. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  63696. emissiveTexture.coordinatesIndex === 1) {
  63697. defines.push("#define EMISSIVEUV2");
  63698. uv2 = true;
  63699. }
  63700. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63701. defines.push("#define EMISSIVEUV1");
  63702. uv1 = true;
  63703. }
  63704. }
  63705. if (uv1) {
  63706. attribs.push(BABYLON.VertexBuffer.UVKind);
  63707. defines.push("#define UV1");
  63708. }
  63709. if (uv2) {
  63710. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63711. defines.push("#define UV2");
  63712. }
  63713. // Bones
  63714. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63715. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63716. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63717. if (mesh.numBoneInfluencers > 4) {
  63718. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63719. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63720. }
  63721. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63722. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  63723. }
  63724. else {
  63725. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63726. }
  63727. // Instances
  63728. if (useInstances) {
  63729. defines.push("#define INSTANCES");
  63730. attribs.push("world0");
  63731. attribs.push("world1");
  63732. attribs.push("world2");
  63733. attribs.push("world3");
  63734. }
  63735. // Get correct effect
  63736. var join = defines.join("\n");
  63737. if (this._cachedDefines !== join) {
  63738. this._cachedDefines = join;
  63739. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  63740. }
  63741. return this._glowMapGenerationEffect.isReady();
  63742. };
  63743. /**
  63744. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  63745. */
  63746. HighlightLayer.prototype.render = function () {
  63747. var currentEffect = this._glowMapMergeEffect;
  63748. // Check
  63749. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  63750. return;
  63751. var engine = this._scene.getEngine();
  63752. this.onBeforeComposeObservable.notifyObservers(this);
  63753. // Render
  63754. engine.enableEffect(currentEffect);
  63755. engine.setState(false);
  63756. // Cache
  63757. var previousStencilBuffer = engine.getStencilBuffer();
  63758. var previousStencilFunction = engine.getStencilFunction();
  63759. var previousStencilMask = engine.getStencilMask();
  63760. var previousStencilOperationPass = engine.getStencilOperationPass();
  63761. var previousStencilOperationFail = engine.getStencilOperationFail();
  63762. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  63763. var previousAlphaMode = engine.getAlphaMode();
  63764. // Texture
  63765. currentEffect.setTexture("textureSampler", this._blurTexture);
  63766. // VBOs
  63767. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  63768. // Stencil operations
  63769. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  63770. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  63771. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  63772. // Draw order
  63773. engine.setAlphaMode(this._options.alphaBlendingMode);
  63774. engine.setStencilMask(0x00);
  63775. engine.setStencilBuffer(true);
  63776. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  63777. if (this.outerGlow) {
  63778. currentEffect.setFloat("offset", 0);
  63779. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  63780. engine.draw(true, 0, 6);
  63781. }
  63782. if (this.innerGlow) {
  63783. currentEffect.setFloat("offset", 1);
  63784. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  63785. engine.draw(true, 0, 6);
  63786. }
  63787. // Restore Cache
  63788. engine.setStencilFunction(previousStencilFunction);
  63789. engine.setStencilMask(previousStencilMask);
  63790. engine.setAlphaMode(previousAlphaMode);
  63791. engine.setStencilBuffer(previousStencilBuffer);
  63792. engine.setStencilOperationPass(previousStencilOperationPass);
  63793. engine.setStencilOperationFail(previousStencilOperationFail);
  63794. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  63795. engine._stencilState.reset();
  63796. this.onAfterComposeObservable.notifyObservers(this);
  63797. // Handle size changes.
  63798. var size = this._mainTexture.getSize();
  63799. this.setMainTextureSize();
  63800. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  63801. // Recreate RTT and post processes on size change.
  63802. this.onSizeChangedObservable.notifyObservers(this);
  63803. this.disposeTextureAndPostProcesses();
  63804. this.createTextureAndPostProcesses();
  63805. }
  63806. };
  63807. /**
  63808. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  63809. * @param mesh The mesh to exclude from the highlight layer
  63810. */
  63811. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  63812. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  63813. if (!meshExcluded) {
  63814. this._excludedMeshes[mesh.uniqueId] = {
  63815. mesh: mesh,
  63816. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  63817. mesh.getEngine().setStencilBuffer(false);
  63818. }),
  63819. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  63820. mesh.getEngine().setStencilBuffer(true);
  63821. }),
  63822. };
  63823. }
  63824. };
  63825. /**
  63826. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  63827. * @param mesh The mesh to highlight
  63828. */
  63829. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  63830. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  63831. if (meshExcluded) {
  63832. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  63833. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  63834. }
  63835. this._excludedMeshes[mesh.uniqueId] = undefined;
  63836. };
  63837. /**
  63838. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  63839. * @param mesh The mesh to highlight
  63840. * @param color The color of the highlight
  63841. * @param glowEmissiveOnly Extract the glow from the emissive texture
  63842. */
  63843. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  63844. var _this = this;
  63845. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  63846. var meshHighlight = this._meshes[mesh.uniqueId];
  63847. if (meshHighlight) {
  63848. meshHighlight.color = color;
  63849. }
  63850. else {
  63851. this._meshes[mesh.uniqueId] = {
  63852. mesh: mesh,
  63853. color: color,
  63854. // Lambda required for capture due to Observable this context
  63855. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  63856. if (_this._excludedMeshes[mesh.uniqueId]) {
  63857. _this.defaultStencilReference(mesh);
  63858. }
  63859. else {
  63860. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  63861. }
  63862. }),
  63863. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  63864. glowEmissiveOnly: glowEmissiveOnly
  63865. };
  63866. }
  63867. this._shouldRender = true;
  63868. };
  63869. /**
  63870. * Remove a mesh from the highlight layer in order to make it stop glowing.
  63871. * @param mesh The mesh to highlight
  63872. */
  63873. HighlightLayer.prototype.removeMesh = function (mesh) {
  63874. var meshHighlight = this._meshes[mesh.uniqueId];
  63875. if (meshHighlight) {
  63876. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  63877. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  63878. }
  63879. this._meshes[mesh.uniqueId] = undefined;
  63880. this._shouldRender = false;
  63881. for (var meshHighlightToCheck in this._meshes) {
  63882. if (meshHighlightToCheck) {
  63883. this._shouldRender = true;
  63884. break;
  63885. }
  63886. }
  63887. };
  63888. /**
  63889. * Returns true if the layer contains information to display, otherwise false.
  63890. */
  63891. HighlightLayer.prototype.shouldRender = function () {
  63892. return this.isEnabled && this._shouldRender;
  63893. };
  63894. /**
  63895. * Sets the main texture desired size which is the closest power of two
  63896. * of the engine canvas size.
  63897. */
  63898. HighlightLayer.prototype.setMainTextureSize = function () {
  63899. if (this._options.mainTextureFixedSize) {
  63900. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  63901. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  63902. }
  63903. else {
  63904. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  63905. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  63906. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  63907. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  63908. }
  63909. };
  63910. /**
  63911. * Force the stencil to the normal expected value for none glowing parts
  63912. */
  63913. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  63914. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  63915. };
  63916. /**
  63917. * Dispose only the render target textures and post process.
  63918. */
  63919. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  63920. this._blurTexture.dispose();
  63921. this._mainTexture.dispose();
  63922. this._downSamplePostprocess.dispose();
  63923. this._horizontalBlurPostprocess.dispose();
  63924. this._verticalBlurPostprocess.dispose();
  63925. };
  63926. /**
  63927. * Dispose the highlight layer and free resources.
  63928. */
  63929. HighlightLayer.prototype.dispose = function () {
  63930. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63931. if (vertexBuffer) {
  63932. vertexBuffer.dispose();
  63933. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63934. }
  63935. if (this._indexBuffer) {
  63936. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  63937. this._indexBuffer = null;
  63938. }
  63939. // Clean textures and post processes
  63940. this.disposeTextureAndPostProcesses();
  63941. // Clean mesh references
  63942. for (var id in this._meshes) {
  63943. var meshHighlight = this._meshes[id];
  63944. if (meshHighlight && meshHighlight.mesh) {
  63945. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  63946. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  63947. }
  63948. }
  63949. this._meshes = null;
  63950. for (var id in this._excludedMeshes) {
  63951. var meshHighlight = this._excludedMeshes[id];
  63952. if (meshHighlight) {
  63953. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  63954. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  63955. }
  63956. }
  63957. this._excludedMeshes = null;
  63958. // Remove from scene
  63959. var index = this._scene.highlightLayers.indexOf(this, 0);
  63960. if (index > -1) {
  63961. this._scene.highlightLayers.splice(index, 1);
  63962. }
  63963. // Callback
  63964. this.onDisposeObservable.notifyObservers(this);
  63965. this.onDisposeObservable.clear();
  63966. this.onBeforeRenderMainTextureObservable.clear();
  63967. this.onBeforeBlurObservable.clear();
  63968. this.onBeforeComposeObservable.clear();
  63969. this.onAfterComposeObservable.clear();
  63970. this.onSizeChangedObservable.clear();
  63971. };
  63972. return HighlightLayer;
  63973. }());
  63974. /**
  63975. * The neutral color used during the preparation of the glow effect.
  63976. * This is black by default as the blend operation is a blend operation.
  63977. */
  63978. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  63979. /**
  63980. * Stencil value used for glowing meshes.
  63981. */
  63982. HighlightLayer.glowingMeshStencilReference = 0x02;
  63983. /**
  63984. * Stencil value used for the other meshes in the scene.
  63985. */
  63986. HighlightLayer.normalMeshStencilReference = 0x01;
  63987. BABYLON.HighlightLayer = HighlightLayer;
  63988. })(BABYLON || (BABYLON = {}));
  63989. //# sourceMappingURL=babylon.highlightlayer.js.map
  63990. var BABYLON;
  63991. (function (BABYLON) {
  63992. var MeshAssetTask = (function () {
  63993. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  63994. this.name = name;
  63995. this.meshesNames = meshesNames;
  63996. this.rootUrl = rootUrl;
  63997. this.sceneFilename = sceneFilename;
  63998. this.isCompleted = false;
  63999. }
  64000. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64001. var _this = this;
  64002. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  64003. _this.loadedMeshes = meshes;
  64004. _this.loadedParticleSystems = particleSystems;
  64005. _this.loadedSkeletons = skeletons;
  64006. _this.isCompleted = true;
  64007. if (_this.onSuccess) {
  64008. _this.onSuccess(_this);
  64009. }
  64010. onSuccess();
  64011. }, null, function () {
  64012. if (_this.onError) {
  64013. _this.onError(_this);
  64014. }
  64015. onError();
  64016. });
  64017. };
  64018. return MeshAssetTask;
  64019. }());
  64020. BABYLON.MeshAssetTask = MeshAssetTask;
  64021. var TextFileAssetTask = (function () {
  64022. function TextFileAssetTask(name, url) {
  64023. this.name = name;
  64024. this.url = url;
  64025. this.isCompleted = false;
  64026. }
  64027. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64028. var _this = this;
  64029. BABYLON.Tools.LoadFile(this.url, function (data) {
  64030. _this.text = data;
  64031. _this.isCompleted = true;
  64032. if (_this.onSuccess) {
  64033. _this.onSuccess(_this);
  64034. }
  64035. onSuccess();
  64036. }, null, scene.database, false, function () {
  64037. if (_this.onError) {
  64038. _this.onError(_this);
  64039. }
  64040. onError();
  64041. });
  64042. };
  64043. return TextFileAssetTask;
  64044. }());
  64045. BABYLON.TextFileAssetTask = TextFileAssetTask;
  64046. var BinaryFileAssetTask = (function () {
  64047. function BinaryFileAssetTask(name, url) {
  64048. this.name = name;
  64049. this.url = url;
  64050. this.isCompleted = false;
  64051. }
  64052. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64053. var _this = this;
  64054. BABYLON.Tools.LoadFile(this.url, function (data) {
  64055. _this.data = data;
  64056. _this.isCompleted = true;
  64057. if (_this.onSuccess) {
  64058. _this.onSuccess(_this);
  64059. }
  64060. onSuccess();
  64061. }, null, scene.database, true, function () {
  64062. if (_this.onError) {
  64063. _this.onError(_this);
  64064. }
  64065. onError();
  64066. });
  64067. };
  64068. return BinaryFileAssetTask;
  64069. }());
  64070. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  64071. var ImageAssetTask = (function () {
  64072. function ImageAssetTask(name, url) {
  64073. this.name = name;
  64074. this.url = url;
  64075. this.isCompleted = false;
  64076. }
  64077. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64078. var _this = this;
  64079. var img = new Image();
  64080. BABYLON.Tools.SetCorsBehavior(this.url, img);
  64081. img.onload = function () {
  64082. _this.image = img;
  64083. _this.isCompleted = true;
  64084. if (_this.onSuccess) {
  64085. _this.onSuccess(_this);
  64086. }
  64087. onSuccess();
  64088. };
  64089. img.onerror = function () {
  64090. if (_this.onError) {
  64091. _this.onError(_this);
  64092. }
  64093. onError();
  64094. };
  64095. img.src = this.url;
  64096. };
  64097. return ImageAssetTask;
  64098. }());
  64099. BABYLON.ImageAssetTask = ImageAssetTask;
  64100. var TextureAssetTask = (function () {
  64101. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  64102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64103. this.name = name;
  64104. this.url = url;
  64105. this.noMipmap = noMipmap;
  64106. this.invertY = invertY;
  64107. this.samplingMode = samplingMode;
  64108. this.isCompleted = false;
  64109. }
  64110. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64111. var _this = this;
  64112. var onload = function () {
  64113. _this.isCompleted = true;
  64114. if (_this.onSuccess) {
  64115. _this.onSuccess(_this);
  64116. }
  64117. onSuccess();
  64118. };
  64119. var onerror = function () {
  64120. if (_this.onError) {
  64121. _this.onError(_this);
  64122. }
  64123. onError();
  64124. };
  64125. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  64126. };
  64127. return TextureAssetTask;
  64128. }());
  64129. BABYLON.TextureAssetTask = TextureAssetTask;
  64130. var CubeTextureAssetTask = (function () {
  64131. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  64132. this.name = name;
  64133. this.url = url;
  64134. this.extensions = extensions;
  64135. this.noMipmap = noMipmap;
  64136. this.files = files;
  64137. this.isCompleted = false;
  64138. }
  64139. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64140. var _this = this;
  64141. var onload = function () {
  64142. _this.isCompleted = true;
  64143. if (_this.onSuccess) {
  64144. _this.onSuccess(_this);
  64145. }
  64146. onSuccess();
  64147. };
  64148. var onerror = function () {
  64149. if (_this.onError) {
  64150. _this.onError(_this);
  64151. }
  64152. onError();
  64153. };
  64154. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  64155. };
  64156. return CubeTextureAssetTask;
  64157. }());
  64158. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  64159. var HDRCubeTextureAssetTask = (function () {
  64160. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  64161. if (noMipmap === void 0) { noMipmap = false; }
  64162. if (generateHarmonics === void 0) { generateHarmonics = true; }
  64163. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  64164. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  64165. this.name = name;
  64166. this.url = url;
  64167. this.size = size;
  64168. this.noMipmap = noMipmap;
  64169. this.generateHarmonics = generateHarmonics;
  64170. this.useInGammaSpace = useInGammaSpace;
  64171. this.usePMREMGenerator = usePMREMGenerator;
  64172. this.isCompleted = false;
  64173. }
  64174. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64175. var _this = this;
  64176. var onload = function () {
  64177. _this.isCompleted = true;
  64178. if (_this.onSuccess) {
  64179. _this.onSuccess(_this);
  64180. }
  64181. onSuccess();
  64182. };
  64183. var onerror = function () {
  64184. if (_this.onError) {
  64185. _this.onError(_this);
  64186. }
  64187. onError();
  64188. };
  64189. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  64190. };
  64191. return HDRCubeTextureAssetTask;
  64192. }());
  64193. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  64194. var AssetsManager = (function () {
  64195. function AssetsManager(scene) {
  64196. this.tasks = new Array();
  64197. this.waitingTasksCount = 0;
  64198. this.useDefaultLoadingScreen = true;
  64199. this._scene = scene;
  64200. }
  64201. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  64202. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  64203. this.tasks.push(task);
  64204. return task;
  64205. };
  64206. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  64207. var task = new TextFileAssetTask(taskName, url);
  64208. this.tasks.push(task);
  64209. return task;
  64210. };
  64211. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  64212. var task = new BinaryFileAssetTask(taskName, url);
  64213. this.tasks.push(task);
  64214. return task;
  64215. };
  64216. AssetsManager.prototype.addImageTask = function (taskName, url) {
  64217. var task = new ImageAssetTask(taskName, url);
  64218. this.tasks.push(task);
  64219. return task;
  64220. };
  64221. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  64222. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64223. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  64224. this.tasks.push(task);
  64225. return task;
  64226. };
  64227. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  64228. this.waitingTasksCount--;
  64229. if (this.waitingTasksCount === 0) {
  64230. if (this.onFinish) {
  64231. this.onFinish(this.tasks);
  64232. }
  64233. this._scene.getEngine().hideLoadingUI();
  64234. }
  64235. };
  64236. AssetsManager.prototype._runTask = function (task) {
  64237. var _this = this;
  64238. task.run(this._scene, function () {
  64239. if (_this.onTaskSuccess) {
  64240. _this.onTaskSuccess(task);
  64241. }
  64242. _this._decreaseWaitingTasksCount();
  64243. }, function () {
  64244. if (_this.onTaskError) {
  64245. _this.onTaskError(task);
  64246. }
  64247. _this._decreaseWaitingTasksCount();
  64248. });
  64249. };
  64250. AssetsManager.prototype.reset = function () {
  64251. this.tasks = new Array();
  64252. return this;
  64253. };
  64254. AssetsManager.prototype.load = function () {
  64255. this.waitingTasksCount = this.tasks.length;
  64256. if (this.waitingTasksCount === 0) {
  64257. if (this.onFinish) {
  64258. this.onFinish(this.tasks);
  64259. }
  64260. return this;
  64261. }
  64262. if (this.useDefaultLoadingScreen) {
  64263. this._scene.getEngine().displayLoadingUI();
  64264. }
  64265. for (var index = 0; index < this.tasks.length; index++) {
  64266. var task = this.tasks[index];
  64267. this._runTask(task);
  64268. }
  64269. return this;
  64270. };
  64271. return AssetsManager;
  64272. }());
  64273. BABYLON.AssetsManager = AssetsManager;
  64274. })(BABYLON || (BABYLON = {}));
  64275. //# sourceMappingURL=babylon.assetsManager.js.map
  64276. var BABYLON;
  64277. (function (BABYLON) {
  64278. var MapTexture = (function (_super) {
  64279. __extends(MapTexture, _super);
  64280. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  64281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64282. if (useMipMap === void 0) { useMipMap = false; }
  64283. if (margin === void 0) { margin = 0; }
  64284. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  64285. _this.name = name;
  64286. _this._size = size;
  64287. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64288. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64289. // Create the rectPackMap that will allocate portion of the texture
  64290. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  64291. // Create the texture that will store the content
  64292. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  64293. return _this;
  64294. }
  64295. /**
  64296. * Allocate a rectangle of a given size in the texture map
  64297. * @param size the size of the rectangle to allocation
  64298. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  64299. */
  64300. MapTexture.prototype.allocateRect = function (size) {
  64301. return this._rectPackingMap.addRect(size);
  64302. };
  64303. /**
  64304. * Free a given rectangle from the texture map
  64305. * @param rectInfo the instance corresponding to the rect to free.
  64306. */
  64307. MapTexture.prototype.freeRect = function (rectInfo) {
  64308. if (rectInfo) {
  64309. rectInfo.freeContent();
  64310. }
  64311. };
  64312. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  64313. /**
  64314. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  64315. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  64316. * @returns {}
  64317. */
  64318. get: function () {
  64319. return this._rectPackingMap.freeSpace;
  64320. },
  64321. enumerable: true,
  64322. configurable: true
  64323. });
  64324. /**
  64325. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  64326. * 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.
  64327. * Don't forget to call unbindTexture when you're done rendering
  64328. * @param rect the zone to render to
  64329. * @param clear true to clear the portion's color/depth data
  64330. */
  64331. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  64332. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  64333. };
  64334. /**
  64335. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  64336. * 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.
  64337. * Don't forget to call unbindTexture when you're done rendering
  64338. * @param pos the position into the texture
  64339. * @param size the portion to fit the clip space to
  64340. * @param clear true to clear the portion's color/depth data
  64341. */
  64342. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  64343. var engine = this.getScene().getEngine();
  64344. engine.bindFramebuffer(this._texture);
  64345. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  64346. if (clear) {
  64347. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  64348. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  64349. }
  64350. };
  64351. /**
  64352. * Unbind the texture map from the rendering engine.
  64353. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  64354. * @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.
  64355. */
  64356. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  64357. // Dump ?
  64358. if (dumpForDebug) {
  64359. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  64360. }
  64361. var engine = this.getScene().getEngine();
  64362. if (this._replacedViewport) {
  64363. engine.setViewport(this._replacedViewport);
  64364. this._replacedViewport = null;
  64365. }
  64366. engine.unBindFramebuffer(this._texture);
  64367. };
  64368. Object.defineProperty(MapTexture.prototype, "canRescale", {
  64369. get: function () {
  64370. return false;
  64371. },
  64372. enumerable: true,
  64373. configurable: true
  64374. });
  64375. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  64376. // Anyway, there's not much point to use this method for this kind of texture I guess
  64377. MapTexture.prototype.clone = function () {
  64378. return null;
  64379. };
  64380. return MapTexture;
  64381. }(BABYLON.Texture));
  64382. BABYLON.MapTexture = MapTexture;
  64383. })(BABYLON || (BABYLON = {}));
  64384. //# sourceMappingURL=babylon.mapTexture.js.map
  64385. var BABYLON;
  64386. (function (BABYLON) {
  64387. /**
  64388. * This class describe a rectangle that were added to the map.
  64389. * You have access to its coordinates either in pixel or normalized (UV)
  64390. */
  64391. var PackedRect = (function () {
  64392. function PackedRect(root, parent, pos, size) {
  64393. this._pos = pos;
  64394. this._size = size;
  64395. this._root = root;
  64396. this._parent = parent;
  64397. this._contentSize = null;
  64398. this._bottomNode = null;
  64399. this._leftNode = null;
  64400. this._initialSize = null;
  64401. this._rightNode = null;
  64402. }
  64403. Object.defineProperty(PackedRect.prototype, "pos", {
  64404. /**
  64405. * @returns the position of this node into the map
  64406. */
  64407. get: function () {
  64408. return this._pos;
  64409. },
  64410. enumerable: true,
  64411. configurable: true
  64412. });
  64413. Object.defineProperty(PackedRect.prototype, "contentSize", {
  64414. /**
  64415. * @returns the size of the rectangle this node handles
  64416. */
  64417. get: function () {
  64418. return this._contentSize;
  64419. },
  64420. enumerable: true,
  64421. configurable: true
  64422. });
  64423. /**
  64424. * Retrieve the inner position (considering the margin) and stores it into the res object
  64425. * @param res must be a valid Vector2 that will contain the inner position after this call
  64426. */
  64427. PackedRect.prototype.getInnerPosToRef = function (res) {
  64428. var m = this._root._margin;
  64429. res.x = this._pos.x + m;
  64430. res.y = this._pos.y + m;
  64431. };
  64432. /**
  64433. * Retrieve the inner size (considering the margin) and stores it into the res object
  64434. * @param res must be a valid Size that will contain the inner size after this call
  64435. */
  64436. PackedRect.prototype.getInnerSizeToRef = function (res) {
  64437. var m = this._root._margin;
  64438. res.width = this._contentSize.width - (m * 2);
  64439. res.height = this._contentSize.height - (m * 2);
  64440. };
  64441. Object.defineProperty(PackedRect.prototype, "UVs", {
  64442. /**
  64443. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  64444. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  64445. */
  64446. get: function () {
  64447. if (!this._contentSize) {
  64448. throw new Error("Can't compute UVs for this object because it's nor allocated");
  64449. }
  64450. return this.getUVsForCustomSize(this._contentSize);
  64451. },
  64452. enumerable: true,
  64453. configurable: true
  64454. });
  64455. /**
  64456. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  64457. * and then using only a part of the PackRect.
  64458. * This method will return the UVs for this part by given the custom size of what you really use
  64459. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  64460. */
  64461. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  64462. var mainWidth = this._root._size.width;
  64463. var mainHeight = this._root._size.height;
  64464. var margin = this._root._margin;
  64465. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  64466. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  64467. var uvs = new Array();
  64468. uvs.push(topLeft);
  64469. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  64470. uvs.push(rightBottom);
  64471. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  64472. return uvs;
  64473. };
  64474. /**
  64475. * Free this rectangle from the map.
  64476. * Call this method when you no longer need the rectangle to be in the map.
  64477. */
  64478. PackedRect.prototype.freeContent = function () {
  64479. if (!this.contentSize) {
  64480. return;
  64481. }
  64482. this._contentSize = null;
  64483. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  64484. this.attemptDefrag();
  64485. };
  64486. Object.defineProperty(PackedRect.prototype, "isUsed", {
  64487. get: function () {
  64488. return this._contentSize != null || this._leftNode != null;
  64489. },
  64490. enumerable: true,
  64491. configurable: true
  64492. });
  64493. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  64494. var node = this.findNode(contentSize);
  64495. // Not enough space...
  64496. if (!node) {
  64497. return null;
  64498. }
  64499. node.splitNode(contentSize);
  64500. return node;
  64501. };
  64502. PackedRect.prototype.findNode = function (size) {
  64503. var resNode = null;
  64504. var margin = this._root._margin * 2;
  64505. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  64506. if (this.isUsed) {
  64507. if (this._leftNode) {
  64508. resNode = this._leftNode.findNode(size);
  64509. }
  64510. if (!resNode && this._rightNode) {
  64511. resNode = this._rightNode.findNode(size);
  64512. }
  64513. if (!resNode && this._bottomNode) {
  64514. resNode = this._bottomNode.findNode(size);
  64515. }
  64516. }
  64517. else if (this._initialSize) {
  64518. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  64519. resNode = this;
  64520. }
  64521. else {
  64522. return null;
  64523. }
  64524. }
  64525. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  64526. resNode = this;
  64527. }
  64528. return resNode;
  64529. };
  64530. PackedRect.prototype.splitNode = function (contentSize) {
  64531. var cs = PackedRect.TpsSize;
  64532. var margin = this._root._margin * 2;
  64533. cs.copyFrom(contentSize);
  64534. cs.width += margin;
  64535. cs.height += margin;
  64536. // 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)
  64537. if (!this._contentSize && this._initialSize) {
  64538. this._contentSize = cs.clone();
  64539. 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));
  64540. return this._leftNode.splitNode(contentSize);
  64541. }
  64542. else {
  64543. this._contentSize = cs.clone();
  64544. this._initialSize = cs.clone();
  64545. if (cs.width !== this._size.width) {
  64546. 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));
  64547. }
  64548. if (cs.height !== this._size.height) {
  64549. 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));
  64550. }
  64551. return this;
  64552. }
  64553. };
  64554. PackedRect.prototype.attemptDefrag = function () {
  64555. if (!this.isUsed && this.isRecursiveFree) {
  64556. this.clearNode();
  64557. if (this._parent) {
  64558. this._parent.attemptDefrag();
  64559. }
  64560. }
  64561. };
  64562. PackedRect.prototype.clearNode = function () {
  64563. this._initialSize = null;
  64564. this._rightNode = null;
  64565. this._bottomNode = null;
  64566. };
  64567. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  64568. get: function () {
  64569. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  64570. },
  64571. enumerable: true,
  64572. configurable: true
  64573. });
  64574. PackedRect.prototype.evalFreeSize = function (size) {
  64575. var levelSize = 0;
  64576. if (!this.isUsed) {
  64577. var margin = this._root._margin;
  64578. var is = this._initialSize;
  64579. if (is) {
  64580. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  64581. }
  64582. else {
  64583. var size_1 = this._size;
  64584. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  64585. }
  64586. }
  64587. if (this._rightNode) {
  64588. levelSize += this._rightNode.evalFreeSize(0);
  64589. }
  64590. if (this._bottomNode) {
  64591. levelSize += this._bottomNode.evalFreeSize(0);
  64592. }
  64593. return levelSize + size;
  64594. };
  64595. return PackedRect;
  64596. }());
  64597. PackedRect.TpsSize = BABYLON.Size.Zero();
  64598. BABYLON.PackedRect = PackedRect;
  64599. /**
  64600. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  64601. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  64602. * 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.
  64603. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  64604. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  64605. */
  64606. var RectPackingMap = (function (_super) {
  64607. __extends(RectPackingMap, _super);
  64608. /**
  64609. * Create an instance of the object with a dimension using the given size
  64610. * @param size The dimension of the rectangle that will contain all the sub ones.
  64611. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  64612. */
  64613. function RectPackingMap(size, margin) {
  64614. if (margin === void 0) { margin = 0; }
  64615. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  64616. _this._margin = margin;
  64617. _this._root = _this;
  64618. return _this;
  64619. }
  64620. /**
  64621. * Add a rectangle, finding the best location to store it into the map
  64622. * @param size the dimension of the rectangle to store
  64623. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  64624. */
  64625. RectPackingMap.prototype.addRect = function (size) {
  64626. var node = this.findAndSplitNode(size);
  64627. return node;
  64628. };
  64629. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  64630. /**
  64631. * Return the current space free normalized between [0;1]
  64632. * @returns {}
  64633. */
  64634. get: function () {
  64635. var freeSize = 0;
  64636. freeSize = this.evalFreeSize(freeSize);
  64637. return freeSize / (this._size.width * this._size.height);
  64638. },
  64639. enumerable: true,
  64640. configurable: true
  64641. });
  64642. return RectPackingMap;
  64643. }(PackedRect));
  64644. BABYLON.RectPackingMap = RectPackingMap;
  64645. })(BABYLON || (BABYLON = {}));
  64646. //# sourceMappingURL=babylon.rectPackingMap.js.map
  64647. var BABYLON;
  64648. (function (BABYLON) {
  64649. var serializedGeometries = [];
  64650. var serializeGeometry = function (geometry, serializationGeometries) {
  64651. if (serializedGeometries[geometry.id]) {
  64652. return;
  64653. }
  64654. if (geometry.doNotSerialize) {
  64655. return;
  64656. }
  64657. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  64658. serializationGeometries.boxes.push(geometry.serialize());
  64659. }
  64660. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  64661. serializationGeometries.spheres.push(geometry.serialize());
  64662. }
  64663. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  64664. serializationGeometries.cylinders.push(geometry.serialize());
  64665. }
  64666. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  64667. serializationGeometries.toruses.push(geometry.serialize());
  64668. }
  64669. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  64670. serializationGeometries.grounds.push(geometry.serialize());
  64671. }
  64672. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  64673. serializationGeometries.planes.push(geometry.serialize());
  64674. }
  64675. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  64676. serializationGeometries.torusKnots.push(geometry.serialize());
  64677. }
  64678. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  64679. throw new Error("Unknown primitive type");
  64680. }
  64681. else {
  64682. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  64683. }
  64684. serializedGeometries[geometry.id] = true;
  64685. };
  64686. var serializeMesh = function (mesh, serializationScene) {
  64687. var serializationObject = {};
  64688. // Geometry
  64689. var geometry = mesh._geometry;
  64690. if (geometry) {
  64691. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  64692. // 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
  64693. serializeGeometry(geometry, serializationScene.geometries);
  64694. }
  64695. }
  64696. // Custom
  64697. if (mesh.serialize) {
  64698. mesh.serialize(serializationObject);
  64699. }
  64700. return serializationObject;
  64701. };
  64702. var finalizeSingleMesh = function (mesh, serializationObject) {
  64703. //only works if the mesh is already loaded
  64704. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  64705. //serialize material
  64706. if (mesh.material) {
  64707. if (mesh.material instanceof BABYLON.StandardMaterial) {
  64708. serializationObject.materials = serializationObject.materials || [];
  64709. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  64710. serializationObject.materials.push(mesh.material.serialize());
  64711. }
  64712. }
  64713. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  64714. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  64715. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  64716. serializationObject.multiMaterials.push(mesh.material.serialize());
  64717. }
  64718. }
  64719. }
  64720. //serialize geometry
  64721. var geometry = mesh._geometry;
  64722. if (geometry) {
  64723. if (!serializationObject.geometries) {
  64724. serializationObject.geometries = {};
  64725. serializationObject.geometries.boxes = [];
  64726. serializationObject.geometries.spheres = [];
  64727. serializationObject.geometries.cylinders = [];
  64728. serializationObject.geometries.toruses = [];
  64729. serializationObject.geometries.grounds = [];
  64730. serializationObject.geometries.planes = [];
  64731. serializationObject.geometries.torusKnots = [];
  64732. serializationObject.geometries.vertexData = [];
  64733. }
  64734. serializeGeometry(geometry, serializationObject.geometries);
  64735. }
  64736. // Skeletons
  64737. if (mesh.skeleton) {
  64738. serializationObject.skeletons = serializationObject.skeletons || [];
  64739. serializationObject.skeletons.push(mesh.skeleton.serialize());
  64740. }
  64741. //serialize the actual mesh
  64742. serializationObject.meshes = serializationObject.meshes || [];
  64743. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  64744. }
  64745. };
  64746. var SceneSerializer = (function () {
  64747. function SceneSerializer() {
  64748. }
  64749. SceneSerializer.ClearCache = function () {
  64750. serializedGeometries = [];
  64751. };
  64752. SceneSerializer.Serialize = function (scene) {
  64753. var serializationObject = {};
  64754. SceneSerializer.ClearCache();
  64755. // Scene
  64756. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  64757. serializationObject.autoClear = scene.autoClear;
  64758. serializationObject.clearColor = scene.clearColor.asArray();
  64759. serializationObject.ambientColor = scene.ambientColor.asArray();
  64760. serializationObject.gravity = scene.gravity.asArray();
  64761. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  64762. serializationObject.workerCollisions = scene.workerCollisions;
  64763. // Fog
  64764. if (scene.fogMode && scene.fogMode !== 0) {
  64765. serializationObject.fogMode = scene.fogMode;
  64766. serializationObject.fogColor = scene.fogColor.asArray();
  64767. serializationObject.fogStart = scene.fogStart;
  64768. serializationObject.fogEnd = scene.fogEnd;
  64769. serializationObject.fogDensity = scene.fogDensity;
  64770. }
  64771. //Physics
  64772. if (scene.isPhysicsEnabled()) {
  64773. serializationObject.physicsEnabled = true;
  64774. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  64775. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  64776. }
  64777. // Metadata
  64778. if (scene.metadata) {
  64779. serializationObject.metadata = scene.metadata;
  64780. }
  64781. // Morph targets
  64782. serializationObject.morphTargetManagers = [];
  64783. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  64784. var abstractMesh = _a[_i];
  64785. var manager = abstractMesh.morphTargetManager;
  64786. if (manager) {
  64787. serializationObject.morphTargetManagers.push(manager.serialize());
  64788. }
  64789. }
  64790. // Lights
  64791. serializationObject.lights = [];
  64792. var index;
  64793. var light;
  64794. for (index = 0; index < scene.lights.length; index++) {
  64795. light = scene.lights[index];
  64796. if (!light.doNotSerialize) {
  64797. serializationObject.lights.push(light.serialize());
  64798. }
  64799. }
  64800. // Cameras
  64801. serializationObject.cameras = [];
  64802. for (index = 0; index < scene.cameras.length; index++) {
  64803. var camera = scene.cameras[index];
  64804. if (!camera.doNotSerialize) {
  64805. serializationObject.cameras.push(camera.serialize());
  64806. }
  64807. }
  64808. if (scene.activeCamera) {
  64809. serializationObject.activeCameraID = scene.activeCamera.id;
  64810. }
  64811. // Animations
  64812. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  64813. // Materials
  64814. serializationObject.materials = [];
  64815. serializationObject.multiMaterials = [];
  64816. var material;
  64817. for (index = 0; index < scene.materials.length; index++) {
  64818. material = scene.materials[index];
  64819. if (!material.doNotSerialize) {
  64820. serializationObject.materials.push(material.serialize());
  64821. }
  64822. }
  64823. // MultiMaterials
  64824. serializationObject.multiMaterials = [];
  64825. for (index = 0; index < scene.multiMaterials.length; index++) {
  64826. var multiMaterial = scene.multiMaterials[index];
  64827. serializationObject.multiMaterials.push(multiMaterial.serialize());
  64828. }
  64829. // Skeletons
  64830. serializationObject.skeletons = [];
  64831. for (index = 0; index < scene.skeletons.length; index++) {
  64832. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  64833. }
  64834. // Geometries
  64835. serializationObject.geometries = {};
  64836. serializationObject.geometries.boxes = [];
  64837. serializationObject.geometries.spheres = [];
  64838. serializationObject.geometries.cylinders = [];
  64839. serializationObject.geometries.toruses = [];
  64840. serializationObject.geometries.grounds = [];
  64841. serializationObject.geometries.planes = [];
  64842. serializationObject.geometries.torusKnots = [];
  64843. serializationObject.geometries.vertexData = [];
  64844. serializedGeometries = [];
  64845. var geometries = scene.getGeometries();
  64846. for (index = 0; index < geometries.length; index++) {
  64847. var geometry = geometries[index];
  64848. if (geometry.isReady()) {
  64849. serializeGeometry(geometry, serializationObject.geometries);
  64850. }
  64851. }
  64852. // Meshes
  64853. serializationObject.meshes = [];
  64854. for (index = 0; index < scene.meshes.length; index++) {
  64855. var abstractMesh = scene.meshes[index];
  64856. if (abstractMesh instanceof BABYLON.Mesh) {
  64857. var mesh = abstractMesh;
  64858. if (!mesh.doNotSerialize) {
  64859. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  64860. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  64861. }
  64862. }
  64863. }
  64864. }
  64865. // Particles Systems
  64866. serializationObject.particleSystems = [];
  64867. for (index = 0; index < scene.particleSystems.length; index++) {
  64868. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  64869. }
  64870. // Lens flares
  64871. serializationObject.lensFlareSystems = [];
  64872. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  64873. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  64874. }
  64875. // Shadows
  64876. serializationObject.shadowGenerators = [];
  64877. for (index = 0; index < scene.lights.length; index++) {
  64878. light = scene.lights[index];
  64879. var shadowGenerator = light.getShadowGenerator();
  64880. if (shadowGenerator) {
  64881. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  64882. }
  64883. }
  64884. // Action Manager
  64885. if (scene.actionManager) {
  64886. serializationObject.actions = scene.actionManager.serialize("scene");
  64887. }
  64888. // Audio
  64889. serializationObject.sounds = [];
  64890. for (index = 0; index < scene.soundTracks.length; index++) {
  64891. var soundtrack = scene.soundTracks[index];
  64892. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  64893. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  64894. }
  64895. }
  64896. return serializationObject;
  64897. };
  64898. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  64899. if (withParents === void 0) { withParents = false; }
  64900. if (withChildren === void 0) { withChildren = false; }
  64901. var serializationObject = {};
  64902. SceneSerializer.ClearCache();
  64903. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  64904. if (withParents || withChildren) {
  64905. //deliberate for loop! not for each, appended should be processed as well.
  64906. for (var i = 0; i < toSerialize.length; ++i) {
  64907. if (withChildren) {
  64908. toSerialize[i].getDescendants().forEach(function (node) {
  64909. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  64910. toSerialize.push(node);
  64911. }
  64912. });
  64913. }
  64914. //make sure the array doesn't contain the object already
  64915. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  64916. toSerialize.push(toSerialize[i].parent);
  64917. }
  64918. }
  64919. }
  64920. toSerialize.forEach(function (mesh) {
  64921. finalizeSingleMesh(mesh, serializationObject);
  64922. });
  64923. return serializationObject;
  64924. };
  64925. return SceneSerializer;
  64926. }());
  64927. BABYLON.SceneSerializer = SceneSerializer;
  64928. })(BABYLON || (BABYLON = {}));
  64929. //# sourceMappingURL=babylon.sceneSerializer.js.map
  64930. var BABYLON;
  64931. (function (BABYLON) {
  64932. var ReflectionProbe = (function () {
  64933. function ReflectionProbe(name, size, scene, generateMipMaps) {
  64934. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64935. var _this = this;
  64936. this.name = name;
  64937. this._viewMatrix = BABYLON.Matrix.Identity();
  64938. this._target = BABYLON.Vector3.Zero();
  64939. this._add = BABYLON.Vector3.Zero();
  64940. this.invertYAxis = false;
  64941. this.position = BABYLON.Vector3.Zero();
  64942. this._scene = scene;
  64943. this._scene.reflectionProbes.push(this);
  64944. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  64945. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  64946. switch (faceIndex) {
  64947. case 0:
  64948. _this._add.copyFromFloats(1, 0, 0);
  64949. break;
  64950. case 1:
  64951. _this._add.copyFromFloats(-1, 0, 0);
  64952. break;
  64953. case 2:
  64954. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  64955. break;
  64956. case 3:
  64957. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  64958. break;
  64959. case 4:
  64960. _this._add.copyFromFloats(0, 0, 1);
  64961. break;
  64962. case 5:
  64963. _this._add.copyFromFloats(0, 0, -1);
  64964. break;
  64965. }
  64966. if (_this._attachedMesh) {
  64967. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  64968. }
  64969. _this.position.addToRef(_this._add, _this._target);
  64970. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  64971. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  64972. });
  64973. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  64974. scene.updateTransformMatrix(true);
  64975. });
  64976. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  64977. }
  64978. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  64979. get: function () {
  64980. return this._renderTargetTexture.samples;
  64981. },
  64982. set: function (value) {
  64983. this._renderTargetTexture.samples = value;
  64984. },
  64985. enumerable: true,
  64986. configurable: true
  64987. });
  64988. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  64989. get: function () {
  64990. return this._renderTargetTexture.refreshRate;
  64991. },
  64992. set: function (value) {
  64993. this._renderTargetTexture.refreshRate = value;
  64994. },
  64995. enumerable: true,
  64996. configurable: true
  64997. });
  64998. ReflectionProbe.prototype.getScene = function () {
  64999. return this._scene;
  65000. };
  65001. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  65002. get: function () {
  65003. return this._renderTargetTexture;
  65004. },
  65005. enumerable: true,
  65006. configurable: true
  65007. });
  65008. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  65009. get: function () {
  65010. return this._renderTargetTexture.renderList;
  65011. },
  65012. enumerable: true,
  65013. configurable: true
  65014. });
  65015. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  65016. this._attachedMesh = mesh;
  65017. };
  65018. ReflectionProbe.prototype.dispose = function () {
  65019. var index = this._scene.reflectionProbes.indexOf(this);
  65020. if (index !== -1) {
  65021. // Remove from the scene if found
  65022. this._scene.reflectionProbes.splice(index, 1);
  65023. }
  65024. if (this._renderTargetTexture) {
  65025. this._renderTargetTexture.dispose();
  65026. this._renderTargetTexture = null;
  65027. }
  65028. };
  65029. return ReflectionProbe;
  65030. }());
  65031. BABYLON.ReflectionProbe = ReflectionProbe;
  65032. })(BABYLON || (BABYLON = {}));
  65033. //# sourceMappingURL=babylon.reflectionProbe.js.map
  65034. var BABYLON;
  65035. (function (BABYLON) {
  65036. var Layer = (function () {
  65037. function Layer(name, imgUrl, scene, isBackground, color) {
  65038. this.name = name;
  65039. this.scale = new BABYLON.Vector2(1, 1);
  65040. this.offset = new BABYLON.Vector2(0, 0);
  65041. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  65042. this.layerMask = 0x0FFFFFFF;
  65043. this._vertexBuffers = {};
  65044. // Events
  65045. /**
  65046. * An event triggered when the layer is disposed.
  65047. * @type {BABYLON.Observable}
  65048. */
  65049. this.onDisposeObservable = new BABYLON.Observable();
  65050. /**
  65051. * An event triggered before rendering the scene
  65052. * @type {BABYLON.Observable}
  65053. */
  65054. this.onBeforeRenderObservable = new BABYLON.Observable();
  65055. /**
  65056. * An event triggered after rendering the scene
  65057. * @type {BABYLON.Observable}
  65058. */
  65059. this.onAfterRenderObservable = new BABYLON.Observable();
  65060. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  65061. this.isBackground = isBackground === undefined ? true : isBackground;
  65062. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  65063. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65064. this._scene.layers.push(this);
  65065. var engine = this._scene.getEngine();
  65066. // VBO
  65067. var vertices = [];
  65068. vertices.push(1, 1);
  65069. vertices.push(-1, 1);
  65070. vertices.push(-1, -1);
  65071. vertices.push(1, -1);
  65072. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65073. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  65074. // Indices
  65075. var indices = [];
  65076. indices.push(0);
  65077. indices.push(1);
  65078. indices.push(2);
  65079. indices.push(0);
  65080. indices.push(2);
  65081. indices.push(3);
  65082. this._indexBuffer = engine.createIndexBuffer(indices);
  65083. // Effects
  65084. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  65085. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  65086. }
  65087. Object.defineProperty(Layer.prototype, "onDispose", {
  65088. set: function (callback) {
  65089. if (this._onDisposeObserver) {
  65090. this.onDisposeObservable.remove(this._onDisposeObserver);
  65091. }
  65092. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  65093. },
  65094. enumerable: true,
  65095. configurable: true
  65096. });
  65097. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  65098. set: function (callback) {
  65099. if (this._onBeforeRenderObserver) {
  65100. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65101. }
  65102. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65103. },
  65104. enumerable: true,
  65105. configurable: true
  65106. });
  65107. Object.defineProperty(Layer.prototype, "onAfterRender", {
  65108. set: function (callback) {
  65109. if (this._onAfterRenderObserver) {
  65110. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65111. }
  65112. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65113. },
  65114. enumerable: true,
  65115. configurable: true
  65116. });
  65117. Layer.prototype.render = function () {
  65118. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  65119. // Check
  65120. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  65121. return;
  65122. var engine = this._scene.getEngine();
  65123. this.onBeforeRenderObservable.notifyObservers(this);
  65124. // Render
  65125. engine.enableEffect(currentEffect);
  65126. engine.setState(false);
  65127. // Texture
  65128. currentEffect.setTexture("textureSampler", this.texture);
  65129. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  65130. // Color
  65131. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  65132. // Scale / offset
  65133. currentEffect.setVector2("offset", this.offset);
  65134. currentEffect.setVector2("scale", this.scale);
  65135. // VBOs
  65136. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  65137. // Draw order
  65138. if (!this.alphaTest) {
  65139. engine.setAlphaMode(this.alphaBlendingMode);
  65140. engine.draw(true, 0, 6);
  65141. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65142. }
  65143. else {
  65144. engine.draw(true, 0, 6);
  65145. }
  65146. this.onAfterRenderObservable.notifyObservers(this);
  65147. };
  65148. Layer.prototype.dispose = function () {
  65149. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65150. if (vertexBuffer) {
  65151. vertexBuffer.dispose();
  65152. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65153. }
  65154. if (this._indexBuffer) {
  65155. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65156. this._indexBuffer = null;
  65157. }
  65158. if (this.texture) {
  65159. this.texture.dispose();
  65160. this.texture = null;
  65161. }
  65162. // Remove from scene
  65163. var index = this._scene.layers.indexOf(this);
  65164. this._scene.layers.splice(index, 1);
  65165. // Callback
  65166. this.onDisposeObservable.notifyObservers(this);
  65167. this.onDisposeObservable.clear();
  65168. this.onAfterRenderObservable.clear();
  65169. this.onBeforeRenderObservable.clear();
  65170. };
  65171. return Layer;
  65172. }());
  65173. BABYLON.Layer = Layer;
  65174. })(BABYLON || (BABYLON = {}));
  65175. //# sourceMappingURL=babylon.layer.js.map
  65176. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef MICROSURFACEMAP\nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP)|| !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) \nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#ifdef ALPHAFROMALBEDO\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#if defined(ALPHATEST) && defined(ALPHATESTVALUE)\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\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#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\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;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\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#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\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\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nlightingInfo info;\nfloat shadow=1.; \n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 lightDiffuseContribution=diffuseBase;\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=specularBase*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\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=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=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 EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=lightDiffuseContribution;\n#ifndef EMISSIVEASILLUMINATION\nfinalDiffuse+=surfaceEmissiveColor;\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\nfloat luminanceOverAlpha=0.0;\n#ifdef RADIANCEOVERALPHA\nluminanceOverAlpha+=getLuminance(environmentRadiance);\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nluminanceOverAlpha+=getLuminance(finalSpecular);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nfinalSpecular*=vLightingIntensity.x;\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*alpha,0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular+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\n#ifdef LDROUTPUT\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#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nuniform vec2 biasAndScale;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5; \n#endif\ndepth+=biasAndScale.x;\n#ifdef ESM\ndepth=exp(-min(87.,biasAndScale.y*depth));\n#endif\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","geometryVertexShader":"#version 300 es\nprecision highp float;\nprecision highp int;\n#include<bones300Declaration>\n#include<instances300Declaration>\nin vec3 position;\nin vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nout vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nin vec2 uv;\n#endif\n#ifdef UV2\nin vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nout vec3 vNormalV;\nout vec4 vViewPos;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*finalWorld*vec4(position,1.0);\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}","geometryPixelShader":"#version 300 es\nprecision highp float;\nprecision highp int;\nin vec3 vNormalV;\nin vec4 vViewPos;\n#ifdef ALPHATEST\nin vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nlayout(location=0) out vec4 color0;\nlayout(location=1) out vec4 color1;\nvoid main() {\n#ifdef ALPHATEST\nif (texture(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ncolor0=vec4(vViewPos.z/vViewPos.w,0.0,0.0,0.0);\ncolor1=vec4(normalize(vNormalV),1.0);\n\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nvec2 sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nvec2 sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nvec2 sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nvec2 sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nvec2 sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nvec2 sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nvec2 sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst float GammaEncodePowerApprox=1.0/2.2;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nuniform float contrast;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\nuniform float cameraExposureLinear;\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color)\n{\nfloat sliceSize=2.0*colorTransformSettings.y; \nfloat sliceContinuous=(color.y-colorTransformSettings.y)*colorTransformSettings.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\nvec2 sliceUV=color.xz;\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=result.bgr;\nreturn color;\n}\nvec4 applyImageProcessing(vec4 result,vec2 viewportXY){\nresult.rgb*=cameraExposureLinear;\n\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#ifdef TONEMAPPING \nfloat tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\nresult.rgb=pow(result.rgb,vec3(GammaEncodePowerApprox));\nresult.rgb=clamp(result.rgb,0.0,1.0);\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n\nfloat luma=dot(result.rgb,RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\nreturn result;\n}\nvoid main(void) \n{\nvec4 result=texture2D(textureSampler,vUV);\nvec2 viewportXY=vUV*2.0-1.0;\nresult=applyImageProcessing(result,viewportXY);\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nvoid main(void)\n{\nvec4 blend=vec4(0.);\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\ngl_FragColor=blend;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}"};
  65177. 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(SHADOWCUBE{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec3 shadowsInfo;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\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\nreturn min(1.0,visibility+darkness);\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.); \nreturn esm;\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{\nreturn darkness;\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\nreturn min(1.0,visibility+darkness);\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\nreturn esm;\n}\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\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#ifdef NORMALXYSCALE\nnormalW=normalize(normalW*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\n#else\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec2 vMicrosurfaceTextureLods;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform vec4 opacityParts;\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=max(0.00000000001,dot(vNormal,directionToLightCenterW));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"blend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n","kernelBlurFragment2":"blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  65178. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  65179. module.exports = BABYLON;
  65180. };